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"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
36#include <bitset>
37
38using namespace llvm;
39using namespace PatternMatch;
40
41#define DEBUG_TYPE "instcombine"
42
43// How many times is a select replaced by one of its operands?
44STATISTIC(NumSel, "Number of select opts");
45
46/// Compute Result = In1+In2, returning true if the result overflowed for this
47/// type.
48static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
49 bool IsSigned = false) {
50 bool Overflow;
51 if (IsSigned)
52 Result = In1.sadd_ov(In2, Overflow);
53 else
54 Result = In1.uadd_ov(In2, Overflow);
55
56 return Overflow;
57}
58
59/// Compute Result = In1-In2, returning true if the result overflowed for this
60/// type.
61static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
62 bool IsSigned = false) {
63 bool Overflow;
64 if (IsSigned)
65 Result = In1.ssub_ov(In2, Overflow);
66 else
67 Result = In1.usub_ov(In2, Overflow);
68
69 return Overflow;
70}
71
72/// Given an icmp instruction, return true if any use of this comparison is a
73/// branch on sign bit comparison.
74static bool hasBranchUse(ICmpInst &I) {
75 for (auto *U : I.users())
76 if (isa<CondBrInst>(U))
77 return true;
78 return false;
79}
80
81/// Returns true if the exploded icmp can be expressed as a signed comparison
82/// to zero and updates the predicate accordingly.
83/// The signedness of the comparison is preserved.
84/// TODO: Refactor with decomposeBitTestICmp()?
85static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
86 if (!ICmpInst::isSigned(Pred))
87 return false;
88
89 if (C.isZero())
90 return ICmpInst::isRelational(Pred);
91
92 if (C.isOne()) {
93 if (Pred == ICmpInst::ICMP_SLT) {
94 Pred = ICmpInst::ICMP_SLE;
95 return true;
96 }
97 } else if (C.isAllOnes()) {
98 if (Pred == ICmpInst::ICMP_SGT) {
99 Pred = ICmpInst::ICMP_SGE;
100 return true;
101 }
102 }
103
104 return false;
105}
106
107/// This is called when we see this pattern:
108/// cmp pred (load (gep GV, ...)), cmpcst
109/// where GV is a global variable with a constant initializer. Try to simplify
110/// this into some simple computation that does not need the load. For example
111/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
112///
113/// If AndCst is non-null, then the loaded value is masked with that constant
114/// before doing the comparison. This handles cases like "A[i]&4 == 0".
115///
116/// We allow multi-use cases in this fold, even though it can increase
117/// instruction count, because it appears to be mostly beneficial in practice.
118/// Even if there are multiple uses, they can often be sunk into the block
119/// guarded by the icmp.
122 Instruction &CtxI, ConstantInt *AndCst) {
124 if (LI->isVolatile() || !GV || !GV->isConstant() ||
125 !GV->hasDefinitiveInitializer())
126 return nullptr;
127
128 Type *EltTy = LI->getType();
129 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
130 if (EltSize.isScalable())
131 return nullptr;
132
134 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
135 return nullptr;
136
137 Constant *Init = GV->getInitializer();
138 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
139
140 Value *Idx = Expr.Index;
141 const APInt &Stride = Expr.Scale;
142 const APInt &ConstOffset = Expr.Offset;
143
144 // Allow an additional context offset, but only within the stride.
145 if (!ConstOffset.ult(Stride))
146 return nullptr;
147
148 // Don't handle overlapping loads for now.
149 if (!Stride.uge(EltSize.getFixedValue()))
150 return nullptr;
151
152 // With nusw (implied by inbounds), Idx * Stride does not wrap as a signed
153 // quantity, and the following enumeration over ArrayElementCount is valid so
154 // long as the stride is positive. Conversely, without nusw, Idx * Stride is
155 // computed modulo 2^N (see MaskIdx below), and the masking in MaskIdx below
156 // is only exact when the stride is a power of two.
157 bool StrideIsValid = Expr.Flags.hasNoUnsignedSignedWrap()
158 ? !Stride.isNegative()
159 : Stride.isPowerOf2();
160 if (!StrideIsValid)
161 return nullptr;
162
163 // Don't blow up on huge arrays.
164 uint64_t ArrayElementCount =
165 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
166 Stride.getZExtValue());
167 if (ArrayElementCount > CLOpts.maxarray_size)
168 return nullptr;
169
170 enum { Overdefined = -3, Undefined = -2 };
171
172 // Variables for our state machines.
173
174 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
175 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
176 // and 87 is the second (and last) index. FirstTrueElement is -2 when
177 // undefined, otherwise set to the first true element. SecondTrueElement is
178 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
179 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
180
181 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
182 // form "i != 47 & i != 87". Same state transitions as for true elements.
183 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
184
185 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
186 /// define a state machine that triggers for ranges of values that the index
187 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
188 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
189 /// index in the range (inclusive). We use -2 for undefined here because we
190 /// use relative comparisons and don't want 0-1 to match -1.
191 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
192
193 // MagicBitvector - This is a magic bitvector where we set a bit if the
194 // comparison is true for element 'i'. If there are 64 elements or less in
195 // the array, this will fully represent all the comparison results.
196 uint64_t MagicBitvector = 0;
197
198 // Scan the array and see if one of our patterns matches.
199 APInt Offset = ConstOffset;
200 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
202 if (!Elt)
203 return nullptr;
204
205 // If the element is masked, handle it.
206 if (AndCst) {
207 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
208 if (!Elt)
209 return nullptr;
210 }
211
212 // Find out if the comparison would be true or false for the i'th element.
213 Constant *C = ConstantFoldCompareInstOperands(Pred, Elt, RHSC, DL, &TLI);
214 if (!C)
215 return nullptr;
216
217 // If the result is undef for this element, ignore it.
218 if (isa<UndefValue>(C)) {
219 // Extend range state machines to cover this element in case there is an
220 // undef in the middle of the range.
221 if (TrueRangeEnd == (int)i - 1)
222 TrueRangeEnd = i;
223 if (FalseRangeEnd == (int)i - 1)
224 FalseRangeEnd = i;
225 continue;
226 }
227
228 // If we can't compute the result for any of the elements, we have to give
229 // up evaluating the entire conditional.
230 if (!isa<ConstantInt>(C))
231 return nullptr;
232
233 // Otherwise, we know if the comparison is true or false for this element,
234 // update our state machines.
235 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
236
237 // State machine for single/double/range index comparison.
238 if (IsTrueForElt) {
239 // Update the TrueElement state machine.
240 if (FirstTrueElement == Undefined)
241 FirstTrueElement = TrueRangeEnd = i; // First true element.
242 else {
243 // Update double-compare state machine.
244 if (SecondTrueElement == Undefined)
245 SecondTrueElement = i;
246 else
247 SecondTrueElement = Overdefined;
248
249 // Update range state machine.
250 if (TrueRangeEnd == (int)i - 1)
251 TrueRangeEnd = i;
252 else
253 TrueRangeEnd = Overdefined;
254 }
255 } else {
256 // Update the FalseElement state machine.
257 if (FirstFalseElement == Undefined)
258 FirstFalseElement = FalseRangeEnd = i; // First false element.
259 else {
260 // Update double-compare state machine.
261 if (SecondFalseElement == Undefined)
262 SecondFalseElement = i;
263 else
264 SecondFalseElement = Overdefined;
265
266 // Update range state machine.
267 if (FalseRangeEnd == (int)i - 1)
268 FalseRangeEnd = i;
269 else
270 FalseRangeEnd = Overdefined;
271 }
272 }
273
274 // If this element is in range, update our magic bitvector.
275 if (i < 64 && IsTrueForElt)
276 MagicBitvector |= 1ULL << i;
277
278 // If all of our states become overdefined, bail out early. Since the
279 // predicate is expensive, only check it every 8 elements. This is only
280 // really useful for really huge arrays.
281 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
282 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
283 FalseRangeEnd == Overdefined)
284 return nullptr;
285 }
286
287 // Now that we've scanned the entire array, emit our new comparison(s). We
288 // order the state machines in complexity of the generated code.
289
290 // If inbounds keyword is not present, Idx * Stride can overflow.
291 // Let's assume that Stride is 2 and the wanted value is at offset 0.
292 // Then, there are two possible values for Idx to match offset 0:
293 // 0x00..00, 0x80..00.
294 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
295 // comparison is false if Idx was 0x80..00.
296 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
297 auto MaskIdx = [&](Value *Idx) {
298 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
299 Value *Mask = Constant::getAllOnesValue(Idx->getType());
300 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
301 Idx = Builder.CreateAnd(Idx, Mask);
302 }
303 return Idx;
304 };
305
306 // If the comparison is only true for one or two elements, emit direct
307 // comparisons.
308 if (SecondTrueElement != Overdefined) {
309 Idx = MaskIdx(Idx);
310 // None true -> false.
311 if (FirstTrueElement == Undefined)
312 return replaceInstUsesWith(CtxI, Builder.getFalse());
313
314 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
315
316 // True for one element -> 'i == 47'.
317 if (SecondTrueElement == Undefined)
318 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
319
320 // True for two elements -> 'i == 47 | i == 72'.
321 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
322 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
323 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
324 return BinaryOperator::CreateOr(C1, C2);
325 }
326
327 // If the comparison is only false for one or two elements, emit direct
328 // comparisons.
329 if (SecondFalseElement != Overdefined) {
330 Idx = MaskIdx(Idx);
331 // None false -> true.
332 if (FirstFalseElement == Undefined)
333 return replaceInstUsesWith(CtxI, Builder.getTrue());
334
335 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
336
337 // False for one element -> 'i != 47'.
338 if (SecondFalseElement == Undefined)
339 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
340
341 // False for two elements -> 'i != 47 & i != 72'.
342 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
343 Value *SecondFalseIdx =
344 ConstantInt::get(Idx->getType(), SecondFalseElement);
345 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
346 return BinaryOperator::CreateAnd(C1, C2);
347 }
348
349 // If the comparison can be replaced with a range comparison for the elements
350 // where it is true, emit the range check.
351 if (TrueRangeEnd != Overdefined) {
352 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
353 Idx = MaskIdx(Idx);
354
355 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
356 if (FirstTrueElement) {
357 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
358 Idx = Builder.CreateAdd(Idx, Offs);
359 }
360
361 Value *End =
362 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
363 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
364 }
365
366 // False range check.
367 if (FalseRangeEnd != Overdefined) {
368 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
369 Idx = MaskIdx(Idx);
370 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
371 if (FirstFalseElement) {
372 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
373 Idx = Builder.CreateAdd(Idx, Offs);
374 }
375
376 Value *End =
377 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
378 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
379 }
380
381 // If a magic bitvector captures the entire comparison state
382 // of this load, replace it with computation that does:
383 // ((magic_cst >> i) & 1) != 0
384 {
385 Type *Ty = nullptr;
386
387 // Look for an appropriate type:
388 // - The type of Idx if the magic fits
389 // - The smallest fitting legal type
390 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
391 Ty = Idx->getType();
392 else
393 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
394
395 if (Ty) {
396 Idx = MaskIdx(Idx);
397 Value *V = Builder.CreateIntCast(Idx, Ty, false);
398 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
399 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
400 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
401 }
402 }
403
404 return nullptr;
405}
406
407/// Returns true if we can rewrite Start as a GEP with pointer Base
408/// and some integer offset. The nodes that need to be re-written
409/// for this transformation will be added to Explored.
411 const DataLayout &DL,
412 SetVector<Value *> &Explored) {
413 SmallVector<Value *, 16> WorkList(1, Start);
414 Explored.insert(Base);
415
416 // The following traversal gives us an order which can be used
417 // when doing the final transformation. Since in the final
418 // transformation we create the PHI replacement instructions first,
419 // we don't have to get them in any particular order.
420 //
421 // However, for other instructions we will have to traverse the
422 // operands of an instruction first, which means that we have to
423 // do a post-order traversal.
424 while (!WorkList.empty()) {
426
427 while (!WorkList.empty()) {
428 if (Explored.size() >= 100)
429 return false;
430
431 Value *V = WorkList.back();
432
433 if (Explored.contains(V)) {
434 WorkList.pop_back();
435 continue;
436 }
437
439 // We've found some value that we can't explore which is different from
440 // the base. Therefore we can't do this transformation.
441 return false;
442
443 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
444 // Only allow inbounds GEPs with at most one variable offset.
445 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
446 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
447 return false;
448
449 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
450 if (!Explored.contains(GEP->getOperand(0)))
451 WorkList.push_back(GEP->getOperand(0));
452 }
453
454 if (WorkList.back() == V) {
455 WorkList.pop_back();
456 // We've finished visiting this node, mark it as such.
457 Explored.insert(V);
458 }
459
460 if (auto *PN = dyn_cast<PHINode>(V)) {
461 // We cannot transform PHIs on unsplittable basic blocks.
462 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
463 return false;
464 Explored.insert(PN);
465 PHIs.insert(PN);
466 }
467 }
468
469 // Explore the PHI nodes further.
470 for (auto *PN : PHIs)
471 for (Value *Op : PN->incoming_values())
472 if (!Explored.contains(Op))
473 WorkList.push_back(Op);
474 }
475
476 // Make sure that we can do this. Since we can't insert GEPs in a basic
477 // block before a PHI node, we can't easily do this transformation if
478 // we have PHI node users of transformed instructions.
479 for (Value *Val : Explored) {
480 for (Value *Use : Val->uses()) {
481
482 auto *PHI = dyn_cast<PHINode>(Use);
483 auto *Inst = dyn_cast<Instruction>(Val);
484
485 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
486 !Explored.contains(PHI))
487 continue;
488
489 if (PHI->getParent() == Inst->getParent())
490 return false;
491 }
492 }
493 return true;
494}
495
496// Sets the appropriate insert point on Builder where we can add
497// a replacement Instruction for V (if that is possible).
498static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
499 bool Before = true) {
500 if (auto *PHI = dyn_cast<PHINode>(V)) {
501 BasicBlock *Parent = PHI->getParent();
502 Builder.SetInsertPoint(Parent->getFirstInsertionPt());
503 return;
504 }
505 if (auto *I = dyn_cast<Instruction>(V)) {
506 if (!Before)
507 I = &*std::next(I->getIterator());
508 Builder.SetInsertPoint(I);
509 return;
510 }
511 if (auto *A = dyn_cast<Argument>(V)) {
512 // Set the insertion point in the entry block.
513 BasicBlock &Entry = A->getParent()->getEntryBlock();
514 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
515 return;
516 }
517 // Otherwise, this is a constant and we don't need to set a new
518 // insertion point.
519 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
520}
521
522/// Returns a re-written value of Start as an indexed GEP using Base as a
523/// pointer.
525 const DataLayout &DL,
526 SetVector<Value *> &Explored,
527 InstCombiner &IC) {
528 // Perform all the substitutions. This is a bit tricky because we can
529 // have cycles in our use-def chains.
530 // 1. Create the PHI nodes without any incoming values.
531 // 2. Create all the other values.
532 // 3. Add the edges for the PHI nodes.
533 // 4. Emit GEPs to get the original pointers.
534 // 5. Remove the original instructions.
535 Type *IndexType = IntegerType::get(
536 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
537
539 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
540
541 // Create the new PHI nodes, without adding any incoming values.
542 for (Value *Val : Explored) {
543 if (Val == Base)
544 continue;
545 // Create empty phi nodes. This avoids cyclic dependencies when creating
546 // the remaining instructions.
547 if (auto *PHI = dyn_cast<PHINode>(Val))
548 NewInsts[PHI] =
549 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
550 PHI->getName() + ".idx", PHI->getIterator());
551 }
552 IRBuilder<> Builder(IC.getModule());
553
554 // Create all the other instructions.
555 for (Value *Val : Explored) {
556 if (NewInsts.contains(Val))
557 continue;
558
559 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
560 setInsertionPoint(Builder, GEP);
561 Value *Op = NewInsts[GEP->getOperand(0)];
562 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
564 NewInsts[GEP] = OffsetV;
565 else
566 NewInsts[GEP] = Builder.CreateAdd(
567 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
568 /*NUW=*/NW.hasNoUnsignedWrap(),
569 /*NSW=*/NW.hasNoUnsignedSignedWrap());
570 continue;
571 }
572 if (isa<PHINode>(Val))
573 continue;
574
575 llvm_unreachable("Unexpected instruction type");
576 }
577
578 // Add the incoming values to the PHI nodes.
579 for (Value *Val : Explored) {
580 if (Val == Base)
581 continue;
582 // All the instructions have been created, we can now add edges to the
583 // phi nodes.
584 if (auto *PHI = dyn_cast<PHINode>(Val)) {
585 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
586 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
587 Value *NewIncoming = PHI->getIncomingValue(I);
588
589 auto It = NewInsts.find(NewIncoming);
590 if (It != NewInsts.end())
591 NewIncoming = It->second;
592
593 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
594 }
595 }
596 }
597
598 for (Value *Val : Explored) {
599 if (Val == Base)
600 continue;
601
602 setInsertionPoint(Builder, Val, false);
603 // Create GEP for external users.
604 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
605 Val->getName() + ".ptr", NW);
606 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
607 // Add old instruction to worklist for DCE. We don't directly remove it
608 // here because the original compare is one of the users.
610 }
611
612 return NewInsts[Start];
613}
614
615/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
616/// We can look through PHIs, GEPs and casts in order to determine a common base
617/// between GEPLHS and RHS.
620 const DataLayout &DL,
621 InstCombiner &IC) {
622 // FIXME: Support vector of pointers.
623 if (GEPLHS->getType()->isVectorTy())
624 return nullptr;
625
626 if (!GEPLHS->hasAllConstantIndices())
627 return nullptr;
628
629 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
630 Value *PtrBase =
632 /*AllowNonInbounds*/ false);
633
634 // Bail if we looked through addrspacecast.
635 if (PtrBase->getType() != GEPLHS->getType())
636 return nullptr;
637
638 // The set of nodes that will take part in this transformation.
639 SetVector<Value *> Nodes;
640 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
641 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
642 return nullptr;
643
644 // We know we can re-write this as
645 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
646 // Since we've only looked through inbouds GEPs we know that we
647 // can't have overflow on either side. We can therefore re-write
648 // this as:
649 // OFFSET1 cmp OFFSET2
650 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
651
652 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
653 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
654 // offset. Since Index is the offset of LHS to the base pointer, we will now
655 // compare the offsets instead of comparing the pointers.
657 IC.Builder.getInt(Offset), NewRHS);
658}
659
660/// Fold comparisons between a GEP instruction and something else. At this point
661/// we know that the GEP is on the LHS of the comparison.
664 // Don't transform signed compares of GEPs into index compares. Even if the
665 // GEP is inbounds, the final add of the base pointer can have signed overflow
666 // and would change the result of the icmp.
667 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
668 // the maximum signed value for the pointer type.
670 return nullptr;
671
672 // Look through bitcasts and addrspacecasts. We do not however want to remove
673 // 0 GEPs.
674 if (!isa<GetElementPtrInst>(RHS))
675 RHS = RHS->stripPointerCasts();
676
677 auto CanFold = [Cond](GEPNoWrapFlags NW) {
679 return true;
680
681 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
683 return NW != GEPNoWrapFlags::none();
684 };
685
686 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
687 if (!NW.hasNoUnsignedWrap()) {
688 // Convert signed to unsigned comparison.
689 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
690 }
691
692 auto *I = new ICmpInst(Cond, Op1, Op2);
693 I->setSameSign(NW.hasNoUnsignedSignedWrap());
694 return I;
695 };
696
698 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
699 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
700 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
701 Value *Offset =
702 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
703 return NewICmp(Base.LHSNW, Offset,
704 Constant::getNullValue(Offset->getType()));
705 }
706
707 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
709 !NullPointerIsDefined(I.getFunction(),
710 RHS->getType()->getPointerAddressSpace())) {
711 // For most address spaces, an allocation can't be placed at null, but null
712 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
713 // the only valid inbounds address derived from null, is null itself.
714 // Thus, we have four cases to consider:
715 // 1) Base == nullptr, Offset == 0 -> inbounds, null
716 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
717 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
718 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
719 //
720 // (Note if we're indexing a type of size 0, that simply collapses into one
721 // of the buckets above.)
722 //
723 // In general, we're allowed to make values less poison (i.e. remove
724 // sources of full UB), so in this case, we just select between the two
725 // non-poison cases (1 and 4 above).
726 //
727 // For vectors, we apply the same reasoning on a per-lane basis.
728 auto *Base = GEPLHS->getPointerOperand();
729 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
730 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
731 Base = Builder.CreateVectorSplat(EC, Base);
732 }
733 return new ICmpInst(Cond, Base,
735 cast<Constant>(RHS), Base->getType()));
736 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
737 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
738
739 // If the base pointers are different, but the indices are the same, just
740 // compare the base pointer.
741 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
742 bool IndicesTheSame =
743 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
744 GEPLHS->getPointerOperand()->getType() ==
745 GEPRHS->getPointerOperand()->getType() &&
746 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
747 if (IndicesTheSame)
748 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
749 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
750 IndicesTheSame = false;
751 break;
752 }
753
754 // If all indices are the same, just compare the base pointers.
755 Type *BaseType = GEPLHS->getOperand(0)->getType();
756 if (IndicesTheSame &&
757 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
758 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
759
760 // If we're comparing GEPs with two base pointers that only differ in type
761 // and both GEPs have only constant indices or just one use, then fold
762 // the compare with the adjusted indices.
763 // FIXME: Support vector of pointers.
764 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
765 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
766 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
767 GEPLHS->getOperand(0)->stripPointerCasts() ==
768 GEPRHS->getOperand(0)->stripPointerCasts() &&
769 !GEPLHS->getType()->isVectorTy()) {
770 Value *LOffset = EmitGEPOffset(GEPLHS);
771 Value *ROffset = EmitGEPOffset(GEPRHS);
772
773 // If we looked through an addrspacecast between different sized address
774 // spaces, the LHS and RHS pointers are different sized
775 // integers. Truncate to the smaller one.
776 Type *LHSIndexTy = LOffset->getType();
777 Type *RHSIndexTy = ROffset->getType();
778 if (LHSIndexTy != RHSIndexTy) {
779 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
780 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
781 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
782 } else
783 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
784 }
785
787 LOffset, ROffset);
788 return replaceInstUsesWith(I, Cmp);
789 }
790 }
791
792 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
793 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
794 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
795 // If the GEPs only differ by one index, compare it.
796 unsigned NumDifferences = 0; // Keep track of # differences.
797 unsigned DiffOperand = 0; // The operand that differs.
798 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
799 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
800 Type *LHSType = GEPLHS->getOperand(i)->getType();
801 Type *RHSType = GEPRHS->getOperand(i)->getType();
802 // FIXME: Better support for vector of pointers.
803 if (LHSType->getPrimitiveSizeInBits() !=
804 RHSType->getPrimitiveSizeInBits() ||
805 (GEPLHS->getType()->isVectorTy() &&
806 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
807 // Irreconcilable differences.
808 NumDifferences = 2;
809 break;
810 }
811
812 if (NumDifferences++)
813 break;
814 DiffOperand = i;
815 }
816
817 if (NumDifferences == 0) // SAME GEP?
818 return replaceInstUsesWith(
819 I, // No comparison is needed here.
820 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
821 // If two GEPs only differ by an index, compare them.
822 // Note that nowrap flags are always needed when comparing two indices.
823 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
824 Value *LHSV = GEPLHS->getOperand(DiffOperand);
825 Value *RHSV = GEPRHS->getOperand(DiffOperand);
826 return NewICmp(NW, LHSV, RHSV);
827 }
828 }
829
830 if (Base.Ptr && !Base.isExpensive()) {
831 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
832 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
833
834 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
835 // Without the flags, we can still fold if the offsets are constant and
836 // they cross the base's alignment boundary the same number of times, so
837 // either both arguments will wrap, or none of them will.
838 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
839 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
840 APInt LOff(BW, 0);
841 APInt ROff(BW, 0);
843 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
844 RHS->stripAndAccumulateConstantOffsets(
845 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
846 DoFold =
849 }
850
851 if (DoFold) {
852 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
853 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
854 /*RewriteGEP=*/true);
855 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
856 /*RewriteGEP=*/true);
857 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
858 }
859 }
860 }
861
862 // Try convert this to an indexed compare by looking through PHIs/casts as a
863 // last resort.
864 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
865}
866
868 // It would be tempting to fold away comparisons between allocas and any
869 // pointer not based on that alloca (e.g. an argument). However, even
870 // though such pointers cannot alias, they can still compare equal.
871 //
872 // But LLVM doesn't specify where allocas get their memory, so if the alloca
873 // doesn't escape we can argue that it's impossible to guess its value, and we
874 // can therefore act as if any such guesses are wrong.
875 //
876 // However, we need to ensure that this folding is consistent: We can't fold
877 // one comparison to false, and then leave a different comparison against the
878 // same value alone (as it might evaluate to true at runtime, leading to a
879 // contradiction). As such, this code ensures that all comparisons are folded
880 // at the same time, and there are no other escapes.
881
882 struct CmpCaptureTracker : public CaptureTracker {
883 AllocaInst *Alloca;
884 bool Captured = false;
885 /// The value of the map is a bit mask of which icmp operands the alloca is
886 /// used in.
888
889 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
890
891 void tooManyUses() override { Captured = true; }
892
893 Action captured(const Use *U, UseCaptureInfo CI) override {
894 // TODO(captures): Use UseCaptureInfo.
895 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
896 // We need to check that U is based *only* on the alloca, and doesn't
897 // have other contributions from a select/phi operand.
898 // TODO: We could check whether getUnderlyingObjects() reduces to one
899 // object, which would allow looking through phi nodes.
900 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
901 // Collect equality icmps of the alloca, and don't treat them as
902 // captures.
903 ICmps[ICmp] |= 1u << U->getOperandNo();
904 return Continue;
905 }
906
907 Captured = true;
908 return Stop;
909 }
910 };
911
912 CmpCaptureTracker Tracker(Alloca);
913 PointerMayBeCaptured(Alloca, &Tracker);
914 if (Tracker.Captured)
915 return false;
916
917 bool Changed = false;
918 for (auto [ICmp, Operands] : Tracker.ICmps) {
919 switch (Operands) {
920 case 1:
921 case 2: {
922 // The alloca is only used in one icmp operand. Assume that the
923 // equality is false.
924 auto *Res = ConstantInt::get(ICmp->getType(),
925 ICmp->getPredicate() == ICmpInst::ICMP_NE);
926 replaceInstUsesWith(*ICmp, Res);
928 Changed = true;
929 break;
930 }
931 case 3:
932 // Both icmp operands are based on the alloca, so this is comparing
933 // pointer offsets, without leaking any information about the address
934 // of the alloca. Ignore such comparisons.
935 break;
936 default:
937 llvm_unreachable("Cannot happen");
938 }
939 }
940
941 return Changed;
942}
943
944/// Fold "icmp pred (X+C), X".
946 CmpPredicate Pred) {
947 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
948 // so the values can never be equal. Similarly for all other "or equals"
949 // operators.
950 assert(!!C && "C should not be zero!");
951
952 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
953 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
954 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
955 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
956 Constant *R =
957 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
958 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
959 }
960
961 // (X+1) >u X --> X <u (0-1) --> X != 255
962 // (X+2) >u X --> X <u (0-2) --> X <u 254
963 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
964 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
965 return new ICmpInst(ICmpInst::ICMP_ULT, X,
966 ConstantInt::get(X->getType(), -C));
967
968 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
969
970 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
971 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
972 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
973 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
974 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
975 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
976 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
977 return new ICmpInst(ICmpInst::ICMP_SGT, X,
978 ConstantInt::get(X->getType(), SMax - C));
979
980 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
981 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
982 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
983 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
984 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
985 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
986
987 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
988 return new ICmpInst(ICmpInst::ICMP_SLT, X,
989 ConstantInt::get(X->getType(), SMax - (C - 1)));
990}
991
992/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
993/// (icmp eq/ne A, Log2(AP2/AP1)) ->
994/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
996 const APInt &AP1,
997 const APInt &AP2) {
998 assert(I.isEquality() && "Cannot fold icmp gt/lt");
999
1000 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1001 if (I.getPredicate() == I.ICMP_NE)
1002 Pred = CmpInst::getInversePredicate(Pred);
1003 return new ICmpInst(Pred, LHS, RHS);
1004 };
1005
1006 // Don't bother doing any work for cases which InstSimplify handles.
1007 if (AP2.isZero())
1008 return nullptr;
1009
1010 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1011 if (IsAShr) {
1012 if (AP2.isAllOnes())
1013 return nullptr;
1014 if (AP2.isNegative() != AP1.isNegative())
1015 return nullptr;
1016 if (AP2.sgt(AP1))
1017 return nullptr;
1018 }
1019
1020 if (!AP1)
1021 // 'A' must be large enough to shift out the highest set bit.
1022 return getICmp(I.ICMP_UGT, A,
1023 ConstantInt::get(A->getType(), AP2.logBase2()));
1024
1025 if (AP1 == AP2)
1026 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1027
1028 int Shift;
1029 if (IsAShr && AP1.isNegative())
1030 Shift = AP1.countl_one() - AP2.countl_one();
1031 else
1032 Shift = AP1.countl_zero() - AP2.countl_zero();
1033
1034 if (Shift > 0) {
1035 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1036 // There are multiple solutions if we are comparing against -1 and the LHS
1037 // of the ashr is not a power of two.
1038 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1039 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1040 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1041 } else if (AP1 == AP2.lshr(Shift)) {
1042 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1043 }
1044 }
1045
1046 // Shifting const2 will never be equal to const1.
1047 // FIXME: This should always be handled by InstSimplify?
1048 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1049 return replaceInstUsesWith(I, TorF);
1050}
1051
1052/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1053/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1055 const APInt &AP1,
1056 const APInt &AP2) {
1057 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1058
1059 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1060 if (I.getPredicate() == I.ICMP_NE)
1061 Pred = CmpInst::getInversePredicate(Pred);
1062 return new ICmpInst(Pred, LHS, RHS);
1063 };
1064
1065 // Don't bother doing any work for cases which InstSimplify handles.
1066 if (AP2.isZero())
1067 return nullptr;
1068
1069 unsigned AP2TrailingZeros = AP2.countr_zero();
1070
1071 if (!AP1 && AP2TrailingZeros != 0)
1072 return getICmp(
1073 I.ICMP_UGE, A,
1074 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1075
1076 if (AP1 == AP2)
1077 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1078
1079 // Get the distance between the lowest bits that are set.
1080 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1081
1082 if (Shift > 0 && AP2.shl(Shift) == AP1)
1083 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1084
1085 // Shifting const2 will never be equal to const1.
1086 // FIXME: This should always be handled by InstSimplify?
1087 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1088 return replaceInstUsesWith(I, TorF);
1089}
1090
1091/// The caller has matched a pattern of the form:
1092/// I = icmp ugt (add (add A, B), CI2), CI1
1093/// If this is of the form:
1094/// sum = a + b
1095/// if (sum+128 >u 255)
1096/// Then replace it with llvm.sadd.with.overflow.i8.
1097///
1099 ConstantInt *CI2, ConstantInt *CI1,
1100 InstCombinerImpl &IC) {
1101 // The transformation we're trying to do here is to transform this into an
1102 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1103 // with a narrower add, and discard the add-with-constant that is part of the
1104 // range check (if we can't eliminate it, this isn't profitable).
1105
1106 // In order to eliminate the add-with-constant, the compare can be its only
1107 // use.
1108 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1109 if (!AddWithCst->hasOneUse())
1110 return nullptr;
1111
1112 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1113 if (!CI2->getValue().isPowerOf2())
1114 return nullptr;
1115 unsigned NewWidth = CI2->getValue().countr_zero();
1116 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1117 return nullptr;
1118
1119 // The width of the new add formed is 1 more than the bias.
1120 ++NewWidth;
1121
1122 // Check to see that CI1 is an all-ones value with NewWidth bits.
1123 if (CI1->getBitWidth() == NewWidth ||
1124 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1125 return nullptr;
1126
1127 // This is only really a signed overflow check if the inputs have been
1128 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1129 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1130 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1131 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1132 return nullptr;
1133
1134 // In order to replace the original add with a narrower
1135 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1136 // and truncates that discard the high bits of the add. Verify that this is
1137 // the case.
1138 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1139 for (User *U : OrigAdd->users()) {
1140 if (U == AddWithCst)
1141 continue;
1142
1143 // Only accept truncates for now. We would really like a nice recursive
1144 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1145 // chain to see which bits of a value are actually demanded. If the
1146 // original add had another add which was then immediately truncated, we
1147 // could still do the transformation.
1149 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1150 return nullptr;
1151 }
1152
1153 // If the pattern matches, truncate the inputs to the narrower type and
1154 // use the sadd_with_overflow intrinsic to efficiently compute both the
1155 // result and the overflow bit.
1156 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1158 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1159
1160 InstCombiner::BuilderTy &Builder = IC.Builder;
1161
1162 // Put the new code above the original add, in case there are any uses of the
1163 // add between the add and the compare.
1164 Builder.SetInsertPoint(OrigAdd);
1165
1166 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1167 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1168 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1169 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1170 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1171
1172 // The inner add was the result of the narrow add, zero extended to the
1173 // wider type. Replace it with the result computed by the intrinsic.
1174 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1175 IC.eraseInstFromFunction(*OrigAdd);
1176
1177 // The original icmp gets replaced with the overflow value.
1178 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1179}
1180
1181/// If we have:
1182/// icmp eq/ne (urem/srem %x, %y), 0
1183/// iff %y is a power-of-two, we can replace this with a bit test:
1184/// icmp eq/ne (and %x, (add %y, -1)), 0
1186 // This fold is only valid for equality predicates.
1187 if (!I.isEquality())
1188 return nullptr;
1189 CmpPredicate Pred;
1190 Value *X, *Y, *Zero;
1191 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1192 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1193 return nullptr;
1194 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1195 return nullptr;
1196 // This may increase instruction count, we don't enforce that Y is a constant.
1197 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1198 Value *Masked = Builder.CreateAnd(X, Mask);
1199 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1200}
1201
1202/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1203/// by one-less-than-bitwidth into a sign test on the original value.
1205 Instruction *Val;
1206 CmpPredicate Pred;
1207 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1208 return nullptr;
1209
1210 Value *X;
1211 Type *XTy;
1212
1213 Constant *C;
1214 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1215 XTy = X->getType();
1216 unsigned XBitWidth = XTy->getScalarSizeInBits();
1218 APInt(XBitWidth, XBitWidth - 1))))
1219 return nullptr;
1220 } else if (isa<BinaryOperator>(Val) &&
1222 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1223 /*AnalyzeForSignBitExtraction=*/true))) {
1224 XTy = X->getType();
1225 } else
1226 return nullptr;
1227
1228 return ICmpInst::Create(Instruction::ICmp,
1232}
1233
1234// Handle icmp pred X, 0
1236 CmpInst::Predicate Pred = Cmp.getPredicate();
1237 if (!match(Cmp.getOperand(1), m_Zero()))
1238 return nullptr;
1239
1240 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1241 if (Pred == ICmpInst::ICMP_SGT) {
1242 Value *A, *B;
1243 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1244 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1245 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1246 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1247 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1248 }
1249 }
1250
1252 return New;
1253
1254 // Given:
1255 // icmp eq/ne (urem %x, %y), 0
1256 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1257 // icmp eq/ne %x, 0
1258 Value *X, *Y;
1259 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1260 ICmpInst::isEquality(Pred)) {
1261 KnownBits XKnown = computeKnownBits(X, &Cmp);
1262 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1263 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1264 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1265 }
1266
1267 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1268 // odd/non-zero/there is no overflow.
1269 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1270 ICmpInst::isEquality(Pred)) {
1271
1272 KnownBits XKnown = computeKnownBits(X, &Cmp);
1273 // if X % 2 != 0
1274 // (icmp eq/ne Y)
1275 if (XKnown.countMaxTrailingZeros() == 0)
1276 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1277
1278 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1279 // if Y % 2 != 0
1280 // (icmp eq/ne X)
1281 if (YKnown.countMaxTrailingZeros() == 0)
1282 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1283
1284 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1285 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1286 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1287 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1288 // but to avoid unnecessary work, first just if this is an obvious case.
1289
1290 // if X non-zero and NoOverflow(X * Y)
1291 // (icmp eq/ne Y)
1292 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1293 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1294
1295 // if Y non-zero and NoOverflow(X * Y)
1296 // (icmp eq/ne X)
1297 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1298 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1299 }
1300 // Note, we are skipping cases:
1301 // if Y % 2 != 0 AND X % 2 != 0
1302 // (false/true)
1303 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1304 // (false/true)
1305 // Those can be simplified later as we would have already replaced the (icmp
1306 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1307 // will fold to a constant elsewhere.
1308 }
1309
1310 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1311 // where f(X) == 0 if and only if X == 0
1312 if (ICmpInst::isEquality(Pred))
1313 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1314 return new ICmpInst(Pred, Stripped,
1315 Constant::getNullValue(Stripped->getType()));
1316
1317 return nullptr;
1318}
1319
1320/// Fold icmp eq (num + mask) & ~mask, num
1321/// to
1322/// icmp eq (and num, mask), 0
1323/// Where mask is a low bit mask.
1325 Value *Num;
1326 CmpPredicate Pred;
1327 const APInt *Mask, *Neg;
1328
1329 if (!match(&Cmp,
1330 m_c_ICmp(Pred, m_Value(Num),
1332 m_LowBitMask(Mask))),
1333 m_APInt(Neg))))))
1334 return nullptr;
1335
1336 if (*Neg != ~*Mask)
1337 return nullptr;
1338
1339 if (!ICmpInst::isEquality(Pred))
1340 return nullptr;
1341
1342 // Create new icmp eq (num & mask), 0
1343 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1344 auto *Zero = Constant::getNullValue(Num->getType());
1345
1346 return new ICmpInst(Pred, NewAnd, Zero);
1347}
1348
1349/// Fold icmp Pred X, C.
1350/// TODO: This code structure does not make sense. The saturating add fold
1351/// should be moved to some other helper and extended as noted below (it is also
1352/// possible that code has been made unnecessary - do we canonicalize IR to
1353/// overflow/saturating intrinsics or not?).
1355 // Match the following pattern, which is a common idiom when writing
1356 // overflow-safe integer arithmetic functions. The source performs an addition
1357 // in wider type and explicitly checks for overflow using comparisons against
1358 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1359 //
1360 // TODO: This could probably be generalized to handle other overflow-safe
1361 // operations if we worked out the formulas to compute the appropriate magic
1362 // constants.
1363 //
1364 // sum = a + b
1365 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1366 CmpInst::Predicate Pred = Cmp.getPredicate();
1367 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1368 Value *A, *B;
1369 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1370 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1371 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1372 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1373 return Res;
1374
1375 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1377 if (!C)
1378 return nullptr;
1379
1380 if (auto *Phi = dyn_cast<PHINode>(Op0))
1381 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1383 for (Value *V : Phi->incoming_values()) {
1384 Constant *Res =
1386 if (!Res)
1387 return nullptr;
1388 Ops.push_back(Res);
1389 }
1390 Builder.SetInsertPoint(Phi);
1391 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1392 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1393 NewPhi->addIncoming(V, Pred);
1394 return replaceInstUsesWith(Cmp, NewPhi);
1395 }
1396
1398 return R;
1399
1400 return nullptr;
1401}
1402
1403/// Canonicalize icmp instructions based on dominating conditions.
1405 // We already checked simple implication in InstSimplify, only handle complex
1406 // cases here.
1407 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1408 const APInt *C;
1409 if (!match(Y, m_APInt(C)))
1410 return nullptr;
1411
1412 CmpInst::Predicate Pred = Cmp.getPredicate();
1414
1415 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1416 const APInt *DomC) -> Instruction * {
1417 // We have 2 compares of a variable with constants. Calculate the constant
1418 // ranges of those compares to see if we can transform the 2nd compare:
1419 // DomBB:
1420 // DomCond = icmp DomPred X, DomC
1421 // br DomCond, CmpBB, FalseBB
1422 // CmpBB:
1423 // Cmp = icmp Pred X, C
1424 ConstantRange DominatingCR =
1425 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1426 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1427 ConstantRange Difference = DominatingCR.difference(CR);
1428 if (Intersection.isEmptySet())
1429 return replaceInstUsesWith(Cmp, Builder.getFalse());
1430 if (Difference.isEmptySet())
1431 return replaceInstUsesWith(Cmp, Builder.getTrue());
1432
1433 // Canonicalizing a sign bit comparison that gets used in a branch,
1434 // pessimizes codegen by generating branch on zero instruction instead
1435 // of a test and branch. So we avoid canonicalizing in such situations
1436 // because test and branch instruction has better branch displacement
1437 // than compare and branch instruction.
1438 bool UnusedBit;
1439 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1440 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1441 return nullptr;
1442
1443 // Avoid an infinite loop with min/max canonicalization.
1444 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1445 if (Cmp.hasOneUse() &&
1446 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1447 return nullptr;
1448
1449 if (const APInt *EqC = Intersection.getSingleElement())
1450 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1451 if (const APInt *NeC = Difference.getSingleElement())
1452 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1453 return nullptr;
1454 };
1455
1456 for (CondBrInst *BI : DC.conditionsFor(X)) {
1457 CmpPredicate DomPred;
1458 const APInt *DomC;
1459 if (!match(BI->getCondition(),
1460 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1461 continue;
1462
1463 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1464 if (DT.dominates(Edge0, Cmp.getParent())) {
1465 if (auto *V = handleDomCond(DomPred, DomC))
1466 return V;
1467 } else {
1468 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1469 if (DT.dominates(Edge1, Cmp.getParent()))
1470 if (auto *V =
1471 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1472 return V;
1473 }
1474 }
1475
1476 return nullptr;
1477}
1478
1479/// Fold icmp (trunc X), C.
1481 TruncInst *Trunc,
1482 const APInt &C) {
1483 ICmpInst::Predicate Pred = Cmp.getPredicate();
1484 Value *X = Trunc->getOperand(0);
1485 Type *SrcTy = X->getType();
1486 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1487 SrcBits = SrcTy->getScalarSizeInBits();
1488
1489 // Match (icmp pred (trunc nuw/nsw X), C)
1490 // Which we can convert to (icmp pred X, (sext/zext C))
1491 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1492 if (Trunc->hasNoSignedWrap())
1493 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1494 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1495 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1496 }
1497
1498 if (C.isOne() && C.getBitWidth() > 1) {
1499 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1500 Value *V = nullptr;
1501 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1502 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1503 ConstantInt::get(V->getType(), 1));
1504 }
1505
1506 // TODO: Handle non-equality predicates.
1507 Value *Y;
1508 const APInt *Pow2;
1509 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1510 DstBits > Pow2->logBase2()) {
1511 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1512 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1513 // iff N > log2(Pow2)
1514 if (C.isZero()) {
1515 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1516 return new ICmpInst(NewPred, Y,
1517 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1518 }
1519 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1520 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1521 if (C.isPowerOf2())
1522 return new ICmpInst(
1523 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1524 }
1525
1526 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1527 // Canonicalize to a mask and wider compare if the wide type is suitable:
1528 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1529 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1530 Constant *Mask =
1531 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1532 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1533 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1534 return new ICmpInst(Pred, And, WideC);
1535 }
1536
1537 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1538 // of the high bits truncated out of x are known.
1540
1541 // If all the high bits are known, we can do this xform.
1542 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1543 // Pull in the high bits from known-ones set.
1544 APInt NewRHS = C.zext(SrcBits);
1545 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1546 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1547 }
1548 }
1549
1550 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1551 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1552 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1553 Value *ShOp;
1554 uint64_t ShAmt;
1555 bool TrueIfSigned;
1556 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1557 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1558 DstBits == SrcBits - ShAmt) {
1559 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1561 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1563 }
1564
1565 return nullptr;
1566}
1567
1568/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1569/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1572 const SimplifyQuery &Q) {
1573 Value *X, *Y;
1574 CmpPredicate Pred;
1575 bool YIsSExt = false;
1576 // Try to match icmp (trunc X), (trunc Y)
1577 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1578 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1579 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1580 if (Cmp.isSigned()) {
1581 // For signed comparisons, both truncs must be nsw.
1582 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1583 return nullptr;
1584 } else {
1585 // For unsigned and equality comparisons, either both must be nuw or
1586 // both must be nsw, we don't care which.
1587 if (!NoWrapFlags)
1588 return nullptr;
1589 }
1590
1591 if (X->getType() != Y->getType() &&
1592 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1593 return nullptr;
1594 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1595 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1596 std::swap(X, Y);
1597 Pred = Cmp.getSwappedPredicate(Pred);
1598 }
1599 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1600 }
1601 // Try to match icmp (trunc nuw X), (zext Y)
1602 else if (!Cmp.isSigned() &&
1603 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1604 m_OneUse(m_ZExt(m_Value(Y)))))) {
1605 // Can fold trunc nuw + zext for unsigned and equality predicates.
1606 }
1607 // Try to match icmp (trunc nsw X), (sext Y)
1608 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1610 // Can fold trunc nsw + zext/sext for all predicates.
1611 YIsSExt =
1612 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1613 } else
1614 return nullptr;
1615
1616 Type *TruncTy = Cmp.getOperand(0)->getType();
1617 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1618
1619 // If this transform will end up changing from desirable types -> undesirable
1620 // types skip it.
1621 if (isDesirableIntType(TruncBits) &&
1622 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1623 return nullptr;
1624
1625 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1626 return new ICmpInst(Pred, X, NewY);
1627}
1628
1629/// Fold icmp (xor X, Y), C.
1632 const APInt &C) {
1633 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1634 return I;
1635
1636 Value *X = Xor->getOperand(0);
1637 Value *Y = Xor->getOperand(1);
1638 const APInt *XorC;
1639 if (!match(Y, m_APInt(XorC)))
1640 return nullptr;
1641
1642 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1643 // fold the xor.
1644 ICmpInst::Predicate Pred = Cmp.getPredicate();
1645 bool TrueIfSigned = false;
1646 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1647
1648 // If the sign bit of the XorCst is not set, there is no change to
1649 // the operation, just stop using the Xor.
1650 if (!XorC->isNegative())
1651 return replaceOperand(Cmp, 0, X);
1652
1653 // Emit the opposite comparison.
1654 if (TrueIfSigned)
1655 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1656 ConstantInt::getAllOnesValue(X->getType()));
1657 else
1658 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1659 ConstantInt::getNullValue(X->getType()));
1660 }
1661
1662 if (Xor->hasOneUse()) {
1663 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1664 if (!Cmp.isEquality() && XorC->isSignMask()) {
1665 Pred = Cmp.getFlippedSignednessPredicate();
1666 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1667 }
1668
1669 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1670 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1671 Pred = Cmp.getFlippedSignednessPredicate();
1672 Pred = Cmp.getSwappedPredicate(Pred);
1673 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1674 }
1675 }
1676
1677 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1678 if (Pred == ICmpInst::ICMP_UGT) {
1679 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1680 if (*XorC == ~C && (C + 1).isPowerOf2())
1681 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1682 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1683 if (*XorC == C && (C + 1).isPowerOf2())
1684 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1685 }
1686 if (Pred == ICmpInst::ICMP_ULT) {
1687 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1688 if (*XorC == -C && C.isPowerOf2())
1689 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1690 ConstantInt::get(X->getType(), ~C));
1691 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1692 if (*XorC == C && (-C).isPowerOf2())
1693 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1694 ConstantInt::get(X->getType(), ~C));
1695 }
1696 return nullptr;
1697}
1698
1699/// For power-of-2 C:
1700/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1701/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1704 const APInt &C) {
1705 CmpInst::Predicate Pred = Cmp.getPredicate();
1706 APInt PowerOf2;
1707 if (Pred == ICmpInst::ICMP_ULT)
1708 PowerOf2 = C;
1709 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1710 PowerOf2 = C + 1;
1711 else
1712 return nullptr;
1713 if (!PowerOf2.isPowerOf2())
1714 return nullptr;
1715 Value *X;
1716 const APInt *ShiftC;
1718 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1719 return nullptr;
1720 uint64_t Shift = ShiftC->getLimitedValue();
1721 Type *XType = X->getType();
1722 if (Shift == 0 || PowerOf2.isMinSignedValue())
1723 return nullptr;
1724 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1725 APInt Bound =
1726 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1727 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1728}
1729
1730/// Fold icmp (and (sh X, Y), C2), C1.
1733 const APInt &C1,
1734 const APInt &C2) {
1735 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1736 if (!Shift || !Shift->isShift())
1737 return nullptr;
1738
1739 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1740 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1741 // code produced by the clang front-end, for bitfield access.
1742 // This seemingly simple opportunity to fold away a shift turns out to be
1743 // rather complicated. See PR17827 for details.
1744 unsigned ShiftOpcode = Shift->getOpcode();
1745 bool IsShl = ShiftOpcode == Instruction::Shl;
1746 const APInt *C3;
1747 if (match(Shift->getOperand(1), m_APInt(C3))) {
1748 APInt NewAndCst, NewCmpCst;
1749 bool AnyCmpCstBitsShiftedOut;
1750 if (ShiftOpcode == Instruction::Shl) {
1751 // For a left shift, we can fold if the comparison is not signed. We can
1752 // also fold a signed comparison if the mask value and comparison value
1753 // are not negative. These constraints may not be obvious, but we can
1754 // prove that they are correct using an SMT solver.
1755 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1756 return nullptr;
1757
1758 NewCmpCst = C1.lshr(*C3);
1759 NewAndCst = C2.lshr(*C3);
1760 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1761 } else if (ShiftOpcode == Instruction::LShr) {
1762 // For a logical right shift, we can fold if the comparison is not signed.
1763 // We can also fold a signed comparison if the shifted mask value and the
1764 // shifted comparison value are not negative. These constraints may not be
1765 // obvious, but we can prove that they are correct using an SMT solver.
1766 NewCmpCst = C1.shl(*C3);
1767 NewAndCst = C2.shl(*C3);
1768 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1769 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1770 return nullptr;
1771 } else {
1772 // For an arithmetic shift, check that both constants don't use (in a
1773 // signed sense) the top bits being shifted out.
1774 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1775 NewCmpCst = C1.shl(*C3);
1776 NewAndCst = C2.shl(*C3);
1777 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1778 if (NewAndCst.ashr(*C3) != C2)
1779 return nullptr;
1780 }
1781
1782 if (AnyCmpCstBitsShiftedOut) {
1783 // If we shifted bits out, the fold is not going to work out. As a
1784 // special case, check to see if this means that the result is always
1785 // true or false now.
1786 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1787 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1788 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1789 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1790 } else {
1791 Value *NewAnd = Builder.CreateAnd(
1792 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1793 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1794 ConstantInt::get(And->getType(), NewCmpCst));
1795 }
1796 }
1797
1798 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1799 // preferable because it allows the C2 << Y expression to be hoisted out of a
1800 // loop if Y is invariant and X is not.
1801 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1802 !Shift->isArithmeticShift() &&
1803 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1804 // Compute C2 << Y.
1805 Value *NewShift =
1806 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1807 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1808
1809 // Compute X & (C2 << Y).
1810 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1811 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1812 }
1813
1814 return nullptr;
1815}
1816
1817/// Fold icmp (and X, C2), C1.
1820 const APInt &C1) {
1821 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1822
1823 // icmp ne (and X, 1), 0 --> trunc X to i1
1824 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1825 return new TruncInst(And->getOperand(0), Cmp.getType());
1826
1827 const APInt *C2;
1828 Value *X;
1829 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1830 return nullptr;
1831
1832 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1833 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1834 C2->isNegatedPowerOf2())
1835 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1836 ConstantInt::get(X->getType(), ~*C2));
1837 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1838 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1839 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1840 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1841 ConstantInt::get(X->getType(), -*C2));
1842
1843 // Don't perform the following transforms if the AND has multiple uses
1844 if (!And->hasOneUse())
1845 return nullptr;
1846
1847 if (Cmp.isEquality() && C1.isZero()) {
1848 // Restrict this fold to single-use 'and' (PR10267).
1849 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1850 if (C2->isSignMask()) {
1851 Constant *Zero = Constant::getNullValue(X->getType());
1852 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1853 return new ICmpInst(NewPred, X, Zero);
1854 }
1855
1856 APInt NewC2 = *C2;
1857 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1858 // Set high zeros of C2 to allow matching negated power-of-2.
1859 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1860 Know.countMinLeadingZeros());
1861
1862 // Restrict this fold only for single-use 'and' (PR10267).
1863 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1864 if (NewC2.isNegatedPowerOf2()) {
1865 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1866 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1867 return new ICmpInst(NewPred, X, NegBOC);
1868 }
1869 }
1870
1871 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1872 // the input width without changing the value produced, eliminate the cast:
1873 //
1874 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1875 //
1876 // We can do this transformation if the constants do not have their sign bits
1877 // set or if it is an equality comparison. Extending a relational comparison
1878 // when we're checking the sign bit would not work.
1879 Value *W;
1880 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1881 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1882 // TODO: Is this a good transform for vectors? Wider types may reduce
1883 // throughput. Should this transform be limited (even for scalars) by using
1884 // shouldChangeType()?
1885 if (!Cmp.getType()->isVectorTy()) {
1886 Type *WideType = W->getType();
1887 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1888 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1889 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1890 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1891 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1892 }
1893 }
1894
1895 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1896 return I;
1897
1898 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1899 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1900 //
1901 // iff pred isn't signed
1902 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1903 match(And->getOperand(1), m_One())) {
1904 Constant *One = cast<Constant>(And->getOperand(1));
1905 Value *Or = And->getOperand(0);
1906 Value *A, *B, *LShr;
1907 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1908 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1909 unsigned UsesRemoved = 0;
1910 if (And->hasOneUse())
1911 ++UsesRemoved;
1912 if (Or->hasOneUse())
1913 ++UsesRemoved;
1914 if (LShr->hasOneUse())
1915 ++UsesRemoved;
1916
1917 // Compute A & ((1 << B) | 1)
1918 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1919 if (UsesRemoved >= RequireUsesRemoved) {
1920 Value *NewOr =
1921 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1922 /*HasNUW=*/true),
1923 One, Or->getName());
1924 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1925 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1926 }
1927 }
1928 }
1929
1930 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1931 // llvm.is.fpclass(X, fcInf|fcNan)
1932 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1933 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1934 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1935 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1936 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1937 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1938 Value *V;
1939 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1940 Attribute::NoImplicitFloat) &&
1941 Cmp.isEquality() &&
1943 Type *FPType = V->getType()->getScalarType();
1944 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1945 APInt ExponentMask =
1946 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1947 if (*C2 == ExponentMask) {
1948 unsigned Mask = C1.isZero()
1951 if (isICMP_NE)
1952 Mask = ~Mask & fcAllFlags;
1953 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1954 }
1955 }
1956 }
1957
1958 return nullptr;
1959}
1960
1961/// Fold icmp (and X, Y), C.
1964 const APInt &C) {
1965 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1966 return I;
1967
1968 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1969 bool TrueIfNeg;
1970 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1971 // ((X - 1) & ~X) < 0 --> X == 0
1972 // ((X - 1) & ~X) >= 0 --> X != 0
1973 Value *X;
1974 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1975 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1976 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1977 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1978 }
1979 // (X & -X) < 0 --> X == MinSignedC
1980 // (X & -X) > -1 --> X != MinSignedC
1981 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1982 Constant *MinSignedC = ConstantInt::get(
1983 X->getType(),
1984 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1985 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1986 return new ICmpInst(NewPred, X, MinSignedC);
1987 }
1988 }
1989
1990 // TODO: These all require that Y is constant too, so refactor with the above.
1991
1992 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1993 Value *X = And->getOperand(0);
1994 Value *Y = And->getOperand(1);
1995 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1996 if (auto *LI = dyn_cast<LoadInst>(X))
1997 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1999 LI, GEP, Cmp.getPredicate(), cast<Constant>(Cmp.getOperand(1)),
2000 Cmp, C2))
2001 return Res;
2002
2003 if (!Cmp.isEquality())
2004 return nullptr;
2005
2006 // (X & -X) == 0 --> X == 0
2007 // (X & -X) != 0 --> X != 0
2008 // (X & -X) == 1 --> trunc X to i1
2009 // (X & -X) != 1 --> !(trunc X to i1)
2010 // Cmp is == or != by the check above.
2011 Value *MatchedX;
2012 // Match X & -X in either operand order.
2013 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2014 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2015 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2016 if (C.isZero())
2017 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2018
2019 // (X & -X) == 1 iff the low bit of X is set.
2020 if (Pred == CmpInst::ICMP_EQ)
2021 return new TruncInst(MatchedX, Cmp.getType());
2022
2023 // The remaining case needs a trunc and not. Require the original and
2024 // to become dead to avoid increasing the instruction count.
2025 if (And->hasOneUse()) {
2026 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2027 return BinaryOperator::CreateNot(Trunc);
2028 }
2029 }
2030
2031 // X & -C == -C -> X > u ~C
2032 // X & -C != -C -> X <= u ~C
2033 // iff C is a power of 2
2034 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2035 auto NewPred =
2037 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2038 }
2039
2040 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2041 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2042 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2043 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2045 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2046 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2047 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2048 Value *And = Builder.CreateAnd(TruncY, X);
2050 }
2051 return BinaryOperator::CreateAnd(TruncY, X);
2052 }
2053
2054 // (icmp eq/ne (and (shl -1, X), Y), 0)
2055 // -> (icmp eq/ne (lshr Y, X), 0)
2056 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2057 // highly unlikely the non-zero case will ever show up in code.
2058 if (C.isZero() &&
2060 m_Value(Y))))) {
2061 Value *LShr = Builder.CreateLShr(Y, X);
2062 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2063 }
2064
2065 // (icmp eq/ne (and (add A, Addend), Msk), C)
2066 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2067 {
2068 Value *A;
2069 const APInt *Addend, *Msk;
2071 m_LowBitMask(Msk)))) &&
2072 C.ule(*Msk)) {
2073 APInt NewComperand = (C - *Addend) & *Msk;
2074 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2075 return new ICmpInst(Pred, MaskA,
2076 ConstantInt::get(MaskA->getType(), NewComperand));
2077 }
2078 }
2079
2080 return nullptr;
2081}
2082
2083/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2085 InstCombiner::BuilderTy &Builder) {
2086 // Are we using xors or subs to bitwise check for a pair or pairs of
2087 // (in)equalities? Convert to a shorter form that has more potential to be
2088 // folded even further.
2089 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2090 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2091 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2092 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2093 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2094 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2096 SmallVector<Value *, 16> WorkList(1, Or);
2097
2098 while (!WorkList.empty()) {
2099 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2100 Value *Lhs, *Rhs;
2101
2102 if (match(OrOperatorArgument,
2103 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2104 CmpValues.emplace_back(Lhs, Rhs);
2105 return;
2106 }
2107
2108 if (match(OrOperatorArgument,
2109 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2110 CmpValues.emplace_back(Lhs, Rhs);
2111 return;
2112 }
2113
2114 WorkList.push_back(OrOperatorArgument);
2115 };
2116
2117 Value *CurrentValue = WorkList.pop_back_val();
2118 Value *OrOperatorLhs, *OrOperatorRhs;
2119
2120 if (!match(CurrentValue,
2121 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2122 return nullptr;
2123 }
2124
2125 MatchOrOperatorArgument(OrOperatorRhs);
2126 MatchOrOperatorArgument(OrOperatorLhs);
2127 }
2128
2129 ICmpInst::Predicate Pred = Cmp.getPredicate();
2130 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2131 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2132 CmpValues.rbegin()->second);
2133
2134 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2135 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2136 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2137 }
2138
2139 return LhsCmp;
2140}
2141
2142/// Fold icmp (or X, Y), C.
2145 const APInt &C) {
2146 ICmpInst::Predicate Pred = Cmp.getPredicate();
2147 if (C.isOne()) {
2148 // icmp slt signum(V) 1 --> icmp slt V, 1
2149 Value *V = nullptr;
2150 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2151 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2152 ConstantInt::get(V->getType(), 1));
2153 }
2154
2155 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2156
2157 // (icmp eq/ne (or disjoint x, C0), C1)
2158 // -> (icmp eq/ne x, C0^C1)
2159 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2160 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2161 Value *NewC =
2162 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2163 return new ICmpInst(Pred, OrOp0, NewC);
2164 }
2165
2166 const APInt *MaskC;
2167 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2168 if (*MaskC == C && (C + 1).isPowerOf2()) {
2169 // X | C == C --> X <=u C
2170 // X | C != C --> X >u C
2171 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2173 return new ICmpInst(Pred, OrOp0, OrOp1);
2174 }
2175
2176 // More general: canonicalize 'equality with set bits mask' to
2177 // 'equality with clear bits mask'.
2178 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2179 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2180 if (Or->hasOneUse()) {
2181 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2182 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2183 return new ICmpInst(Pred, And, NewC);
2184 }
2185 }
2186
2187 // (X | (X-1)) s< 0 --> X s< 1
2188 // (X | (X-1)) s> -1 --> X s> 0
2189 Value *X;
2190 bool TrueIfSigned;
2191 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2193 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2194 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2195 return new ICmpInst(NewPred, X, NewC);
2196 }
2197
2198 const APInt *OrC;
2199 // icmp(X | OrC, C) --> icmp(X, 0)
2200 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2201 switch (Pred) {
2202 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2203 case ICmpInst::ICMP_SLT:
2204 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2205 case ICmpInst::ICMP_SGE:
2206 if (OrC->sge(C))
2207 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2208 break;
2209 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2210 case ICmpInst::ICMP_SLE:
2211 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2212 case ICmpInst::ICMP_SGT:
2213 if (OrC->sgt(C))
2215 ConstantInt::getNullValue(X->getType()));
2216 break;
2217 default:
2218 break;
2219 }
2220 }
2221
2222 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2223 return nullptr;
2224
2225 Value *P, *Q;
2227 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2228 // -> and (icmp eq P, null), (icmp eq Q, null).
2229 Value *CmpP =
2230 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2231 Value *CmpQ =
2232 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2233 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2234 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2235 }
2236
2237 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2238 return replaceInstUsesWith(Cmp, V);
2239
2240 return nullptr;
2241}
2242
2243/// Fold icmp (mul X, Y), C.
2246 const APInt &C) {
2247 ICmpInst::Predicate Pred = Cmp.getPredicate();
2248 Type *MulTy = Mul->getType();
2249 Value *X = Mul->getOperand(0);
2250
2251 // If comparing a square with a constant, try simplifying to comparing square
2252 // roots.
2253 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2254 APInt R = C.sqrtFloor();
2255 bool IsSqr = C == R * R;
2256
2257 // X * X eq/ne C
2258 if (Cmp.isEquality() &&
2259 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2260
2261 // If constant is not a square, eq/ne is false/true respectively
2262 if (!IsSqr)
2263 return replaceInstUsesWith(
2264 Cmp,
2265 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2266
2267 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2268 }
2269
2270 // If the multiply does not wrap
2271 // X * X pred C --> X pred R
2272 if (Mul->hasNoUnsignedWrap()) {
2273
2274 if (IsSqr)
2275 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2276
2277 // If C is not a square, we use floor/ceil of sqrt(C).
2278 //
2279 // If LT or LE, we need R to be an overestimate of sqrt(C),
2280 // then use the strict predicate (LT->LT, LE->LT).
2281 //
2282 // If GT or GE, we need R to be an underestimate of sqrt(C),
2283 // then use the strict predicate (GT->GT, GE->GT).
2284 //
2285 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2286 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2287 ++R;
2288
2289 return new ICmpInst(Cmp.getStrictPredicate(), X,
2290 ConstantInt::get(MulTy, R));
2291 }
2292 }
2293
2294 const APInt *MulC;
2295 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2296 return nullptr;
2297
2298 // If this is a test of the sign bit and the multiply is sign-preserving with
2299 // a constant operand, use the multiply LHS operand instead:
2300 // (X * +MulC) < 0 --> X < 0
2301 // (X * -MulC) < 0 --> X > 0
2302 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2303 if (MulC->isNegative())
2304 Pred = ICmpInst::getSwappedPredicate(Pred);
2305 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2306 }
2307
2308 if (MulC->isZero())
2309 return nullptr;
2310
2311 // If the multiply does not wrap or the constant is odd, try to divide the
2312 // compare constant by the multiplication factor.
2313 if (Cmp.isEquality()) {
2314 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2315 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2316 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2317 return new ICmpInst(Pred, X, NewC);
2318 }
2319
2320 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2321 // correct to transform if MulC * N == C including overflow. I.e with i8
2322 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2323 // miss that case.
2324 if (C.urem(*MulC).isZero()) {
2325 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2326 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2327 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2328 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2329 return new ICmpInst(Pred, X, NewC);
2330 }
2331 }
2332 }
2333
2334 // With a matching no-overflow guarantee, fold the constants:
2335 // (X * MulC) < C --> X < (C / MulC)
2336 // (X * MulC) > C --> X > (C / MulC)
2337 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2338 Constant *NewC = nullptr;
2339 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2340 // MININT / -1 --> overflow.
2341 if (C.isMinSignedValue() && MulC->isAllOnes())
2342 return nullptr;
2343 if (MulC->isNegative())
2344 Pred = ICmpInst::getSwappedPredicate(Pred);
2345
2346 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2347 NewC = ConstantInt::get(
2349 } else {
2350 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2351 "Unexpected predicate");
2352 NewC = ConstantInt::get(
2354 }
2355 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2356 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2357 NewC = ConstantInt::get(
2359 } else {
2360 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2361 "Unexpected predicate");
2362 NewC = ConstantInt::get(
2364 }
2365 }
2366
2367 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2368}
2369
2370/// Fold icmp (shl nuw C2, Y), C.
2372 const APInt &C) {
2373 Value *Y;
2374 const APInt *C2;
2375 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2376 return nullptr;
2377
2378 Type *ShiftType = Shl->getType();
2379 unsigned TypeBits = C.getBitWidth();
2380 ICmpInst::Predicate Pred = Cmp.getPredicate();
2381 if (Cmp.isUnsigned()) {
2382 if (C2->isZero() || C2->ugt(C))
2383 return nullptr;
2384 APInt Div, Rem;
2385 APInt::udivrem(C, *C2, Div, Rem);
2386 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2387
2388 // (1 << Y) pred C -> Y pred Log2(C)
2389 if (!CIsPowerOf2) {
2390 // (1 << Y) < 30 -> Y <= 4
2391 // (1 << Y) <= 30 -> Y <= 4
2392 // (1 << Y) >= 30 -> Y > 4
2393 // (1 << Y) > 30 -> Y > 4
2394 if (Pred == ICmpInst::ICMP_ULT)
2395 Pred = ICmpInst::ICMP_ULE;
2396 else if (Pred == ICmpInst::ICMP_UGE)
2397 Pred = ICmpInst::ICMP_UGT;
2398 }
2399
2400 unsigned CLog2 = Div.logBase2();
2401 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2402 } else if (Cmp.isSigned() && C2->isOne()) {
2403 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2404 // (1 << Y) > 0 -> Y != 31
2405 // (1 << Y) > C -> Y != 31 if C is negative.
2406 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2407 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2408
2409 // (1 << Y) < 0 -> Y == 31
2410 // (1 << Y) < 1 -> Y == 31
2411 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2412 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2413 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2414 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2415 }
2416
2417 return nullptr;
2418}
2419
2420/// Fold icmp (shl X, Y), C.
2422 BinaryOperator *Shl,
2423 const APInt &C) {
2424 const APInt *ShiftVal;
2425 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2426 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2427
2428 ICmpInst::Predicate Pred = Cmp.getPredicate();
2429 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2430 // -> (icmp pred X, Csle0)
2431 //
2432 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2433 // so X's must be what is used.
2434 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2435 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2436
2437 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2438 // -> (icmp eq/ne X, 0)
2439 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2440 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2441 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2442
2443 // (icmp slt (shl nsw X, Y), 0/1)
2444 // -> (icmp slt X, 0/1)
2445 // (icmp sgt (shl nsw X, Y), 0/-1)
2446 // -> (icmp sgt X, 0/-1)
2447 //
2448 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2449 if (Shl->hasNoSignedWrap() &&
2450 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2451 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2452 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2453
2454 const APInt *ShiftAmt;
2455 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2456 return foldICmpShlLHSC(Cmp, Shl, C);
2457
2458 // Check that the shift amount is in range. If not, don't perform undefined
2459 // shifts. When the shift is visited, it will be simplified.
2460 unsigned TypeBits = C.getBitWidth();
2461 if (ShiftAmt->uge(TypeBits))
2462 return nullptr;
2463
2464 Value *X = Shl->getOperand(0);
2465 Type *ShType = Shl->getType();
2466
2467 // NSW guarantees that we are only shifting out sign bits from the high bits,
2468 // so we can ASHR the compare constant without needing a mask and eliminate
2469 // the shift.
2470 if (Shl->hasNoSignedWrap()) {
2471 if (Pred == ICmpInst::ICMP_SGT) {
2472 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2473 APInt ShiftedC = C.ashr(*ShiftAmt);
2474 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2475 }
2476 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2477 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2478 APInt ShiftedC = C.ashr(*ShiftAmt);
2479 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2480 }
2481 if (Pred == ICmpInst::ICMP_SLT) {
2482 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2483 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2484 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2485 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2486 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2487 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2488 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2489 }
2490 }
2491
2492 // NUW guarantees that we are only shifting out zero bits from the high bits,
2493 // so we can LSHR the compare constant without needing a mask and eliminate
2494 // the shift.
2495 if (Shl->hasNoUnsignedWrap()) {
2496 if (Pred == ICmpInst::ICMP_UGT) {
2497 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2498 APInt ShiftedC = C.lshr(*ShiftAmt);
2499 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2500 }
2501 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2502 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2503 APInt ShiftedC = C.lshr(*ShiftAmt);
2504 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2505 }
2506 if (Pred == ICmpInst::ICMP_ULT) {
2507 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2508 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2509 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2510 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2511 assert(C.ugt(0) && "ult 0 should have been eliminated");
2512 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2513 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2514 }
2515 }
2516
2517 if (Cmp.isEquality() && Shl->hasOneUse()) {
2518 // Strength-reduce the shift into an 'and'.
2519 Constant *Mask = ConstantInt::get(
2520 ShType,
2521 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2522 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2523 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2524 return new ICmpInst(Pred, And, LShrC);
2525 }
2526
2527 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2528 bool TrueIfSigned = false;
2529 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2530 // (X << 31) <s 0 --> (X & 1) != 0
2531 Constant *Mask = ConstantInt::get(
2532 ShType,
2533 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2534 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2535 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2536 And, Constant::getNullValue(ShType));
2537 }
2538
2539 // Simplify 'shl' inequality test into 'and' equality test.
2540 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2541 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2542 if ((C + 1).isPowerOf2() &&
2543 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2544 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2545 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2547 And, Constant::getNullValue(ShType));
2548 }
2549 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2550 if (C.isPowerOf2() &&
2551 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2552 Value *And =
2553 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2554 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2556 And, Constant::getNullValue(ShType));
2557 }
2558 }
2559
2560 // Transform (icmp pred iM (shl iM %v, N), C)
2561 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2562 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2563 // This enables us to get rid of the shift in favor of a trunc that may be
2564 // free on the target. It has the additional benefit of comparing to a
2565 // smaller constant that may be more target-friendly.
2566 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2567 if (Shl->hasOneUse() && Amt != 0 &&
2568 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2569 ICmpInst::Predicate CmpPred = Pred;
2570 APInt RHSC = C;
2571
2572 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2573 // Try the flipped strictness predicate.
2574 // e.g.:
2575 // icmp ult i64 (shl X, 32), 8589934593 ->
2576 // icmp ule i64 (shl X, 32), 8589934592 ->
2577 // icmp ule i32 (trunc X, i32), 2 ->
2578 // icmp ult i32 (trunc X, i32), 3
2579 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2580 Pred, ConstantInt::get(ShType->getContext(), C))) {
2581 CmpPred = FlippedStrictness->first;
2582 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2583 }
2584 }
2585
2586 if (RHSC.countr_zero() >= Amt) {
2587 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2588 Constant *NewC =
2589 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2590 return new ICmpInst(CmpPred,
2591 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2592 Shl->hasNoSignedWrap()),
2593 NewC);
2594 }
2595 }
2596
2597 return nullptr;
2598}
2599
2600/// Fold icmp ({al}shr X, Y), C.
2602 BinaryOperator *Shr,
2603 const APInt &C) {
2604 // An exact shr only shifts out zero bits, so:
2605 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2606 Value *X = Shr->getOperand(0);
2607 CmpInst::Predicate Pred = Cmp.getPredicate();
2608 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2609 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2610
2611 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2612 const APInt *ShiftValC;
2613 if (match(X, m_APInt(ShiftValC))) {
2614 if (Cmp.isEquality())
2615 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2616
2617 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2618 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2619 bool TrueIfSigned;
2620 if (!IsAShr && ShiftValC->isNegative() &&
2621 isSignBitCheck(Pred, C, TrueIfSigned))
2622 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2623 Shr->getOperand(1),
2624 ConstantInt::getNullValue(X->getType()));
2625
2626 // If the shifted constant is a power-of-2, test the shift amount directly:
2627 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2628 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2629 if (!IsAShr && ShiftValC->isPowerOf2() &&
2630 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2631 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2632 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2633 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2634
2635 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2636 unsigned ShiftLZ = ShiftValC->countl_zero();
2637 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2638 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2639 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2640 }
2641 }
2642
2643 const APInt *ShiftAmtC;
2644 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2645 return nullptr;
2646
2647 // Check that the shift amount is in range. If not, don't perform undefined
2648 // shifts. When the shift is visited it will be simplified.
2649 unsigned TypeBits = C.getBitWidth();
2650 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2651 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2652 return nullptr;
2653
2654 bool IsExact = Shr->isExact();
2655 Type *ShrTy = Shr->getType();
2656 // TODO: If we could guarantee that InstSimplify would handle all of the
2657 // constant-value-based preconditions in the folds below, then we could assert
2658 // those conditions rather than checking them. This is difficult because of
2659 // undef/poison (PR34838).
2660 if (IsAShr && Shr->hasOneUse()) {
2661 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2662 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2663 // When C - 1 is a power of two and the transform can be legally
2664 // performed, prefer this form so the produced constant is close to a
2665 // power of two.
2666 // icmp slt/ult (ashr exact X, ShAmtC), C
2667 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2668 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2669 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2670 }
2671 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2672 // When ShAmtC can be shifted losslessly:
2673 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2674 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2675 APInt ShiftedC = C.shl(ShAmtVal);
2676 if (ShiftedC.ashr(ShAmtVal) == C)
2677 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2678 }
2679 if (Pred == CmpInst::ICMP_SGT) {
2680 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2681 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2682 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2683 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2684 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2685 }
2686 if (Pred == CmpInst::ICMP_UGT) {
2687 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2688 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2689 // clause accounts for that pattern.
2690 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2691 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2692 (C + 1).shl(ShAmtVal).isMinSignedValue())
2693 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2694 }
2695
2696 // If the compare constant has significant bits above the lowest sign-bit,
2697 // then convert an unsigned cmp to a test of the sign-bit:
2698 // (ashr X, ShiftC) u> C --> X s< 0
2699 // (ashr X, ShiftC) u< C --> X s> -1
2700 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2701 if (Pred == CmpInst::ICMP_UGT) {
2702 return new ICmpInst(CmpInst::ICMP_SLT, X,
2704 }
2705 if (Pred == CmpInst::ICMP_ULT) {
2706 return new ICmpInst(CmpInst::ICMP_SGT, X,
2708 }
2709 }
2710 } else if (!IsAShr) {
2711 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2712 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2713 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2714 APInt ShiftedC = C.shl(ShAmtVal);
2715 if (ShiftedC.lshr(ShAmtVal) == C)
2716 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2717 }
2718 if (Pred == CmpInst::ICMP_UGT) {
2719 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2720 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2721 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2722 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2723 }
2724 }
2725
2726 if (!Cmp.isEquality())
2727 return nullptr;
2728
2729 // Handle equality comparisons of shift-by-constant.
2730
2731 // If the comparison constant changes with the shift, the comparison cannot
2732 // succeed (bits of the comparison constant cannot match the shifted value).
2733 // This should be known by InstSimplify and already be folded to true/false.
2734 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2735 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2736 "Expected icmp+shr simplify did not occur.");
2737
2738 // If the bits shifted out are known zero, compare the unshifted value:
2739 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2740 if (Shr->isExact())
2741 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2742
2743 if (Shr->hasOneUse()) {
2744 // Canonicalize the shift into an 'and':
2745 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2746 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2747 Constant *Mask = ConstantInt::get(ShrTy, Val);
2748 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2749 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2750 }
2751
2752 return nullptr;
2753}
2754
2756 BinaryOperator *SRem,
2757 const APInt &C) {
2758 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2759 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2760 // Canonicalize unsigned predicates to signed:
2761 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2762 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2763 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2764 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2765
2766 const APInt *DivisorC;
2767 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2768 return nullptr;
2769 if (DivisorC->isZero())
2770 return nullptr;
2771
2772 APInt NormalizedC = C;
2773 if (Pred == ICmpInst::ICMP_ULT) {
2774 assert(!NormalizedC.isZero() &&
2775 "ult X, 0 should have been simplified already.");
2776 --NormalizedC;
2777 }
2778 if (C.isNegative())
2779 NormalizedC.flipAllBits();
2780 if (!NormalizedC.uge(DivisorC->abs() - 1))
2781 return nullptr;
2782
2783 Type *Ty = SRem->getType();
2784 if (Pred == ICmpInst::ICMP_UGT)
2785 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2787 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2789 }
2790 // Match an 'is positive' or 'is negative' comparison of remainder by a
2791 // constant power-of-2 value:
2792 // (X % pow2C) sgt/slt 0
2793 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2794 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2795 return nullptr;
2796
2797 // TODO: The one-use check is standard because we do not typically want to
2798 // create longer instruction sequences, but this might be a special-case
2799 // because srem is not good for analysis or codegen.
2800 if (!SRem->hasOneUse())
2801 return nullptr;
2802
2803 const APInt *DivisorC;
2804 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2805 return nullptr;
2806
2807 // For cmp_sgt/cmp_slt only zero valued C is handled.
2808 // For cmp_eq/cmp_ne only positive valued C is handled.
2809 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2810 !C.isZero()) ||
2811 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2812 !C.isStrictlyPositive()))
2813 return nullptr;
2814
2815 // Mask off the sign bit and the modulo bits (low-bits).
2816 Type *Ty = SRem->getType();
2817 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2818 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2819 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2820
2821 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2822 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2823
2824 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2825 // bit is set. Example:
2826 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2827 if (Pred == ICmpInst::ICMP_SGT)
2829
2830 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2831 // bit is set. Example:
2832 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2833 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2834}
2835
2836/// Fold icmp (udiv X, Y), C.
2838 BinaryOperator *UDiv,
2839 const APInt &C) {
2840 ICmpInst::Predicate Pred = Cmp.getPredicate();
2841 Value *X = UDiv->getOperand(0);
2842 Value *Y = UDiv->getOperand(1);
2843 Type *Ty = UDiv->getType();
2844
2845 const APInt *C2;
2846 if (!match(X, m_APInt(C2)))
2847 return nullptr;
2848
2849 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2850
2851 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2852 if (Pred == ICmpInst::ICMP_UGT) {
2853 assert(!C.isMaxValue() &&
2854 "icmp ugt X, UINT_MAX should have been simplified already.");
2855 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2856 ConstantInt::get(Ty, C2->udiv(C + 1)));
2857 }
2858
2859 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2860 if (Pred == ICmpInst::ICMP_ULT) {
2861 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2862 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2863 ConstantInt::get(Ty, C2->udiv(C)));
2864 }
2865
2866 return nullptr;
2867}
2868
2869/// Fold icmp ({su}div X, Y), C.
2871 BinaryOperator *Div,
2872 const APInt &C) {
2873 ICmpInst::Predicate Pred = Cmp.getPredicate();
2874 Value *X = Div->getOperand(0);
2875 Value *Y = Div->getOperand(1);
2876 Type *Ty = Div->getType();
2877 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2878
2879 // If unsigned division and the compare constant is bigger than
2880 // UMAX/2 (negative), there's only one pair of values that satisfies an
2881 // equality check, so eliminate the division:
2882 // (X u/ Y) == C --> (X == C) && (Y == 1)
2883 // (X u/ Y) != C --> (X != C) || (Y != 1)
2884 // Similarly, if signed division and the compare constant is exactly SMIN:
2885 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2886 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2887 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2888 (!DivIsSigned || C.isMinSignedValue())) {
2889 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2890 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2891 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2892 return BinaryOperator::Create(Logic, XBig, YOne);
2893 }
2894
2895 // Fold: icmp pred ([us]div X, C2), C -> range test
2896 // Fold this div into the comparison, producing a range check.
2897 // Determine, based on the divide type, what the range is being
2898 // checked. If there is an overflow on the low or high side, remember
2899 // it, otherwise compute the range [low, hi) bounding the new value.
2900 // See: InsertRangeTest above for the kinds of replacements possible.
2901 const APInt *C2;
2902 if (!match(Y, m_APInt(C2)))
2903 return nullptr;
2904
2905 // FIXME: If the operand types don't match the type of the divide
2906 // then don't attempt this transform. The code below doesn't have the
2907 // logic to deal with a signed divide and an unsigned compare (and
2908 // vice versa). This is because (x /s C2) <s C produces different
2909 // results than (x /s C2) <u C or (x /u C2) <s C or even
2910 // (x /u C2) <u C. Simply casting the operands and result won't
2911 // work. :( The if statement below tests that condition and bails
2912 // if it finds it.
2913 // However, when the divisor is a positive constant and the dividend is
2914 // known non-negative, sdiv is equivalent to udiv, so we can lower
2915 // DivIsSigned and proceed through the unsigned path.
2916 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2917 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2918 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2919 return nullptr;
2920 DivIsSigned = false;
2921 }
2922
2923 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2924 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2925 // division-by-constant cases should be present, we can not assert that they
2926 // have happened before we reach this icmp instruction.
2927 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2928 return nullptr;
2929
2930 // Compute Prod = C * C2. We are essentially solving an equation of
2931 // form X / C2 = C. We solve for X by multiplying C2 and C.
2932 // By solving for X, we can turn this into a range check instead of computing
2933 // a divide.
2934 APInt Prod = C * *C2;
2935
2936 // Determine if the product overflows by seeing if the product is not equal to
2937 // the divide. Make sure we do the same kind of divide as in the LHS
2938 // instruction that we're folding.
2939 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2940
2941 // If the division is known to be exact, then there is no remainder from the
2942 // divide, so the covered range size is unit, otherwise it is the divisor.
2943 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2944
2945 // Figure out the interval that is being checked. For example, a comparison
2946 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2947 // Compute this interval based on the constants involved and the signedness of
2948 // the compare/divide. This computes a half-open interval, keeping track of
2949 // whether either value in the interval overflows. After analysis each
2950 // overflow variable is set to 0 if it's corresponding bound variable is valid
2951 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2952 int LoOverflow = 0, HiOverflow = 0;
2953 APInt LoBound, HiBound;
2954
2955 if (!DivIsSigned) { // udiv
2956 // e.g. X/5 op 3 --> [15, 20)
2957 LoBound = Prod;
2958 HiOverflow = LoOverflow = ProdOV;
2959 if (!HiOverflow) {
2960 // If this is not an exact divide, then many values in the range collapse
2961 // to the same result value.
2962 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2963 }
2964 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2965 if (C.isZero()) { // (X / pos) op 0
2966 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2967 LoBound = -(RangeSize - 1);
2968 HiBound = RangeSize;
2969 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2970 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2971 HiOverflow = LoOverflow = ProdOV;
2972 if (!HiOverflow)
2973 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2974 } else { // (X / pos) op neg
2975 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2976 HiBound = Prod + 1;
2977 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2978 if (!LoOverflow) {
2979 APInt DivNeg = -RangeSize;
2980 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2981 }
2982 }
2983 } else if (C2->isNegative()) { // Divisor is < 0.
2984 if (Div->isExact())
2985 RangeSize.negate();
2986 if (C.isZero()) { // (X / neg) op 0
2987 // e.g. X/-5 op 0 --> [-4, 5)
2988 LoBound = RangeSize + 1;
2989 HiBound = -RangeSize;
2990 if (HiBound == *C2) { // -INTMIN = INTMIN
2991 HiOverflow = 1; // [INTMIN+1, overflow)
2992 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2993 }
2994 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2995 // e.g. X/-5 op 3 --> [-19, -14)
2996 HiBound = Prod + 1;
2997 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2998 if (!LoOverflow)
2999 LoOverflow =
3000 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
3001 } else { // (X / neg) op neg
3002 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
3003 LoOverflow = HiOverflow = ProdOV;
3004 if (!HiOverflow)
3005 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
3006 }
3007
3008 // Dividing by a negative swaps the condition. LT <-> GT
3009 Pred = ICmpInst::getSwappedPredicate(Pred);
3010 }
3011
3012 switch (Pred) {
3013 default:
3014 llvm_unreachable("Unhandled icmp predicate!");
3015 case ICmpInst::ICMP_EQ:
3016 if (LoOverflow && HiOverflow)
3017 return replaceInstUsesWith(Cmp, Builder.getFalse());
3018 if (HiOverflow)
3019 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3020 X, ConstantInt::get(Ty, LoBound));
3021 if (LoOverflow)
3022 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3023 X, ConstantInt::get(Ty, HiBound));
3024 return replaceInstUsesWith(
3025 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3026 case ICmpInst::ICMP_NE:
3027 if (LoOverflow && HiOverflow)
3028 return replaceInstUsesWith(Cmp, Builder.getTrue());
3029 if (HiOverflow)
3030 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3031 X, ConstantInt::get(Ty, LoBound));
3032 if (LoOverflow)
3033 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3034 X, ConstantInt::get(Ty, HiBound));
3035 return replaceInstUsesWith(
3036 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3037 case ICmpInst::ICMP_ULT:
3038 case ICmpInst::ICMP_SLT:
3039 if (LoOverflow == +1) // Low bound is greater than input range.
3040 return replaceInstUsesWith(Cmp, Builder.getTrue());
3041 if (LoOverflow == -1) // Low bound is less than input range.
3042 return replaceInstUsesWith(Cmp, Builder.getFalse());
3043 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3044 case ICmpInst::ICMP_UGT:
3045 case ICmpInst::ICMP_SGT:
3046 if (HiOverflow == +1) // High bound greater than input range.
3047 return replaceInstUsesWith(Cmp, Builder.getFalse());
3048 if (HiOverflow == -1) // High bound less than input range.
3049 return replaceInstUsesWith(Cmp, Builder.getTrue());
3050 if (Pred == ICmpInst::ICMP_UGT)
3051 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3052 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3053 }
3054
3055 return nullptr;
3056}
3057
3058/// Fold icmp (sub X, Y), C.
3061 const APInt &C) {
3062 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3063 ICmpInst::Predicate Pred = Cmp.getPredicate();
3064 Type *Ty = Sub->getType();
3065
3066 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3067 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3068 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3069 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3070 const APInt *D;
3071 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3072 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3073 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3074 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3075 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3076 }
3077
3078 // (SubC - Y) == C) --> Y == (SubC - C)
3079 // (SubC - Y) != C) --> Y != (SubC - C)
3080 Constant *SubC;
3081 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3082 return new ICmpInst(Pred, Y,
3083 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3084 }
3085
3086 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3087 const APInt *C2;
3088 APInt SubResult;
3089 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3090 bool HasNSW = Sub->hasNoSignedWrap();
3091 bool HasNUW = Sub->hasNoUnsignedWrap();
3092 if (match(X, m_APInt(C2)) &&
3093 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3094 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3095 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3096
3097 // X - Y == 0 --> X == Y.
3098 // X - Y != 0 --> X != Y.
3099 // TODO: We allow this with multiple uses as long as the other uses are not
3100 // in phis. The phi use check is guarding against a codegen regression
3101 // for a loop test. If the backend could undo this (and possibly
3102 // subsequent transforms), we would not need this hack.
3103 if (Cmp.isEquality() && C.isZero() &&
3104 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3105 return new ICmpInst(Pred, X, Y);
3106
3107 // The following transforms are only worth it if the only user of the subtract
3108 // is the icmp.
3109 // TODO: This is an artificial restriction for all of the transforms below
3110 // that only need a single replacement icmp. Can these use the phi test
3111 // like the transform above here?
3112 if (!Sub->hasOneUse())
3113 return nullptr;
3114
3115 if (Sub->hasNoSignedWrap()) {
3116 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3117 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3118 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3119
3120 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3121 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3122 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3123
3124 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3125 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3126 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3127
3128 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3129 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3130 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3131 }
3132
3133 if (!match(X, m_APInt(C2)))
3134 return nullptr;
3135
3136 // C2 - Y <u C -> (Y | (C - 1)) == C2
3137 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3138 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3139 (*C2 & (C - 1)) == (C - 1))
3140 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3141
3142 // C2 - Y >u C -> (Y | C) != C2
3143 // iff C2 & C == C and C + 1 is a power of 2
3144 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3145 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3146
3147 // We have handled special cases that reduce.
3148 // Canonicalize any remaining sub to add as:
3149 // (C2 - Y) > C --> (Y + ~C2) < ~C
3150 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3151 HasNUW, HasNSW);
3152 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3153}
3154
3155static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3156 Value *Op1, IRBuilderBase &Builder,
3157 bool HasOneUse) {
3158 auto FoldConstant = [&](bool Val) {
3159 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3160 if (Op0->getType()->isVectorTy())
3162 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3163 return Res;
3164 };
3165
3166 switch (Table.to_ulong()) {
3167 case 0: // 0 0 0 0
3168 return FoldConstant(false);
3169 case 1: // 0 0 0 1
3170 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3171 case 2: // 0 0 1 0
3172 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3173 case 3: // 0 0 1 1
3174 return Builder.CreateNot(Op0);
3175 case 4: // 0 1 0 0
3176 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3177 case 5: // 0 1 0 1
3178 return Builder.CreateNot(Op1);
3179 case 6: // 0 1 1 0
3180 return Builder.CreateXor(Op0, Op1);
3181 case 7: // 0 1 1 1
3182 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3183 case 8: // 1 0 0 0
3184 return Builder.CreateAnd(Op0, Op1);
3185 case 9: // 1 0 0 1
3186 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3187 case 10: // 1 0 1 0
3188 return Op1;
3189 case 11: // 1 0 1 1
3190 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3191 case 12: // 1 1 0 0
3192 return Op0;
3193 case 13: // 1 1 0 1
3194 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3195 case 14: // 1 1 1 0
3196 return Builder.CreateOr(Op0, Op1);
3197 case 15: // 1 1 1 1
3198 return FoldConstant(true);
3199 default:
3200 llvm_unreachable("Invalid Operation");
3201 }
3202 return nullptr;
3203}
3204
3206 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3207 Value *A, *B;
3208 Constant *C1, *C2, *C3, *C4;
3209 if (!match(BO->getOperand(0),
3211 !match(BO->getOperand(1),
3213 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3214 return nullptr;
3215
3216 std::bitset<4> Table;
3217 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3218 Constant *L = First ? C1 : C2;
3219 Constant *R = Second ? C3 : C4;
3220 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3221 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3222 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3223 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3224 }
3225 return std::nullopt;
3226 };
3227
3228 for (unsigned I = 0; I < 4; ++I) {
3229 bool First = (I >> 1) & 1;
3230 bool Second = I & 1;
3231 if (auto Res = ComputeTable(First, Second))
3232 Table[I] = *Res;
3233 else
3234 return nullptr;
3235 }
3236
3237 // Synthesize optimal logic.
3238 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3239 return replaceInstUsesWith(Cmp, Cond);
3240 return nullptr;
3241}
3242
3243/// Fold icmp (add X, Y), C.
3246 const APInt &C) {
3247 Value *Y = Add->getOperand(1);
3248 Value *X = Add->getOperand(0);
3249 const CmpPredicate Pred = Cmp.getCmpPredicate();
3250
3251 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3252 // when C <= (1 << ShAmtC).
3253 const APInt *ShAmtC;
3254 Value *A;
3255 unsigned BitWidth = C.getBitWidth();
3256 if (Pred == ICmpInst::ICMP_ULT &&
3257 match(Add,
3258 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3259 ShAmtC->ult(BitWidth) &&
3260 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3261 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3262
3263 const APInt *C2;
3264 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3265 return nullptr;
3266
3267 // Fold icmp pred (add X, C2), C.
3268 Type *Ty = Add->getType();
3269
3270 // If the add does not wrap, we can always adjust the compare by subtracting
3271 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3272 // have been canonicalized to SGT/SLT/UGT/ULT.
3273 if (Add->hasNoUnsignedWrap() &&
3274 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3275 bool Overflow;
3276 APInt NewC = C.usub_ov(*C2, Overflow);
3277 // If there is overflow, the result must be true or false.
3278 if (!Overflow)
3279 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3280 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3281 }
3282
3283 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3284
3285 if (Add->hasNoSignedWrap() &&
3286 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3287 bool Overflow;
3288 APInt NewC = C.ssub_ov(*C2, Overflow);
3289 if (!Overflow)
3290 // icmp samesign ugt/ult (add nsw X, C2), C
3291 // -> icmp sgt/slt X, (C - C2)
3292 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3293 }
3294
3295 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3296 C.isNonNegative() && (C - *C2).isNonNegative() &&
3297 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3298 .add(*C2)
3299 .isAllNonNegative())
3300 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3301 ConstantInt::get(Ty, C - *C2));
3302
3303 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3304 const APInt &Upper = CR.getUpper();
3305 const APInt &Lower = CR.getLower();
3306 if (Cmp.isSigned()) {
3307 if (Lower.isSignMask())
3308 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3309 if (Upper.isSignMask())
3310 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3311 } else {
3312 if (Lower.isMinValue())
3313 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3314 if (Upper.isMinValue())
3315 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3316 }
3317
3318 // This set of folds is intentionally placed after folds that use no-wrapping
3319 // flags because those folds are likely better for later analysis/codegen.
3320 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3321 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3322
3323 // Fold compare with offset to opposite sign compare if it eliminates offset:
3324 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3325 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3326 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3327
3328 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3329 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3330 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3331
3332 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3333 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3334 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3335
3336 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3337 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3338 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3339
3340 // (X + -1) <u C --> X <=u C (if X is never null)
3341 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3342 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3343 if (llvm::isKnownNonZero(X, Q))
3344 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3345 }
3346
3347 if (!Add->hasOneUse())
3348 return nullptr;
3349
3350 // X+C <u C2 -> (X & -C2) == C
3351 // iff C & (C2-1) == 0
3352 // C2 is a power of 2
3353 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3354 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3356
3357 // X+C2 <u C -> (X & C) == 2C
3358 // iff C == -(C2)
3359 // C2 is a power of 2
3360 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3361 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3362 ConstantInt::get(Ty, C * 2));
3363
3364 // X+C >u C2 -> (X & ~C2) != C
3365 // iff C & C2 == 0
3366 // C2+1 is a power of 2
3367 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3368 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3370
3371 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3372 // to the ult form.
3373 // X+C2 >u C -> X+(C2-C-1) <u ~C
3374 if (Pred == ICmpInst::ICMP_UGT)
3375 return new ICmpInst(ICmpInst::ICMP_ULT,
3376 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3377 ConstantInt::get(Ty, ~C));
3378
3379 // zext(V) + C2 pred C -> V + C3 pred' C4
3380 Value *V;
3381 if (match(X, m_ZExt(m_Value(V)))) {
3382 Type *NewCmpTy = V->getType();
3383 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3384 if (shouldChangeType(Ty, NewCmpTy)) {
3385 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3386 CmpInst::Predicate EquivPred;
3387 APInt EquivInt;
3388 APInt EquivOffset;
3389
3390 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3391 return new ICmpInst(
3392 EquivPred,
3393 EquivOffset.isZero()
3394 ? V
3395 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3396 ConstantInt::get(NewCmpTy, EquivInt));
3397 }
3398 }
3399
3400 return nullptr;
3401}
3402
3404 Value *&RHS, ConstantInt *&Less,
3405 ConstantInt *&Equal,
3406 ConstantInt *&Greater) {
3407 // TODO: Generalize this to work with other comparison idioms or ensure
3408 // they get canonicalized into this form.
3409
3410 // select i1 (a == b),
3411 // i32 Equal,
3412 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3413 // where Equal, Less and Greater are placeholders for any three constants.
3414 CmpPredicate PredA;
3415 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3416 !ICmpInst::isEquality(PredA))
3417 return false;
3418 Value *EqualVal = SI->getTrueValue();
3419 Value *UnequalVal = SI->getFalseValue();
3420 // We still can get non-canonical predicate here, so canonicalize.
3421 if (PredA == ICmpInst::ICMP_NE)
3422 std::swap(EqualVal, UnequalVal);
3423 if (!match(EqualVal, m_ConstantInt(Equal)))
3424 return false;
3425 CmpPredicate PredB;
3426 Value *LHS2, *RHS2;
3427 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3428 m_ConstantInt(Less), m_ConstantInt(Greater))))
3429 return false;
3430 // We can get predicate mismatch here, so canonicalize if possible:
3431 // First, ensure that 'LHS' match.
3432 if (LHS2 != LHS) {
3433 // x sgt y <--> y slt x
3434 std::swap(LHS2, RHS2);
3435 PredB = ICmpInst::getSwappedPredicate(PredB);
3436 }
3437 if (LHS2 != LHS)
3438 return false;
3439 // We also need to canonicalize 'RHS'.
3440 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3441 // x sgt C-1 <--> x sge C <--> not(x slt C)
3442 auto FlippedStrictness =
3444 if (!FlippedStrictness)
3445 return false;
3446 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3447 "basic correctness failure");
3448 RHS2 = FlippedStrictness->second;
3449 // And kind-of perform the result swap.
3450 std::swap(Less, Greater);
3451 PredB = ICmpInst::ICMP_SLT;
3452 }
3453 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3454}
3455
3458 ConstantInt *C) {
3459
3460 assert(C && "Cmp RHS should be a constant int!");
3461 // If we're testing a constant value against the result of a three way
3462 // comparison, the result can be expressed directly in terms of the
3463 // original values being compared. Note: We could possibly be more
3464 // aggressive here and remove the hasOneUse test. The original select is
3465 // really likely to simplify or sink when we remove a test of the result.
3466 Value *OrigLHS, *OrigRHS;
3467 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3468 if (Cmp.hasOneUse() &&
3469 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3470 C3GreaterThan)) {
3471 assert(C1LessThan && C2Equal && C3GreaterThan);
3472
3473 bool TrueWhenLessThan = ICmpInst::compare(
3474 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3475 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3476 Cmp.getPredicate());
3477 bool TrueWhenGreaterThan = ICmpInst::compare(
3478 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3479
3480 // This generates the new instruction that will replace the original Cmp
3481 // Instruction. Instead of enumerating the various combinations when
3482 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3483 // false, we rely on chaining of ORs and future passes of InstCombine to
3484 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3485
3486 // When none of the three constants satisfy the predicate for the RHS (C),
3487 // the entire original Cmp can be simplified to a false.
3488 Value *Cond = Builder.getFalse();
3489 if (TrueWhenLessThan)
3490 Cond = Builder.CreateOr(
3491 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3492 if (TrueWhenEqual)
3493 Cond = Builder.CreateOr(
3494 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3495 if (TrueWhenGreaterThan)
3496 Cond = Builder.CreateOr(
3497 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3498
3499 return replaceInstUsesWith(Cmp, Cond);
3500 }
3501 return nullptr;
3502}
3503
3505 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3506 if (!Bitcast)
3507 return nullptr;
3508
3509 ICmpInst::Predicate Pred = Cmp.getPredicate();
3510 Value *Op1 = Cmp.getOperand(1);
3511 Value *BCSrcOp = Bitcast->getOperand(0);
3512 Type *SrcType = Bitcast->getSrcTy();
3513 Type *DstType = Bitcast->getType();
3514
3515 // Make sure the bitcast doesn't change between scalar and vector and
3516 // doesn't change the number of vector elements.
3517 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3518 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3519 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3520 Value *X;
3521 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3522 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3523 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3524 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3525 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3526 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3527 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3528 match(Op1, m_Zero()))
3529 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3530
3531 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3532 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3533 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3534
3535 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3536 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3537 return new ICmpInst(Pred, X,
3538 ConstantInt::getAllOnesValue(X->getType()));
3539 }
3540
3541 // Zero-equality checks are preserved through unsigned floating-point casts:
3542 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3543 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3544 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3545 if (Cmp.isEquality() && match(Op1, m_Zero()))
3546 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3547
3548 const APInt *C;
3549 bool TrueIfSigned;
3550 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3551 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3552 // the FP extend/truncate because that cast does not change the sign-bit.
3553 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3554 // The sign-bit is always the most significant bit in those types.
3555 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3556 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3557 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3558 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3559 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3560 Type *XType = X->getType();
3561
3562 // We can't currently handle Power style floating point operations here.
3563 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3564 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3565 if (auto *XVTy = dyn_cast<VectorType>(XType))
3566 NewType = VectorType::get(NewType, XVTy->getElementCount());
3567 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3568 if (TrueIfSigned)
3569 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3570 ConstantInt::getNullValue(NewType));
3571 else
3572 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3574 }
3575 }
3576
3577 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3578 Type *FPType = SrcType->getScalarType();
3579 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3580 Attribute::NoImplicitFloat) &&
3581 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3582 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3583 if (Mask & (fcInf | fcZero)) {
3584 if (Pred == ICmpInst::ICMP_NE)
3585 Mask = ~Mask;
3586 return replaceInstUsesWith(Cmp,
3587 Builder.createIsFPClass(BCSrcOp, Mask));
3588 }
3589 }
3590 }
3591 }
3592
3593 // Fold the canonicalized form of vector_reduce_or if the arg is
3594 // get_active_lane mask.
3595 // icmp ne (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3596 // icmp ult l, h
3597 // icmp eq (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3598 // icmp uge l, h
3599 Value *Upper, *Lower;
3601 m_Value(Lower), m_Value(Upper))) &&
3602 match(Op1, m_Zero()) && DstType->isIntegerTy()) {
3603 if (Pred == ICmpInst::ICMP_NE)
3604 return new ICmpInst(ICmpInst::ICMP_ULT, Lower, Upper);
3605 if (Pred == ICmpInst::ICMP_EQ)
3606 return new ICmpInst(ICmpInst::ICMP_UGE, Lower, Upper);
3607 }
3608
3609 const APInt *C;
3610 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3611 !SrcType->isIntOrIntVectorTy())
3612 return nullptr;
3613
3614 // If this is checking if all elements of a vector compare are set or not,
3615 // invert the casted vector equality compare and test if all compare
3616 // elements are clear or not. Compare against zero is generally easier for
3617 // analysis and codegen.
3618 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3619 // Example: are all elements equal? --> are zero elements not equal?
3620 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3621 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3622 if (Value *NotBCSrcOp =
3623 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3624 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3625 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3626 }
3627 }
3628
3629 // If this is checking if all elements of an extended vector are clear or not,
3630 // compare in a narrow type to eliminate the extend:
3631 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3632 Value *X;
3633 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3634 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3635 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3636 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3637 Value *NewCast = Builder.CreateBitCast(X, NewType);
3638 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3639 }
3640 }
3641
3642 // Folding: icmp <pred> iN X, C
3643 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3644 // and C is a splat of a K-bit pattern
3645 // and SC is a constant vector = <C', C', C', ..., C'>
3646 // Into:
3647 // %E = extractelement <M x iK> %vec, i32 C'
3648 // icmp <pred> iK %E, trunc(C)
3649 Value *Vec;
3650 ArrayRef<int> Mask;
3651 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3652 // Check whether every element of Mask is the same constant
3653 if (all_equal(Mask)) {
3654 auto *VecTy = cast<VectorType>(SrcType);
3655 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3656 if (C->isSplat(EltTy->getBitWidth())) {
3657 // Fold the icmp based on the value of C
3658 // If C is M copies of an iK sized bit pattern,
3659 // then:
3660 // => %E = extractelement <N x iK> %vec, i64 Elem
3661 // icmp <pred> iK %SplatVal, <pattern>
3662 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3663 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3664 return new ICmpInst(Pred, Extract, NewC);
3665 }
3666 }
3667 }
3668 return nullptr;
3669}
3670
3671/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3672/// where X is some kind of instruction.
3674 const APInt *C;
3675
3676 if (match(Cmp.getOperand(1), m_APInt(C))) {
3677 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3678 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3679 return I;
3680
3681 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3682 // For now, we only support constant integers while folding the
3683 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3684 // similar to the cases handled by binary ops above.
3685 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3686 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3687 return I;
3688
3689 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3690 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3691 return I;
3692
3693 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3695 return I;
3696
3697 {
3698 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3699 // fcmp olt/oge (fabs X), 2^ExpVal
3700 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3701 Value *X;
3702 if (match(Cmp.getOperand(0),
3705 ICmpInst::Predicate Pred = Cmp.getPredicate();
3706 APInt Exp;
3707 FCmpInst::Predicate NewPred;
3708 bool ValidPred = true;
3709
3710 switch (Pred) {
3711 case ICmpInst::ICMP_SLT:
3712 NewPred = FCmpInst::FCMP_OLT;
3713 Exp = *C - 1;
3714 break;
3715 case ICmpInst::ICMP_SGT:
3716 NewPred = FCmpInst::FCMP_OGE;
3717 Exp = *C;
3718 break;
3719 default:
3720 ValidPred = false;
3721 break;
3722 }
3723
3724 if (ValidPred) {
3725 const fltSemantics &Sem =
3726 X->getType()->getScalarType()->getFltSemantics();
3727 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3728
3729 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3730 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3731 int ExpVal = static_cast<int>(Exp.getSExtValue());
3732 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3734 Value *Fabs = Builder.CreateFAbs(X);
3735 return new FCmpInst(NewPred, Fabs,
3736 ConstantFP::get(X->getType(), CmpConst));
3737 }
3738 }
3739 }
3740 }
3741
3742 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3743 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3744 // TODO: This checks one-use, but that is not strictly necessary.
3745 Value *Cmp0 = Cmp.getOperand(0);
3746 Value *X, *Y;
3747 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3748 (match(Cmp0,
3750 m_Value(X), m_Value(Y)))) ||
3751 match(Cmp0,
3753 m_Value(X), m_Value(Y))))))
3754 return new ICmpInst(Cmp.getPredicate(), X, Y);
3755 }
3756
3757 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3759
3760 return nullptr;
3761}
3762
3763/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3764/// icmp eq/ne BO, C.
3766 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3767 // TODO: Some of these folds could work with arbitrary constants, but this
3768 // function is limited to scalar and vector splat constants.
3769 if (!Cmp.isEquality())
3770 return nullptr;
3771
3772 ICmpInst::Predicate Pred = Cmp.getPredicate();
3773 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3774 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3775 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3776
3777 switch (BO->getOpcode()) {
3778 case Instruction::SRem:
3779 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3780 if (C.isZero() && BO->hasOneUse()) {
3781 const APInt *BOC;
3782 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3783 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3784 return new ICmpInst(Pred, NewRem,
3786 }
3787 }
3788 break;
3789 case Instruction::Add: {
3790 // (A + C2) == C --> A == (C - C2)
3791 // (A + C2) != C --> A != (C - C2)
3792 // TODO: Remove the one-use limitation? See discussion in D58633.
3793 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3794 if (BO->hasOneUse())
3795 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3796 } else if (C.isZero()) {
3797 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3798 // efficiently invertible, or if the add has just this one use.
3799 if (Value *NegVal = dyn_castNegVal(BOp1))
3800 return new ICmpInst(Pred, BOp0, NegVal);
3801 if (Value *NegVal = dyn_castNegVal(BOp0))
3802 return new ICmpInst(Pred, NegVal, BOp1);
3803 if (BO->hasOneUse()) {
3804 // (add nuw A, B) != 0 -> (or A, B) != 0
3805 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3806 Value *Or = Builder.CreateOr(BOp0, BOp1);
3807 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3808 }
3809 Value *Neg = Builder.CreateNeg(BOp1);
3810 Neg->takeName(BO);
3811 return new ICmpInst(Pred, BOp0, Neg);
3812 }
3813 }
3814 break;
3815 }
3816 case Instruction::Xor:
3817 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3818 // For the xor case, we can xor two constants together, eliminating
3819 // the explicit xor.
3820 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3821 } else if (C.isZero()) {
3822 // Replace ((xor A, B) != 0) with (A != B)
3823 return new ICmpInst(Pred, BOp0, BOp1);
3824 }
3825 break;
3826 case Instruction::Or: {
3827 const APInt *BOC;
3828 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3829 // Comparing if all bits outside of a constant mask are set?
3830 // Replace (X | C) == -1 with (X & ~C) == ~C.
3831 // This removes the -1 constant.
3833 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3834 return new ICmpInst(Pred, And, NotBOC);
3835 }
3836 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3837 // -> (and cond, (icmp eq Other, 0))
3838 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3839 // -> (or cond, (icmp ne Other, 0))
3840 Value *Cond, *TV, *FV, *Other, *Sel;
3841 if (C.isZero() &&
3842 match(BO,
3845 m_Value(FV))),
3846 m_Value(Other)))) &&
3847 Cond->getType() == Cmp.getType()) {
3848 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3849 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3850 if (Pred == ICmpInst::ICMP_EQ
3851 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3852 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3853 Value *Cmp = Builder.CreateICmp(
3854 Pred, Other, Constant::getNullValue(Other->getType()));
3856 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3857 Cond);
3858 }
3859 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3860 // case we need to invert the select condition so we need to be careful to
3861 // avoid creating extra instructions.
3862 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3863 // -> (or (not cond), (icmp ne Other, 0))
3864 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3865 // -> (and (not cond), (icmp eq Other, 0))
3866 //
3867 // Only do this if the inner select has one use, in which case we are
3868 // replacing `select` with `(not cond)`. Otherwise, we will create more
3869 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3870 // cond was freely invertable, the select arms would have been inverted.
3871 if (Sel->hasOneUse() &&
3872 (Pred == ICmpInst::ICMP_EQ
3873 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3874 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3875 Value *NotCond = Builder.CreateNot(Cond);
3876 Value *Cmp = Builder.CreateICmp(
3877 Pred, Other, Constant::getNullValue(Other->getType()));
3879 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3880 NotCond);
3881 }
3882 }
3883 break;
3884 }
3885 case Instruction::UDiv:
3886 case Instruction::SDiv:
3887 if (BO->isExact()) {
3888 // div exact X, Y eq/ne 0 -> X eq/ne 0
3889 // div exact X, Y eq/ne 1 -> X eq/ne Y
3890 // div exact X, Y eq/ne C ->
3891 // if Y * C never-overflow && OneUse:
3892 // -> Y * C eq/ne X
3893 if (C.isZero())
3894 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3895 else if (C.isOne())
3896 return new ICmpInst(Pred, BOp0, BOp1);
3897 else if (BO->hasOneUse()) {
3899 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3900 Cmp.getOperand(1), BO);
3902 Value *YC =
3903 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3904 return new ICmpInst(Pred, YC, BOp0);
3905 }
3906 }
3907 }
3908 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3909 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3910 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3911 return new ICmpInst(NewPred, BOp1, BOp0);
3912 }
3913 break;
3914 default:
3915 break;
3916 }
3917 return nullptr;
3918}
3919
3921 const APInt &CRhs,
3922 InstCombiner::BuilderTy &Builder,
3923 const SimplifyQuery &Q) {
3924 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3925 "Non-ctpop intrin in ctpop fold");
3926 if (!CtpopLhs->hasOneUse())
3927 return nullptr;
3928
3929 // Power of 2 test:
3930 // isPow2OrZero : ctpop(X) u< 2
3931 // isPow2 : ctpop(X) == 1
3932 // NotPow2OrZero: ctpop(X) u> 1
3933 // NotPow2 : ctpop(X) != 1
3934 // If we know any bit of X can be folded to:
3935 // IsPow2 : X & (~Bit) == 0
3936 // NotPow2 : X & (~Bit) != 0
3937 const ICmpInst::Predicate Pred = I.getPredicate();
3938 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3939 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3940 Value *Op = CtpopLhs->getArgOperand(0);
3941 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CtxI, Q.DT);
3942 // No need to check for count > 1, that should be already constant folded.
3943 if (OpKnown.countMinPopulation() == 1) {
3944 Value *And = Builder.CreateAnd(
3945 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3946 return new ICmpInst(
3947 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3950 And, Constant::getNullValue(Op->getType()));
3951 }
3952 }
3953
3954 return nullptr;
3955}
3956
3957/// Fold an equality icmp with LLVM intrinsic and constant operand.
3959 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3960 Type *Ty = II->getType();
3961 unsigned BitWidth = C.getBitWidth();
3962 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3963
3964 switch (II->getIntrinsicID()) {
3965 case Intrinsic::abs:
3966 // abs(A) == 0 -> A == 0
3967 // abs(A) == INT_MIN -> A == INT_MIN
3968 if (C.isZero() || C.isMinSignedValue())
3969 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3970 break;
3971
3972 case Intrinsic::bswap:
3973 // bswap(A) == C -> A == bswap(C)
3974 return new ICmpInst(Pred, II->getArgOperand(0),
3975 ConstantInt::get(Ty, C.byteSwap()));
3976
3977 case Intrinsic::bitreverse:
3978 // bitreverse(A) == C -> A == bitreverse(C)
3979 return new ICmpInst(Pred, II->getArgOperand(0),
3980 ConstantInt::get(Ty, C.reverseBits()));
3981
3982 case Intrinsic::ctlz:
3983 case Intrinsic::cttz: {
3984 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3985 if (C == BitWidth)
3986 return new ICmpInst(Pred, II->getArgOperand(0),
3988
3989 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3990 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3991 // Limit to one use to ensure we don't increase instruction count.
3992 unsigned Num = C.getLimitedValue(BitWidth);
3993 if (Num != BitWidth && II->hasOneUse()) {
3994 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3995 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3996 : APInt::getHighBitsSet(BitWidth, Num + 1);
3997 APInt Mask2 = IsTrailing
4000 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
4001 ConstantInt::get(Ty, Mask2));
4002 }
4003 break;
4004 }
4005
4006 case Intrinsic::ctpop: {
4007 // popcount(A) == 0 -> A == 0 and likewise for !=
4008 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
4009 bool IsZero = C.isZero();
4010 if (IsZero || C == BitWidth)
4011 return new ICmpInst(Pred, II->getArgOperand(0),
4012 IsZero ? Constant::getNullValue(Ty)
4014
4015 break;
4016 }
4017
4018 case Intrinsic::fshl:
4019 case Intrinsic::fshr:
4020 if (II->getArgOperand(0) == II->getArgOperand(1)) {
4021 const APInt *RotAmtC;
4022 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
4023 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
4024 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
4025 return new ICmpInst(Pred, II->getArgOperand(0),
4026 II->getIntrinsicID() == Intrinsic::fshl
4027 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
4028 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4029 }
4030 break;
4031
4032 case Intrinsic::umax:
4033 case Intrinsic::uadd_sat: {
4034 // uadd.sat(a, b) == 0 -> (a | b) == 0
4035 // umax(a, b) == 0 -> (a | b) == 0
4036 if (C.isZero() && II->hasOneUse()) {
4037 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4038 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4039 }
4040 break;
4041 }
4042
4043 case Intrinsic::ssub_sat:
4044 // ssub.sat(a, b) == 0 -> a == b
4045 //
4046 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4047 // (because 1 saturates to 0). Just skip the optimization for i1.
4048 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4049 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4050 break;
4051 case Intrinsic::usub_sat: {
4052 // usub.sat(a, b) == 0 -> a <= b
4053 if (C.isZero()) {
4054 ICmpInst::Predicate NewPred =
4056 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4057 }
4058 break;
4059 }
4060 default:
4061 break;
4062 }
4063
4064 return nullptr;
4065}
4066
4067/// Fold an icmp with LLVM intrinsics
4068static Instruction *
4070 InstCombiner::BuilderTy &Builder) {
4071 assert(Cmp.isEquality());
4072
4073 ICmpInst::Predicate Pred = Cmp.getPredicate();
4074 Value *Op0 = Cmp.getOperand(0);
4075 Value *Op1 = Cmp.getOperand(1);
4076 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4077 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4078 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4079 return nullptr;
4080
4081 switch (IIOp0->getIntrinsicID()) {
4082 case Intrinsic::bswap:
4083 case Intrinsic::bitreverse:
4084 // If both operands are byte-swapped or bit-reversed, just compare the
4085 // original values.
4086 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4087 case Intrinsic::fshl:
4088 case Intrinsic::fshr: {
4089 // If both operands are rotated by same amount, just compare the
4090 // original values.
4091 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4092 break;
4093 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4094 break;
4095 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4096 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4097
4098 // rotate(X, AmtX) == rotate(Y, AmtY)
4099 // -> rotate(X, AmtX - AmtY) == Y
4100 // Do this if either both rotates have one use or if only one has one use
4101 // and AmtX/AmtY are constants.
4102 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4103 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4104 if (OneUses == 2 ||
4105 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4106 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4107
4108 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4109 // of two.
4110 if (isPowerOf2_32(BW)) {
4111 Value *SubAmt =
4112 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4113 Value *CombinedRotate = Builder.CreateIntrinsic(
4114 Op0->getType(), IIOp0->getIntrinsicID(),
4115 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4116 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4117 }
4118 }
4119 } break;
4120 default:
4121 break;
4122 }
4123
4124 return nullptr;
4125}
4126
4127/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4128/// where X is some kind of instruction and C is AllowPoison.
4129/// TODO: Move more folds which allow poison to this function.
4132 const APInt &C) {
4133 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4134 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4135 switch (II->getIntrinsicID()) {
4136 default:
4137 break;
4138 case Intrinsic::fshl:
4139 case Intrinsic::fshr:
4140 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4141 // (rot X, ?) == 0/-1 --> X == 0/-1
4142 if (C.isZero() || C.isAllOnes())
4143 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4144 }
4145 break;
4146 }
4147 }
4148
4149 return nullptr;
4150}
4151
4152/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4154 BinaryOperator *BO,
4155 const APInt &C) {
4156 switch (BO->getOpcode()) {
4157 case Instruction::Xor:
4158 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4159 return I;
4160 break;
4161 case Instruction::And:
4162 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4163 return I;
4164 break;
4165 case Instruction::Or:
4166 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4167 return I;
4168 break;
4169 case Instruction::Mul:
4170 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4171 return I;
4172 break;
4173 case Instruction::Shl:
4174 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4175 return I;
4176 break;
4177 case Instruction::LShr:
4178 case Instruction::AShr:
4179 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4180 return I;
4181 break;
4182 case Instruction::SRem:
4183 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4184 return I;
4185 break;
4186 case Instruction::UDiv:
4187 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4188 return I;
4189 [[fallthrough]];
4190 case Instruction::SDiv:
4191 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4192 return I;
4193 break;
4194 case Instruction::Sub:
4195 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4196 return I;
4197 break;
4198 case Instruction::Add:
4199 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4200 return I;
4201 break;
4202 default:
4203 break;
4204 }
4205
4206 // TODO: These folds could be refactored to be part of the above calls.
4208 return I;
4209
4210 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4211 // : C4), C5` pattern, by computing a truth table of the four constant
4212 // variants.
4214}
4215
4216static Instruction *
4218 const APInt &C,
4219 InstCombiner::BuilderTy &Builder) {
4220 // This transform may end up producing more than one instruction for the
4221 // intrinsic, so limit it to one user of the intrinsic.
4222 if (!II->hasOneUse())
4223 return nullptr;
4224
4225 // Let Y = [add/sub]_sat(X, C) pred C2
4226 // SatVal = The saturating value for the operation
4227 // WillWrap = Whether or not the operation will underflow / overflow
4228 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4229 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4230 //
4231 // When (SatVal pred C2) is true, then
4232 // Y = WillWrap ? true : ((X binop C) pred C2)
4233 // => Y = WillWrap || ((X binop C) pred C2)
4234 // else
4235 // Y = WillWrap ? false : ((X binop C) pred C2)
4236 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4237 // => Y = !WillWrap && ((X binop C) pred C2)
4238 Value *Op0 = II->getOperand(0);
4239 Value *Op1 = II->getOperand(1);
4240
4241 const APInt *COp1;
4242 // This transform only works when the intrinsic has an integral constant or
4243 // splat vector as the second operand.
4244 if (!match(Op1, m_APInt(COp1)))
4245 return nullptr;
4246
4247 APInt SatVal;
4248 switch (II->getIntrinsicID()) {
4249 default:
4251 "This function only works with usub_sat and uadd_sat for now!");
4252 case Intrinsic::uadd_sat:
4253 SatVal = APInt::getAllOnes(C.getBitWidth());
4254 break;
4255 case Intrinsic::usub_sat:
4256 SatVal = APInt::getZero(C.getBitWidth());
4257 break;
4258 }
4259
4260 // Check (SatVal pred C2)
4261 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4262
4263 // !WillWrap.
4265 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4266
4267 // WillWrap.
4268 if (SatValCheck)
4269 C1 = C1.inverse();
4270
4272 if (II->getBinaryOp() == Instruction::Add)
4273 C2 = C2.sub(*COp1);
4274 else
4275 C2 = C2.add(*COp1);
4276
4277 Instruction::BinaryOps CombiningOp =
4278 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4279
4280 std::optional<ConstantRange> Combination;
4281 if (CombiningOp == Instruction::BinaryOps::Or)
4282 Combination = C1.exactUnionWith(C2);
4283 else /* CombiningOp == Instruction::BinaryOps::And */
4284 Combination = C1.exactIntersectWith(C2);
4285
4286 if (!Combination)
4287 return nullptr;
4288
4289 CmpInst::Predicate EquivPred;
4290 APInt EquivInt;
4291 APInt EquivOffset;
4292
4293 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4294
4295 return new ICmpInst(
4296 EquivPred,
4297 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4298 ConstantInt::get(Op1->getType(), EquivInt));
4299}
4300
4301static Instruction *
4303 const APInt &C,
4304 InstCombiner::BuilderTy &Builder) {
4305 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4306 switch (Pred) {
4307 case ICmpInst::ICMP_EQ:
4308 case ICmpInst::ICMP_NE:
4309 if (C.isZero())
4310 NewPredicate = Pred;
4311 else if (C.isOne())
4312 NewPredicate =
4314 else if (C.isAllOnes())
4315 NewPredicate =
4317 break;
4318
4319 case ICmpInst::ICMP_SGT:
4320 if (C.isAllOnes())
4321 NewPredicate = ICmpInst::ICMP_UGE;
4322 else if (C.isZero())
4323 NewPredicate = ICmpInst::ICMP_UGT;
4324 break;
4325
4326 case ICmpInst::ICMP_SLT:
4327 if (C.isZero())
4328 NewPredicate = ICmpInst::ICMP_ULT;
4329 else if (C.isOne())
4330 NewPredicate = ICmpInst::ICMP_ULE;
4331 break;
4332
4333 case ICmpInst::ICMP_ULT:
4334 if (C.ugt(1))
4335 NewPredicate = ICmpInst::ICMP_UGE;
4336 break;
4337
4338 case ICmpInst::ICMP_UGT:
4339 if (!C.isZero() && !C.isAllOnes())
4340 NewPredicate = ICmpInst::ICMP_ULT;
4341 break;
4342
4343 default:
4344 break;
4345 }
4346
4347 if (!NewPredicate)
4348 return nullptr;
4349
4350 if (I->getIntrinsicID() == Intrinsic::scmp)
4351 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4352 Value *LHS = I->getOperand(0);
4353 Value *RHS = I->getOperand(1);
4354 return new ICmpInst(*NewPredicate, LHS, RHS);
4355}
4356
4357/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4360 const APInt &C) {
4361 ICmpInst::Predicate Pred = Cmp.getPredicate();
4362
4363 // Handle folds that apply for any kind of icmp.
4364 switch (II->getIntrinsicID()) {
4365 default:
4366 break;
4367 case Intrinsic::uadd_sat:
4368 case Intrinsic::usub_sat:
4369 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4370 Pred, cast<SaturatingInst>(II), C, Builder))
4371 return Folded;
4372 break;
4373 case Intrinsic::ctpop: {
4374 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4375 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4376 return R;
4377 } break;
4378 case Intrinsic::scmp:
4379 case Intrinsic::ucmp:
4380 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4381 return Folded;
4382 break;
4383 }
4384
4385 if (Cmp.isEquality())
4386 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4387
4388 Type *Ty = II->getType();
4389 unsigned BitWidth = C.getBitWidth();
4390 switch (II->getIntrinsicID()) {
4391 case Intrinsic::ctpop: {
4392 // (ctpop X > BitWidth - 1) --> X == -1
4393 Value *X = II->getArgOperand(0);
4394 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4395 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4397 // (ctpop X < BitWidth) --> X != -1
4398 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4399 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4401 break;
4402 }
4403 case Intrinsic::ctlz: {
4404 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4405 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4406 unsigned Num = C.getLimitedValue();
4407 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4408 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4409 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4410 }
4411
4412 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4413 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4414 unsigned Num = C.getLimitedValue();
4416 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4417 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4418 }
4419 break;
4420 }
4421 case Intrinsic::cttz: {
4422 // Limit to one use to ensure we don't increase instruction count.
4423 if (!II->hasOneUse())
4424 return nullptr;
4425
4426 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4427 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4428 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4429 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4430 Builder.CreateAnd(II->getArgOperand(0), Mask),
4432 }
4433
4434 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4435 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4436 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4437 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4438 Builder.CreateAnd(II->getArgOperand(0), Mask),
4440 }
4441 break;
4442 }
4443 case Intrinsic::ssub_sat:
4444 // ssub.sat(a, b) spred 0 -> a spred b
4445 //
4446 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4447 // (because 1 saturates to 0). Just skip the optimization for i1.
4448 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4449 if (C.isZero())
4450 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4451 // X s<= 0 is cannonicalized to X s< 1
4452 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4453 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4454 II->getArgOperand(1));
4455 // X s>= 0 is cannonicalized to X s> -1
4456 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4457 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4458 II->getArgOperand(1));
4459 }
4460 break;
4461 case Intrinsic::abs: {
4462 if (!II->hasOneUse())
4463 return nullptr;
4464
4465 Value *X = II->getArgOperand(0);
4466
4467 // If C >= 0:
4468 // abs(X) u> C --> X + C u> 2 * C
4469 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4470 return new ICmpInst(ICmpInst::ICMP_UGT,
4471 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4472 ConstantInt::get(Ty, 2 * C));
4473 }
4474
4475 // If C >= 1:
4476 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4477 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4478 return new ICmpInst(ICmpInst::ICMP_ULE,
4479 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4480 ConstantInt::get(Ty, 2 * (C - 1)));
4481
4482 break;
4483 }
4484 default:
4485 break;
4486 }
4487
4488 return nullptr;
4489}
4490
4491/// Handle icmp with constant (but not simple integer constant) RHS.
4493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4494 Constant *RHSC = dyn_cast<Constant>(Op1);
4496 if (!RHSC || !LHSI)
4497 return nullptr;
4498
4499 switch (LHSI->getOpcode()) {
4500 case Instruction::IntToPtr:
4501 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4502 if (isa<ConstantPointerNull>(RHSC)) {
4503 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4504 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4505 APInt NullPtrValue =
4506 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4507 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4508 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4509 }
4510 }
4511 break;
4512
4513 case Instruction::Load:
4514 // Try to optimize things like "A[i] > 4" to index computations.
4515 if (GetElementPtrInst *GEP =
4518 cast<LoadInst>(LHSI), GEP, I.getPredicate(), RHSC, I))
4519 return Res;
4520 break;
4521 }
4522
4523 return nullptr;
4524}
4525
4527 Value *RHS, const ICmpInst &I) {
4528 // Try to fold the comparison into the select arms, which will cause the
4529 // select to be converted into a logical and/or.
4530 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4531 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4532 return Res;
4533 if (std::optional<bool> Impl = isImpliedCondition(
4534 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4535 return ConstantInt::get(I.getType(), *Impl);
4536 return nullptr;
4537 };
4538
4539 ConstantInt *CI = nullptr;
4540 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4541 if (Op1)
4542 CI = dyn_cast<ConstantInt>(Op1);
4543
4544 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4545 if (Op2)
4546 CI = dyn_cast<ConstantInt>(Op2);
4547
4548 auto Simplifies = [&](Value *Op, unsigned Idx) {
4549 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4550 const APInt *Dummy;
4551 return Op ||
4552 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4553 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4554 };
4555
4556 // We only want to perform this transformation if it will not lead to
4557 // additional code. This is true if either both sides of the select
4558 // fold to a constant (in which case the icmp is replaced with a select
4559 // which will usually simplify) or this is the only user of the
4560 // select (in which case we are trading a select+icmp for a simpler
4561 // select+icmp) or all uses of the select can be replaced based on
4562 // dominance information ("Global cases").
4563 bool Transform = false;
4564 if (Op1 && Op2)
4565 Transform = true;
4566 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4567 // Local case
4568 if (SI->hasOneUse())
4569 Transform = true;
4570 // Global cases
4571 else if (CI && !CI->isZero())
4572 // When Op1 is constant try replacing select with second operand.
4573 // Otherwise Op2 is constant and try replacing select with first
4574 // operand.
4575 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4576 }
4577 if (Transform) {
4578 if (!Op1)
4579 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4580 if (!Op2)
4581 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4582 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
4583 }
4584
4585 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4586 // When the select condition compares X with a constant P and the select
4587 // arms are constants C1/C2, we can fold to a set membership test.
4588 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4589 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4590 if (ICmpInst::isEquality(Pred)) {
4591 CmpPredicate CondPred;
4592 const APInt *C1, *C2, *P;
4593 if (match(SI,
4594 m_OneUse(m_Select(m_ICmp(CondPred, m_Specific(RHS), m_APInt(P)),
4595 m_APInt(C1), m_APInt(C2))))) {
4596 bool C1SatisfiesCond = ICmpInst::compare(*C1, *P, CondPred);
4597 bool C2SatisfiesCond = ICmpInst::compare(*C2, *P, CondPred);
4598
4599 if (C1SatisfiesCond && !C2SatisfiesCond) {
4600 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4601 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4602 Value *Cmp1 = Builder.CreateICmp(Pred, RHS, SI->getTrueValue());
4603 Value *Cmp2 = Builder.CreateICmp(Pred, RHS, SI->getFalseValue());
4604 if (Pred == ICmpInst::ICMP_EQ)
4605 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4606 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4607 }
4608 }
4609 }
4610
4611 return nullptr;
4612}
4613
4614// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4615static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4616 unsigned Depth = 0) {
4617 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4618 return true;
4619 if (V->getType()->getScalarSizeInBits() == 1)
4620 return true;
4622 return false;
4623 Value *X;
4625 if (!I)
4626 return false;
4627 switch (I->getOpcode()) {
4628 case Instruction::ZExt:
4629 // ZExt(Mask) is a Mask.
4630 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4631 case Instruction::SExt:
4632 // SExt(Mask) is a Mask.
4633 // SExt(~Mask) is a ~Mask.
4634 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4635 case Instruction::And:
4636 case Instruction::Or:
4637 // Mask0 | Mask1 is a Mask.
4638 // Mask0 & Mask1 is a Mask.
4639 // ~Mask0 | ~Mask1 is a ~Mask.
4640 // ~Mask0 & ~Mask1 is a ~Mask.
4641 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4642 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4643 case Instruction::Xor:
4644 if (match(V, m_Not(m_Value(X))))
4645 return isMaskOrZero(X, !Not, Q, Depth);
4646
4647 // (X ^ -X) is a ~Mask
4648 if (Not)
4649 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4650 // (X ^ (X - 1)) is a Mask
4651 else
4652 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4653 case Instruction::Select:
4654 // c ? Mask0 : Mask1 is a Mask.
4655 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4656 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4657 case Instruction::Shl:
4658 // (~Mask) << X is a ~Mask.
4659 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4660 case Instruction::LShr:
4661 // Mask >> X is a Mask.
4662 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4663 case Instruction::AShr:
4664 // Mask s>> X is a Mask.
4665 // ~Mask s>> X is a ~Mask.
4666 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4667 case Instruction::Add:
4668 // Pow2 - 1 is a Mask.
4669 if (!Not && match(I->getOperand(1), m_AllOnes()))
4670 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4671 Q.AC, Q.CtxI, Q.DT, Depth);
4672 break;
4673 case Instruction::Sub:
4674 // -Pow2 is a ~Mask.
4675 if (Not && match(I->getOperand(0), m_Zero()))
4676 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4677 Q.AC, Q.CtxI, Q.DT, Depth);
4678 break;
4679 case Instruction::Call: {
4680 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4681 switch (II->getIntrinsicID()) {
4682 // min/max(Mask0, Mask1) is a Mask.
4683 // min/max(~Mask0, ~Mask1) is a ~Mask.
4684 case Intrinsic::umax:
4685 case Intrinsic::smax:
4686 case Intrinsic::umin:
4687 case Intrinsic::smin:
4688 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4689 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4690
4691 // In the context of masks, bitreverse(Mask) == ~Mask
4692 case Intrinsic::bitreverse:
4693 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4694 default:
4695 break;
4696 }
4697 }
4698 break;
4699 }
4700 default:
4701 break;
4702 }
4703 return false;
4704}
4705
4706/// Some comparisons can be simplified.
4707/// In this case, we are looking for comparisons that look like
4708/// a check for a lossy truncation.
4709/// Folds:
4710/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4711/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4712/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4713/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4714/// Where Mask is some pattern that produces all-ones in low bits:
4715/// (-1 >> y)
4716/// ((-1 << y) >> y) <- non-canonical, has extra uses
4717/// ~(-1 << y)
4718/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4719/// The Mask can be a constant, too.
4720/// For some predicates, the operands are commutative.
4721/// For others, x can only be on a specific side.
4723 Value *Op1, const SimplifyQuery &Q,
4724 InstCombiner &IC) {
4725
4726 ICmpInst::Predicate DstPred;
4727 switch (Pred) {
4729 // x & Mask == x
4730 // x & ~Mask == 0
4731 // ~x | Mask == -1
4732 // -> x u<= Mask
4733 // x & ~Mask == ~Mask
4734 // -> ~Mask u<= x
4736 break;
4738 // x & Mask != x
4739 // x & ~Mask != 0
4740 // ~x | Mask != -1
4741 // -> x u> Mask
4742 // x & ~Mask != ~Mask
4743 // -> ~Mask u> x
4745 break;
4747 // x & Mask u< x
4748 // -> x u> Mask
4749 // x & ~Mask u< ~Mask
4750 // -> ~Mask u> x
4752 break;
4754 // x & Mask u>= x
4755 // -> x u<= Mask
4756 // x & ~Mask u>= ~Mask
4757 // -> ~Mask u<= x
4759 break;
4761 // x & Mask s< x [iff Mask s>= 0]
4762 // -> x s> Mask
4763 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4764 // -> ~Mask s> x
4766 break;
4768 // x & Mask s>= x [iff Mask s>= 0]
4769 // -> x s<= Mask
4770 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4771 // -> ~Mask s<= x
4773 break;
4774 default:
4775 // We don't support sgt,sle
4776 // ult/ugt are simplified to true/false respectively.
4777 return nullptr;
4778 }
4779
4780 Value *X, *M;
4781 // Put search code in lambda for early positive returns.
4782 auto IsLowBitMask = [&]() {
4783 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4784 X = Op1;
4785 // Look for: x & Mask pred x
4786 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4787 return !ICmpInst::isSigned(Pred) ||
4788 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4789 }
4790
4791 // Look for: x & ~Mask pred ~Mask
4792 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4793 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4794 }
4795 return false;
4796 }
4797 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4798 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4799
4800 auto Check = [&]() {
4801 // Look for: ~x | Mask == -1
4802 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4803 if (Value *NotX =
4804 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4805 X = NotX;
4806 return true;
4807 }
4808 }
4809 return false;
4810 };
4811 if (Check())
4812 return true;
4813 std::swap(X, M);
4814 return Check();
4815 }
4816 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4817 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4818 auto Check = [&]() {
4819 // Look for: x & ~Mask == 0
4820 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4821 if (Value *NotM =
4822 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4823 M = NotM;
4824 return true;
4825 }
4826 }
4827 return false;
4828 };
4829 if (Check())
4830 return true;
4831 std::swap(X, M);
4832 return Check();
4833 }
4834 return false;
4835 };
4836
4837 if (!IsLowBitMask())
4838 return nullptr;
4839
4840 return IC.Builder.CreateICmp(DstPred, X, M);
4841}
4842
4843/// Some comparisons can be simplified.
4844/// In this case, we are looking for comparisons that look like
4845/// a check for a lossy signed truncation.
4846/// Folds: (MaskedBits is a constant.)
4847/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4848/// Into:
4849/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4850/// Where KeptBits = bitwidth(%x) - MaskedBits
4851static Value *
4853 InstCombiner::BuilderTy &Builder) {
4854 CmpPredicate SrcPred;
4855 Value *X;
4856 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4857 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4858 if (!match(&I, m_c_ICmp(SrcPred,
4860 m_APInt(C1))),
4861 m_Deferred(X))))
4862 return nullptr;
4863
4864 // Potential handling of non-splats: for each element:
4865 // * if both are undef, replace with constant 0.
4866 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4867 // * if both are not undef, and are different, bailout.
4868 // * else, only one is undef, then pick the non-undef one.
4869
4870 // The shift amount must be equal.
4871 if (*C0 != *C1)
4872 return nullptr;
4873 const APInt &MaskedBits = *C0;
4874 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4875
4876 ICmpInst::Predicate DstPred;
4877 switch (SrcPred) {
4879 // ((%x << MaskedBits) a>> MaskedBits) == %x
4880 // =>
4881 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4883 break;
4885 // ((%x << MaskedBits) a>> MaskedBits) != %x
4886 // =>
4887 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4889 break;
4890 // FIXME: are more folds possible?
4891 default:
4892 return nullptr;
4893 }
4894
4895 auto *XType = X->getType();
4896 const unsigned XBitWidth = XType->getScalarSizeInBits();
4897 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4898 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4899
4900 // KeptBits = bitwidth(%x) - MaskedBits
4901 const APInt KeptBits = BitWidth - MaskedBits;
4902 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4903 // ICmpCst = (1 << KeptBits)
4904 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4905 assert(ICmpCst.isPowerOf2());
4906 // AddCst = (1 << (KeptBits-1))
4907 const APInt AddCst = ICmpCst.lshr(1);
4908 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4909
4910 // T0 = add %x, AddCst
4911 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4912 // T1 = T0 DstPred ICmpCst
4913 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4914
4915 return T1;
4916}
4917
4918// Given pattern:
4919// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4920// we should move shifts to the same hand of 'and', i.e. rewrite as
4921// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4922// We are only interested in opposite logical shifts here.
4923// One of the shifts can be truncated.
4924// If we can, we want to end up creating 'lshr' shift.
4925static Value *
4927 InstCombiner::BuilderTy &Builder) {
4928 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4929 !I.getOperand(0)->hasOneUse())
4930 return nullptr;
4931
4932 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4933
4934 // Look for an 'and' of two logical shifts, one of which may be truncated.
4935 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4936 Instruction *XShift, *MaybeTruncation, *YShift;
4937 if (!match(
4938 I.getOperand(0),
4939 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4941 m_AnyLogicalShift, m_Instruction(YShift))),
4942 m_Instruction(MaybeTruncation)))))
4943 return nullptr;
4944
4945 // We potentially looked past 'trunc', but only when matching YShift,
4946 // therefore YShift must have the widest type.
4947 Instruction *WidestShift = YShift;
4948 // Therefore XShift must have the shallowest type.
4949 // Or they both have identical types if there was no truncation.
4950 Instruction *NarrowestShift = XShift;
4951
4952 Type *WidestTy = WidestShift->getType();
4953 Type *NarrowestTy = NarrowestShift->getType();
4954 assert(NarrowestTy == I.getOperand(0)->getType() &&
4955 "We did not look past any shifts while matching XShift though.");
4956 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4957
4958 // If YShift is a 'lshr', swap the shifts around.
4959 if (match(YShift, m_LShr(m_Value(), m_Value())))
4960 std::swap(XShift, YShift);
4961
4962 // The shifts must be in opposite directions.
4963 auto XShiftOpcode = XShift->getOpcode();
4964 if (XShiftOpcode == YShift->getOpcode())
4965 return nullptr; // Do not care about same-direction shifts here.
4966
4967 Value *X, *XShAmt, *Y, *YShAmt;
4968 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4969 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4970
4971 // If one of the values being shifted is a constant, then we will end with
4972 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4973 // however, we will need to ensure that we won't increase instruction count.
4974 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4975 // At least one of the hands of the 'and' should be one-use shift.
4976 if (!match(I.getOperand(0),
4977 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4978 return nullptr;
4979 if (HadTrunc) {
4980 // Due to the 'trunc', we will need to widen X. For that either the old
4981 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4982 if (!MaybeTruncation->hasOneUse() &&
4983 !NarrowestShift->getOperand(1)->hasOneUse())
4984 return nullptr;
4985 }
4986 }
4987
4988 // We have two shift amounts from two different shifts. The types of those
4989 // shift amounts may not match. If that's the case let's bailout now.
4990 if (XShAmt->getType() != YShAmt->getType())
4991 return nullptr;
4992
4993 // As input, we have the following pattern:
4994 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4995 // We want to rewrite that as:
4996 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4997 // While we know that originally (Q+K) would not overflow
4998 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4999 // shift amounts. so it may now overflow in smaller bitwidth.
5000 // To ensure that does not happen, we need to ensure that the total maximal
5001 // shift amount is still representable in that smaller bit width.
5002 unsigned MaximalPossibleTotalShiftAmount =
5003 (WidestTy->getScalarSizeInBits() - 1) +
5004 (NarrowestTy->getScalarSizeInBits() - 1);
5005 APInt MaximalRepresentableShiftAmount =
5007 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
5008 return nullptr;
5009
5010 // Can we fold (XShAmt+YShAmt) ?
5011 auto *NewShAmt = dyn_cast_or_null<Constant>(
5012 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
5013 /*isNUW=*/false, SQ.getWithInstruction(&I)));
5014 if (!NewShAmt)
5015 return nullptr;
5016 if (NewShAmt->getType() != WidestTy) {
5017 NewShAmt =
5018 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
5019 if (!NewShAmt)
5020 return nullptr;
5021 }
5022 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
5023
5024 // Is the new shift amount smaller than the bit width?
5025 // FIXME: could also rely on ConstantRange.
5026 if (!match(NewShAmt,
5028 APInt(WidestBitWidth, WidestBitWidth))))
5029 return nullptr;
5030
5031 // An extra legality check is needed if we had trunc-of-lshr.
5032 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
5033 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5034 WidestShift]() {
5035 // It isn't obvious whether it's worth it to analyze non-constants here.
5036 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5037 // If *any* of these preconditions matches we can perform the fold.
5038 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5039 ? NewShAmt->getSplatValue()
5040 : NewShAmt;
5041 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5042 if (NewShAmtSplat &&
5043 (NewShAmtSplat->isNullValue() ||
5044 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5045 return true;
5046 // We consider *min* leading zeros so a single outlier
5047 // blocks the transform as opposed to allowing it.
5048 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
5050 unsigned MinLeadZero = Known.countMinLeadingZeros();
5051 // If the value being shifted has at most lowest bit set we can fold.
5052 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5053 if (MaxActiveBits <= 1)
5054 return true;
5055 // Precondition: NewShAmt u<= countLeadingZeros(C)
5056 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5057 return true;
5058 }
5059 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5061 unsigned MinLeadZero = Known.countMinLeadingZeros();
5062 // If the value being shifted has at most lowest bit set we can fold.
5063 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5064 if (MaxActiveBits <= 1)
5065 return true;
5066 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5067 if (NewShAmtSplat) {
5068 APInt AdjNewShAmt =
5069 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5070 if (AdjNewShAmt.ule(MinLeadZero))
5071 return true;
5072 }
5073 }
5074 return false; // Can't tell if it's ok.
5075 };
5076 if (!CanFold())
5077 return nullptr;
5078 }
5079
5080 // All good, we can do this fold.
5081 X = Builder.CreateZExt(X, WidestTy);
5082 Y = Builder.CreateZExt(Y, WidestTy);
5083 // The shift is the same that was for X.
5084 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5085 ? Builder.CreateLShr(X, NewShAmt)
5086 : Builder.CreateShl(X, NewShAmt);
5087 Value *T1 = Builder.CreateAnd(T0, Y);
5088 return Builder.CreateICmp(I.getPredicate(), T1,
5089 Constant::getNullValue(WidestTy));
5090}
5091
5092/// Fold
5093/// (-1 u/ x) u< y
5094/// ((x * y) ?/ x) != y
5095/// to
5096/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5097/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5098/// will mean that we are looking for the opposite answer.
5100 CmpPredicate Pred;
5101 Value *X, *Y;
5103 Instruction *Div;
5104 bool NeedNegation;
5105 // Look for: (-1 u/ x) u</u>= y
5106 if (!I.isEquality() &&
5107 match(&I, m_c_ICmp(Pred,
5109 m_Instruction(Div)),
5110 m_Value(Y)))) {
5111 Mul = nullptr;
5112
5113 // Are we checking that overflow does not happen, or does happen?
5114 switch (Pred) {
5116 NeedNegation = false;
5117 break; // OK
5119 NeedNegation = true;
5120 break; // OK
5121 default:
5122 return nullptr; // Wrong predicate.
5123 }
5124 } else // Look for: ((x * y) / x) !=/== y
5125 if (I.isEquality() &&
5126 match(&I, m_c_ICmp(Pred, m_Value(Y),
5129 m_Value(X)),
5131 m_Deferred(X))),
5132 m_Instruction(Div))))) {
5133 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5134 } else
5135 return nullptr;
5136
5138 // If the pattern included (x * y), we'll want to insert new instructions
5139 // right before that original multiplication so that we can replace it.
5140 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5141 if (MulHadOtherUses)
5142 Builder.SetInsertPoint(Mul);
5143
5144 Value *Call = Builder.CreateIntrinsic(
5145 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5146 : Intrinsic::smul_with_overflow,
5147 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5148
5149 // If the multiplication was used elsewhere, to ensure that we don't leave
5150 // "duplicate" instructions, replace uses of that original multiplication
5151 // with the multiplication result from the with.overflow intrinsic.
5152 if (MulHadOtherUses)
5153 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5154
5155 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5156 if (NeedNegation) // This technically increases instruction count.
5157 Res = Builder.CreateNot(Res, "mul.not.ov");
5158
5159 // If we replaced the mul, erase it. Do this after all uses of Builder,
5160 // as the mul is used as insertion point.
5161 if (MulHadOtherUses)
5163
5164 return Res;
5165}
5166
5168 InstCombiner::BuilderTy &Builder) {
5169 CmpPredicate Pred;
5170 Value *X;
5171 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5172
5173 if (ICmpInst::isSigned(Pred))
5174 Pred = ICmpInst::getSwappedPredicate(Pred);
5175 else if (ICmpInst::isUnsigned(Pred))
5176 Pred = ICmpInst::getSignedPredicate(Pred);
5177 // else for equality-comparisons just keep the predicate.
5178
5179 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5180 Constant::getNullValue(X->getType()), I.getName());
5181 }
5182
5183 // A value is not equal to its negation unless that value is 0 or
5184 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5185 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5186 ICmpInst::isEquality(Pred)) {
5187 Type *Ty = X->getType();
5188 uint32_t BitWidth = Ty->getScalarSizeInBits();
5189 Constant *MaxSignedVal =
5190 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5191 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5192 Constant *Zero = Constant::getNullValue(Ty);
5193 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5194 }
5195
5196 return nullptr;
5197}
5198
5200 InstCombinerImpl &IC) {
5201 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5202 // Normalize and operand as operand 0.
5203 CmpInst::Predicate Pred = I.getPredicate();
5204 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5205 std::swap(Op0, Op1);
5206 Pred = ICmpInst::getSwappedPredicate(Pred);
5207 }
5208
5209 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5210 return nullptr;
5211
5212 // (icmp (X & Y) u< X --> (X & Y) != X
5213 if (Pred == ICmpInst::ICMP_ULT)
5214 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5215
5216 // (icmp (X & Y) u>= X --> (X & Y) == X
5217 if (Pred == ICmpInst::ICMP_UGE)
5218 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5219
5220 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5221 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5222 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5223 // so don't do this fold.
5224 if (!match(Op1, m_ImmConstant()))
5225 if (auto *NotOp1 =
5226 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5227 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5228 Constant::getAllOnesValue(Op1->getType()));
5229 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5230 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5231 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5232 Constant::getNullValue(Op1->getType()));
5233 }
5234
5235 if (!ICmpInst::isSigned(Pred))
5236 return nullptr;
5237
5238 KnownBits KnownY = IC.computeKnownBits(A, &I);
5239 // (X & NegY) spred X --> (X & NegY) upred X
5240 if (KnownY.isNegative())
5241 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5242
5243 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5244 return nullptr;
5245
5246 if (KnownY.isNonNegative())
5247 // (X & PosY) s<= X --> X s>= 0
5248 // (X & PosY) s> X --> X s< 0
5249 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5250 Constant::getNullValue(Op1->getType()));
5251
5253 // (NegX & Y) s<= NegX --> Y s< 0
5254 // (NegX & Y) s> NegX --> Y s>= 0
5256 Constant::getNullValue(A->getType()));
5257
5258 return nullptr;
5259}
5260
5262 InstCombinerImpl &IC) {
5263 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5264
5265 // Normalize or operand as operand 0.
5266 CmpInst::Predicate Pred = I.getPredicate();
5267 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5268 std::swap(Op0, Op1);
5269 Pred = ICmpInst::getSwappedPredicate(Pred);
5270 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5271 return nullptr;
5272 }
5273
5274 // icmp (X | Y) u<= X --> (X | Y) == X
5275 if (Pred == ICmpInst::ICMP_ULE)
5276 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5277
5278 // icmp (X | Y) u> X --> (X | Y) != X
5279 if (Pred == ICmpInst::ICMP_UGT)
5280 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5281
5282 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5283 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5284 if (Value *NotOp1 = IC.getFreelyInverted(
5285 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5286 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5287 Constant::getNullValue(Op1->getType()));
5288 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5289 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5290 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5291 Constant::getAllOnesValue(Op1->getType()));
5292 }
5293 return nullptr;
5294}
5295
5297 InstCombinerImpl &IC) {
5298 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5299 // Normalize xor operand as operand 0.
5300 CmpInst::Predicate Pred = I.getPredicate();
5301 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5302 std::swap(Op0, Op1);
5303 Pred = ICmpInst::getSwappedPredicate(Pred);
5304 }
5305 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5306 return nullptr;
5307
5308 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5309 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5310 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5311 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5313 if (PredOut != Pred && isKnownNonZero(A, Q))
5314 return new ICmpInst(PredOut, Op0, Op1);
5315
5316 // These transform work when A is negative.
5317 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5318 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5319 if (match(A, m_Negative())) {
5320 CmpInst::Predicate NewPred;
5321 switch (ICmpInst::getStrictPredicate(Pred)) {
5322 default:
5323 return nullptr;
5324 case ICmpInst::ICMP_SLT:
5325 case ICmpInst::ICMP_UGT:
5326 NewPred = ICmpInst::ICMP_SLT;
5327 break;
5328 case ICmpInst::ICMP_SGT:
5329 case ICmpInst::ICMP_ULT:
5330 NewPred = ICmpInst::ICMP_SGE;
5331 break;
5332 }
5333 Constant *Const = Constant::getNullValue(Op0->getType());
5334 return new ICmpInst(NewPred, Op0, Const);
5335 }
5336
5337 return nullptr;
5338}
5339
5340/// Return true if X is a multiple of C.
5341/// TODO: Handle non-power-of-2 factors.
5342static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5343 if (C.isOne())
5344 return true;
5345
5346 if (!C.isPowerOf2())
5347 return false;
5348
5349 return MaskedValueIsZero(X, C - 1, Q);
5350}
5351
5352/// Try to fold icmp (binop), X or icmp X, (binop).
5353/// TODO: A large part of this logic is duplicated in InstSimplify's
5354/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5355/// duplication.
5357 const SimplifyQuery &SQ) {
5358 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5360
5361 // Special logic for binary operators.
5364 if (!BO0 && !BO1)
5365 return nullptr;
5366
5367 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5368 return NewICmp;
5369
5370 const CmpInst::Predicate Pred = I.getPredicate();
5371
5372 // (X urem Y) == X --> X u< Y
5373 // (X urem Y) != X --> X u>= Y
5374 Value *Dividend, *Divisor;
5375 if (I.isEquality() &&
5376 match(&I, m_c_ICmp(m_URem(m_Value(Dividend), m_Value(Divisor)),
5377 m_Deferred(Dividend)))) {
5378 CmpInst::Predicate NewPred =
5380 return new ICmpInst(NewPred, Dividend, Divisor);
5381 }
5382
5383 Value *X;
5384
5385 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5386 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5387 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5388 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5389 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5390 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5391 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5392 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5393 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5394
5395 {
5396 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5397 Constant *C;
5398 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5399 m_ImmConstant(C)))) &&
5400 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5402 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5403 }
5404 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5405 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5406 m_ImmConstant(C)))) &&
5407 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5409 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5410 }
5411 }
5412
5413 // (icmp eq/ne (X, -P2), INT_MIN)
5414 // -> (icmp slt/sge X, INT_MIN + P2)
5415 if (ICmpInst::isEquality(Pred) && BO0 &&
5416 match(I.getOperand(1), m_SignMask()) &&
5418 // Will Constant fold.
5419 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5420 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5422 BO0->getOperand(0), NewC);
5423 }
5424
5425 {
5426 // Similar to above: an unsigned overflow comparison may use offset + mask:
5427 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5428 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5429 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5430 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5431 BinaryOperator *BO;
5432 const APInt *C;
5433 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5434 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5436 CmpInst::Predicate NewPred =
5438 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5439 return new ICmpInst(NewPred, Op1, Zero);
5440 }
5441
5442 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5443 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5445 CmpInst::Predicate NewPred =
5447 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5448 return new ICmpInst(NewPred, Op0, Zero);
5449 }
5450 }
5451
5452 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5453 bool Op0HasNUW = false, Op1HasNUW = false;
5454 bool Op0HasNSW = false, Op1HasNSW = false;
5455 // Analyze the case when either Op0 or Op1 is an add instruction.
5456 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5457 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5458 bool &HasNSW, bool &HasNUW) -> bool {
5460 HasNUW = BO.hasNoUnsignedWrap();
5461 HasNSW = BO.hasNoSignedWrap();
5462 return ICmpInst::isEquality(Pred) ||
5463 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5464 (CmpInst::isSigned(Pred) && HasNSW);
5465 } else if (BO.getOpcode() == Instruction::Or) {
5466 // The invariant here is that we are handling m_AddLike instructions,
5467 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5468 HasNUW = true;
5469 HasNSW = true;
5470 return true;
5471 } else {
5472 return false;
5473 }
5474 };
5475 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5476
5477 if (BO0) {
5478 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5479 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5480 }
5481 if (BO1) {
5482 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5483 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5484 }
5485
5486 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5487 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5488 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5489 return new ICmpInst(Pred, A == Op1 ? B : A,
5490 Constant::getNullValue(Op1->getType()));
5491
5492 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5493 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5494 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5495 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5496 C == Op0 ? D : C);
5497
5498 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5499 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5500 NoOp1WrapProblem) {
5501 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5502 Value *Y, *Z;
5503 if (A == C) {
5504 // C + B == C + D -> B == D
5505 Y = B;
5506 Z = D;
5507 } else if (A == D) {
5508 // D + B == C + D -> B == C
5509 Y = B;
5510 Z = C;
5511 } else if (B == C) {
5512 // A + C == C + D -> A == D
5513 Y = A;
5514 Z = D;
5515 } else {
5516 assert(B == D);
5517 // A + D == C + D -> A == C
5518 Y = A;
5519 Z = C;
5520 }
5521 return new ICmpInst(Pred, Y, Z);
5522 }
5523
5524 if (ICmpInst::isRelational(Pred)) {
5525 // Return if both X and Y is divisible by Z/-Z.
5526 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5527 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5528 bool IsNegative) -> bool {
5529 const APInt *OffsetC;
5530 if (!match(Z, m_APInt(OffsetC)))
5531 return false;
5532
5533 // Fast path for Z == 1/-1.
5534 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5535 return true;
5536
5537 APInt C = *OffsetC;
5538 if (IsNegative)
5539 C.negate();
5540 // Note: -INT_MIN is also negative.
5541 if (!C.isStrictlyPositive())
5542 return false;
5543
5544 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5545 };
5546
5547 // The subtraction-related identities (A -nuw B) shown below require that
5548 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5549 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5550 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5551 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5552 // requires proving A <u B, for which the nowrap precondition can never be
5553 // satisfied. These are therefore skipped.
5554 //
5555 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5556 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5557 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5558 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5559
5560 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5561 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5562 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5563 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5564 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5565 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5566 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5567 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5568 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5569 ShareCommonDivisor(A, Op1, B, IsNegative))
5571 Op1);
5572
5573 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5574 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5575 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5576 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5577 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5578 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5579 if (C && NoOp1WrapProblem &&
5580 ShareCommonDivisor(Op0, C, D,
5581 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5583 C);
5584 }
5585
5586 // if C1 has greater magnitude than C2:
5587 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5588 // s.t. C3 = C1 - C2
5589 //
5590 // if C2 has greater magnitude than C1:
5591 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5592 // s.t. C3 = C2 - C1
5593 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5594 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5595 const APInt *AP1, *AP2;
5596 // TODO: Support non-uniform vectors.
5597 // TODO: Allow poison passthrough if B or D's element is poison.
5598 if (match(B, m_APIntAllowPoison(AP1)) &&
5599 match(D, m_APIntAllowPoison(AP2)) &&
5600 AP1->isNegative() == AP2->isNegative()) {
5601 APInt AP1Abs = AP1->abs();
5602 APInt AP2Abs = AP2->abs();
5603 if (AP1Abs.uge(AP2Abs)) {
5604 APInt Diff = *AP1 - *AP2;
5605 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5606 Value *NewAdd = Builder.CreateAdd(
5607 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5608 return new ICmpInst(Pred, NewAdd, C);
5609 } else {
5610 APInt Diff = *AP2 - *AP1;
5611 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5612 Value *NewAdd = Builder.CreateAdd(
5613 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5614 return new ICmpInst(Pred, A, NewAdd);
5615 }
5616 }
5617 Constant *Cst1, *Cst2;
5618 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5619 ICmpInst::isEquality(Pred)) {
5620 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5621 Value *NewAdd = Builder.CreateAdd(C, Diff);
5622 return new ICmpInst(Pred, A, NewAdd);
5623 }
5624 }
5625
5626 // Analyze the case when either Op0 or Op1 is a sub instruction.
5627 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5628 A = nullptr;
5629 B = nullptr;
5630 C = nullptr;
5631 D = nullptr;
5632 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5633 A = BO0->getOperand(0);
5634 B = BO0->getOperand(1);
5635 }
5636 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5637 C = BO1->getOperand(0);
5638 D = BO1->getOperand(1);
5639 }
5640
5641 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5642 if (A == Op1 && NoOp0WrapProblem)
5643 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5644 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5645 if (C == Op0 && NoOp1WrapProblem)
5646 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5647
5648 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5649 // (A - B) u>/u<= A --> B u>/u<= A
5650 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5651 return new ICmpInst(Pred, B, A);
5652 // C u</u>= (C - D) --> C u</u>= D
5653 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5654 return new ICmpInst(Pred, C, D);
5655 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5656 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5657 isKnownNonZero(B, Q))
5659 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5660 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5661 isKnownNonZero(D, Q))
5663
5664 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5665 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5666 return new ICmpInst(Pred, A, C);
5667
5668 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5669 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5670 return new ICmpInst(Pred, D, B);
5671
5672 // icmp (0-X) < cst --> x > -cst
5673 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5674 Value *X;
5675 if (match(BO0, m_Neg(m_Value(X))))
5676 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5677 if (RHSC->isNotMinSignedValue())
5678 return new ICmpInst(I.getSwappedPredicate(), X,
5679 ConstantExpr::getNeg(RHSC));
5680 }
5681
5682 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5683 return R;
5684 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5685 return R;
5686
5687 {
5688 // Try to remove shared multiplier from comparison:
5689 // X * Z pred Y * Z
5690 Value *X, *Y, *Z;
5691 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5692 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5693 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5694 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5695 if (ICmpInst::isSigned(Pred)) {
5696 if (Op0HasNSW && Op1HasNSW) {
5697 KnownBits ZKnown = computeKnownBits(Z, &I);
5698 if (ZKnown.isStrictlyPositive())
5699 return new ICmpInst(Pred, X, Y);
5700 if (ZKnown.isNegative())
5701 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5703 SQ.getWithInstruction(&I));
5704 if (LessThan && match(LessThan, m_One()))
5705 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5706 Constant::getNullValue(Z->getType()));
5707 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5708 SQ.getWithInstruction(&I));
5709 if (GreaterThan && match(GreaterThan, m_One()))
5710 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5711 }
5712 } else {
5713 bool NonZero;
5714 if (ICmpInst::isEquality(Pred)) {
5715 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5716 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5717 isKnownNonEqual(X, Y, SQ))
5718 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5719
5720 KnownBits ZKnown = computeKnownBits(Z, &I);
5721 // if Z % 2 != 0
5722 // X * Z eq/ne Y * Z -> X eq/ne Y
5723 if (ZKnown.countMaxTrailingZeros() == 0)
5724 return new ICmpInst(Pred, X, Y);
5725 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5726 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5727 // X * Z eq/ne Y * Z -> X eq/ne Y
5728 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5729 return new ICmpInst(Pred, X, Y);
5730 } else
5731 NonZero = isKnownNonZero(Z, Q);
5732
5733 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5734 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5735 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5736 return new ICmpInst(Pred, X, Y);
5737 }
5738 }
5739 }
5740
5741 BinaryOperator *SRem = nullptr;
5742 // icmp (srem X, Y), Y
5743 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5744 SRem = BO0;
5745 // icmp Y, (srem X, Y)
5746 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5747 Op0 == BO1->getOperand(1))
5748 SRem = BO1;
5749 if (SRem) {
5750 // We don't check hasOneUse to avoid increasing register pressure because
5751 // the value we use is the same value this instruction was already using.
5752 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5753 default:
5754 break;
5755 case ICmpInst::ICMP_EQ:
5756 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5757 case ICmpInst::ICMP_NE:
5758 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5759 case ICmpInst::ICMP_SGT:
5760 case ICmpInst::ICMP_SGE:
5761 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5763 case ICmpInst::ICMP_SLT:
5764 case ICmpInst::ICMP_SLE:
5765 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5767 }
5768 }
5769
5770 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5771 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5772 BO0->getOperand(1) == BO1->getOperand(1)) {
5773 switch (BO0->getOpcode()) {
5774 default:
5775 break;
5776 case Instruction::Add:
5777 case Instruction::Sub:
5778 case Instruction::Xor: {
5779 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5780 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5781
5782 const APInt *C;
5783 if (match(BO0->getOperand(1), m_APInt(C))) {
5784 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5785 if (C->isSignMask()) {
5786 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5787 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5788 }
5789
5790 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5791 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5792 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5793 NewPred = I.getSwappedPredicate(NewPred);
5794 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5795 }
5796 }
5797 break;
5798 }
5799 case Instruction::Mul: {
5800 if (!I.isEquality())
5801 break;
5802
5803 const APInt *C;
5804 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5805 !C->isOne()) {
5806 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5807 // Mask = -1 >> count-trailing-zeros(C).
5808 if (unsigned TZs = C->countr_zero()) {
5809 Constant *Mask = ConstantInt::get(
5810 BO0->getType(),
5811 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5812 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5813 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5814 return new ICmpInst(Pred, And1, And2);
5815 }
5816 }
5817 break;
5818 }
5819 case Instruction::UDiv:
5820 case Instruction::LShr:
5821 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5822 break;
5823 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5824
5825 case Instruction::SDiv:
5826 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5827 !BO0->isExact() || !BO1->isExact())
5828 break;
5829 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5830
5831 case Instruction::AShr:
5832 if (!BO0->isExact() || !BO1->isExact())
5833 break;
5834 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5835
5836 case Instruction::Shl: {
5837 bool NUW = Op0HasNUW && Op1HasNUW;
5838 bool NSW = Op0HasNSW && Op1HasNSW;
5839 if (!NUW && !NSW)
5840 break;
5841 if (!NSW && I.isSigned())
5842 break;
5843 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5844 }
5845 }
5846 }
5847
5848 if (BO0) {
5849 // Transform A & (L - 1) `ult` L --> L != 0
5850 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5851 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5852
5853 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5854 auto *Zero = Constant::getNullValue(BO0->getType());
5855 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5856 }
5857 }
5858
5859 // For unsigned predicates / eq / ne:
5860 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5861 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5862 if (!ICmpInst::isSigned(Pred)) {
5863 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5864 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5865 Constant::getNullValue(Op1->getType()));
5866 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5867 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5868 Constant::getNullValue(Op0->getType()), Op0);
5869 }
5870
5872 return replaceInstUsesWith(I, V);
5873
5874 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5875 return R;
5876
5878 return replaceInstUsesWith(I, V);
5879
5881 return replaceInstUsesWith(I, V);
5882
5883 return nullptr;
5884}
5885
5886/// Fold icmp Pred min|max(X, Y), Z.
5889 Value *Z, CmpPredicate Pred) {
5890 Value *X = MinMax->getLHS();
5891 Value *Y = MinMax->getRHS();
5892 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5893 return nullptr;
5894 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5895 // Revert the transform signed pred -> unsigned pred
5896 // TODO: We can flip the signedness of predicate if both operands of icmp
5897 // are negative.
5898 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5899 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5901 } else
5902 return nullptr;
5903 }
5904 SimplifyQuery Q = SQ.getWithInstruction(&I);
5905 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5906 if (!Val)
5907 return std::nullopt;
5908 if (match(Val, m_One()))
5909 return true;
5910 if (match(Val, m_Zero()))
5911 return false;
5912 return std::nullopt;
5913 };
5914 // Remove samesign here since it is illegal to keep it when we speculatively
5915 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5916 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5917 // -46, -32)`. `X` is allowed to be non-negative here.
5918 Pred = Pred.dropSameSign();
5919 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5920 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5921 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5922 return nullptr;
5923 if (!CmpXZ.has_value()) {
5924 std::swap(X, Y);
5925 std::swap(CmpXZ, CmpYZ);
5926 }
5927
5928 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5929 if (CmpYZ.has_value())
5930 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5931 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5932 };
5933
5934 switch (Pred) {
5935 case ICmpInst::ICMP_EQ:
5936 case ICmpInst::ICMP_NE: {
5937 // If X == Z:
5938 // Expr Result
5939 // min(X, Y) == Z X <= Y
5940 // max(X, Y) == Z X >= Y
5941 // min(X, Y) != Z X > Y
5942 // max(X, Y) != Z X < Y
5943 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5944 ICmpInst::Predicate NewPred =
5945 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5946 if (Pred == ICmpInst::ICMP_NE)
5947 NewPred = ICmpInst::getInversePredicate(NewPred);
5948 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5949 }
5950 // Otherwise (X != Z):
5951 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5952 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5953 if (!MinMaxCmpXZ.has_value()) {
5954 std::swap(X, Y);
5955 std::swap(CmpXZ, CmpYZ);
5956 // Re-check pre-condition X != Z
5957 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5958 break;
5959 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5960 }
5961 if (!MinMaxCmpXZ.has_value())
5962 break;
5963 if (*MinMaxCmpXZ) {
5964 // Expr Fact Result
5965 // min(X, Y) == Z X < Z false
5966 // max(X, Y) == Z X > Z false
5967 // min(X, Y) != Z X < Z true
5968 // max(X, Y) != Z X > Z true
5969 return replaceInstUsesWith(
5970 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5971 } else {
5972 // Expr Fact Result
5973 // min(X, Y) == Z X > Z Y == Z
5974 // max(X, Y) == Z X < Z Y == Z
5975 // min(X, Y) != Z X > Z Y != Z
5976 // max(X, Y) != Z X < Z Y != Z
5977 return FoldIntoCmpYZ();
5978 }
5979 break;
5980 }
5981 case ICmpInst::ICMP_SLT:
5982 case ICmpInst::ICMP_ULT:
5983 case ICmpInst::ICMP_SLE:
5984 case ICmpInst::ICMP_ULE:
5985 case ICmpInst::ICMP_SGT:
5986 case ICmpInst::ICMP_UGT:
5987 case ICmpInst::ICMP_SGE:
5988 case ICmpInst::ICMP_UGE: {
5989 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5990 if (*CmpXZ) {
5991 if (IsSame) {
5992 // Expr Fact Result
5993 // min(X, Y) < Z X < Z true
5994 // min(X, Y) <= Z X <= Z true
5995 // max(X, Y) > Z X > Z true
5996 // max(X, Y) >= Z X >= Z true
5997 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5998 } else {
5999 // Expr Fact Result
6000 // max(X, Y) < Z X < Z Y < Z
6001 // max(X, Y) <= Z X <= Z Y <= Z
6002 // min(X, Y) > Z X > Z Y > Z
6003 // min(X, Y) >= Z X >= Z Y >= Z
6004 return FoldIntoCmpYZ();
6005 }
6006 } else {
6007 if (IsSame) {
6008 // Expr Fact Result
6009 // min(X, Y) < Z X >= Z Y < Z
6010 // min(X, Y) <= Z X > Z Y <= Z
6011 // max(X, Y) > Z X <= Z Y > Z
6012 // max(X, Y) >= Z X < Z Y >= Z
6013 return FoldIntoCmpYZ();
6014 } else {
6015 // Expr Fact Result
6016 // max(X, Y) < Z X >= Z false
6017 // max(X, Y) <= Z X > Z false
6018 // min(X, Y) > Z X <= Z false
6019 // min(X, Y) >= Z X < Z false
6020 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6021 }
6022 }
6023 break;
6024 }
6025 default:
6026 break;
6027 }
6028
6029 return nullptr;
6030}
6031
6032/// Match and fold patterns like:
6033/// icmp eq/ne X, min(max(X, Lo), Hi)
6034/// which represents a range check and can be represented as a ConstantRange.
6035///
6036/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6037/// (X - Lo) u< (Hi + 1 - Lo)
6038/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6039/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6041 MinMaxIntrinsic *Min) {
6042 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6043 return nullptr;
6044
6045 const APInt *Lo = nullptr, *Hi = nullptr;
6046 if (Min->isSigned()) {
6047 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
6048 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
6049 return nullptr;
6050 } else {
6051 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
6052 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
6053 return nullptr;
6054 }
6055
6058 APInt C, Offset;
6059 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6060 CR.getEquivalentICmp(Pred, C, Offset);
6061 else
6062 CR.inverse().getEquivalentICmp(Pred, C, Offset);
6063
6064 if (!Offset.isZero())
6065 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
6066
6067 return replaceInstUsesWith(
6068 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6069}
6070
6071// Canonicalize checking for a power-of-2-or-zero value:
6073 InstCombiner::BuilderTy &Builder) {
6074 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6075 const CmpInst::Predicate Pred = I.getPredicate();
6076 Value *A = nullptr;
6077 bool CheckIs;
6078 if (I.isEquality()) {
6079 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6080 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6081 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6082 m_Deferred(A)))) ||
6083 !match(Op1, m_ZeroInt()))
6084 A = nullptr;
6085
6086 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6087 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6088 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6089 A = Op1;
6090 else if (match(Op1,
6092 A = Op0;
6093
6094 CheckIs = Pred == ICmpInst::ICMP_EQ;
6095 } else if (ICmpInst::isUnsigned(Pred)) {
6096 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6097 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6098
6099 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6101 m_Specific(Op1))))) {
6102 A = Op1;
6103 CheckIs = Pred == ICmpInst::ICMP_UGE;
6104 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6106 m_Specific(Op0))))) {
6107 A = Op0;
6108 CheckIs = Pred == ICmpInst::ICMP_ULE;
6109 }
6110 }
6111
6112 if (A) {
6113 Type *Ty = A->getType();
6114 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6115 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6116 ConstantInt::get(Ty, 2))
6117 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6118 ConstantInt::get(Ty, 1));
6119 }
6120
6121 return nullptr;
6122}
6123
6124/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6125using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6127 bool AllowRecursion) {
6129 if (!Inst || !Inst->hasOneUse())
6130 return;
6131
6132 switch (Inst->getOpcode()) {
6133 case Instruction::Add:
6134 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6135 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6136 break;
6137 case Instruction::Sub:
6138 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6139 break;
6140 case Instruction::Xor:
6141 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6142 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6143 break;
6144 case Instruction::Shl:
6145 if (Inst->hasNoSignedWrap())
6146 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6147 if (Inst->hasNoUnsignedWrap())
6148 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6149 break;
6150 case Instruction::Select:
6151 if (AllowRecursion) {
6152 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6153 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6154 }
6155 break;
6156 default:
6157 break;
6158 }
6159}
6160
6162
6167
6169 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6170 }
6172 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6173 }
6174 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6176 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6177 }
6178 bool isValid() const { return Kind != OffsetKind::Invalid; }
6180 switch (Kind) {
6182 llvm_unreachable("Invalid offset result");
6183 case OffsetKind::Value:
6184 return V0;
6185 case OffsetKind::Select:
6186 return Builder.CreateSelect(V0, V1, V2, "", MDFrom);
6187 }
6188 llvm_unreachable("Unknown OffsetKind enum");
6189 }
6190};
6191
6192/// Offset both sides of an equality icmp to see if we can save some
6193/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6194/// Note: This operation should not introduce poison.
6196 InstCombiner::BuilderTy &Builder,
6197 const SimplifyQuery &SQ) {
6198 assert(I.isEquality() && "Expected an equality icmp");
6199 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6200 if (!Op0->getType()->isIntOrIntVectorTy())
6201 return nullptr;
6202
6203 SmallVector<OffsetOp, 4> OffsetOps;
6204 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6205 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6206
6207 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6208 switch (BinOpc) {
6209 // V = shl nsw X, RHS => X = ashr V, RHS
6210 case Instruction::AShr: {
6211 const APInt *CV, *CRHS;
6212 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6213 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6215 return nullptr;
6216 break;
6217 }
6218 // V = shl nuw X, RHS => X = lshr V, RHS
6219 case Instruction::LShr: {
6220 const APInt *CV, *CRHS;
6221 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6222 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6224 return nullptr;
6225 break;
6226 }
6227 default:
6228 break;
6229 }
6230
6231 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6232 if (!Simplified)
6233 return nullptr;
6234 // Reject constant expressions as they don't simplify things.
6235 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6236 return nullptr;
6237 // Check if the transformation introduces poison.
6238 return impliesPoison(RHS, V) ? Simplified : nullptr;
6239 };
6240
6241 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6242 Value *RHS) -> OffsetResult {
6243 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6244 if (!Sel->hasOneUse())
6245 return OffsetResult::invalid();
6246 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6247 if (!TrueVal)
6248 return OffsetResult::invalid();
6249 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6250 if (!FalseVal)
6251 return OffsetResult::invalid();
6252 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6253 }
6254 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6255 return OffsetResult::value(Simplified);
6256 return OffsetResult::invalid();
6257 };
6258
6259 for (auto [BinOp, RHS] : OffsetOps) {
6260 auto BinOpc = static_cast<unsigned>(BinOp);
6261
6262 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6263 if (!Op0Result.isValid())
6264 continue;
6265 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6266 if (!Op1Result.isValid())
6267 continue;
6268
6269 Value *NewLHS = Op0Result.materialize(Builder);
6270 Value *NewRHS = Op1Result.materialize(Builder);
6271 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6272 }
6273
6274 return nullptr;
6275}
6276
6278 if (!I.isEquality())
6279 return nullptr;
6280
6281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6282 const CmpInst::Predicate Pred = I.getPredicate();
6283 Value *A, *B, *C, *D;
6284 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6285 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6286 Value *OtherVal = A == Op1 ? B : A;
6287 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6288 }
6289
6290 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6291 // A^c1 == C^c2 --> A == C^(c1^c2)
6292 ConstantInt *C1, *C2;
6293 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6294 Op1->hasOneUse()) {
6295 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6296 Value *Xor = Builder.CreateXor(C, NC);
6297 return new ICmpInst(Pred, A, Xor);
6298 }
6299
6300 // A^B == A^D -> B == D
6301 if (A == C)
6302 return new ICmpInst(Pred, B, D);
6303 if (A == D)
6304 return new ICmpInst(Pred, B, C);
6305 if (B == C)
6306 return new ICmpInst(Pred, A, D);
6307 if (B == D)
6308 return new ICmpInst(Pred, A, C);
6309 }
6310 }
6311
6312 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6313 // A == (A^B) -> B == 0
6314 Value *OtherVal = A == Op0 ? B : A;
6315 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6316 }
6317
6318 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6319 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6320 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6321 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6322
6323 if (A == C) {
6324 X = B;
6325 Y = D;
6326 Z = A;
6327 } else if (A == D) {
6328 X = B;
6329 Y = C;
6330 Z = A;
6331 } else if (B == C) {
6332 X = A;
6333 Y = D;
6334 Z = B;
6335 } else if (B == D) {
6336 X = A;
6337 Y = C;
6338 Z = B;
6339 }
6340
6341 if (X) {
6342 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6343 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6344 // instructions.
6345 const APInt *C0, *C1;
6346 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6347 (*C0 ^ *C1).isNegatedPowerOf2();
6348
6349 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6350 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6351 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6352 int UseCnt =
6353 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6354 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6355 if (XorIsNegP2 || UseCnt >= 2) {
6356 // Build (X^Y) & Z
6357 Op1 = Builder.CreateXor(X, Y);
6358 Op1 = Builder.CreateAnd(Op1, Z);
6359 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6360 }
6361 }
6362 }
6363
6364 {
6365 // Similar to above, but specialized for constant because invert is needed:
6366 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6367 Value *X, *Y;
6368 Constant *C;
6369 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6370 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6371 Value *Xor = Builder.CreateXor(X, Y);
6372 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6373 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6374 }
6375 }
6376
6377 if (match(Op1, m_ZExt(m_Value(A))) &&
6378 (Op0->hasOneUse() || Op1->hasOneUse())) {
6379 // (B & (Pow2C-1)) == zext A --> A == trunc B
6380 // (B & (Pow2C-1)) != zext A --> A != trunc B
6381 const APInt *MaskC;
6382 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6383 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6384 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6385 }
6386
6387 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6388 // For lshr and ashr pairs.
6389 const APInt *AP1, *AP2;
6390 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6391 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6392 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6393 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6394 if (*AP1 != *AP2)
6395 return nullptr;
6396 unsigned TypeBits = AP1->getBitWidth();
6397 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6398 if (ShAmt < TypeBits && ShAmt != 0) {
6399 ICmpInst::Predicate NewPred =
6401 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6402 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6403 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6404 }
6405 }
6406
6407 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6408 ConstantInt *Cst1;
6409 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6410 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6411 unsigned TypeBits = Cst1->getBitWidth();
6412 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6413 if (ShAmt < TypeBits && ShAmt != 0) {
6414 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6415 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6416 Value *And =
6417 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6418 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6419 }
6420 }
6421
6422 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6423 // "icmp (and X, mask), cst"
6424 uint64_t ShAmt = 0;
6425 if (Op0->hasOneUse() &&
6426 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6427 match(Op1, m_ConstantInt(Cst1)) &&
6428 // Only do this when A has multiple uses. This is most important to do
6429 // when it exposes other optimizations.
6430 !A->hasOneUse()) {
6431 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6432
6433 if (ShAmt < ASize) {
6434 APInt MaskV =
6436 MaskV <<= ShAmt;
6437
6438 APInt CmpV = Cst1->getValue().zext(ASize);
6439 CmpV <<= ShAmt;
6440
6441 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6442 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6443 }
6444 }
6445
6447 return ICmp;
6448
6449 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6450 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6451 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6452 // few steps of instcombine.
6453 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6454 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6456 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6457 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6459 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6460 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6462 Add, ConstantInt::get(A->getType(), C.shl(1)));
6463 }
6464
6465 // Canonicalize:
6466 // Assume B_Pow2 != 0
6467 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6468 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6469 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6470 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6471 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6473
6474 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6475 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6476 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6477 ConstantInt::getNullValue(Op1->getType()));
6478
6479 // Canonicalize:
6480 // icmp eq/ne X, OneUse(rotate-right(X))
6481 // -> icmp eq/ne X, rotate-left(X)
6482 // We generally try to convert rotate-right -> rotate-left, this just
6483 // canonicalizes another case.
6484 if (match(&I, m_c_ICmp(m_Value(A),
6486 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6487 return new ICmpInst(
6488 Pred, A,
6489 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6490
6491 // Canonicalize:
6492 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6493 Constant *Cst;
6496 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6497
6498 {
6499 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6500 auto m_Matcher =
6503 m_Sub(m_Value(B), m_Deferred(A)));
6504 std::optional<bool> IsZero = std::nullopt;
6505 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6506 m_Deferred(A))))
6507 IsZero = false;
6508 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6509 else if (match(&I,
6510 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6511 IsZero = true;
6512
6513 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6514 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6515 // -> (icmp eq/ne (and X, P2), 0)
6516 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6517 // -> (icmp eq/ne (and X, P2), P2)
6518 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6519 *IsZero ? A
6520 : ConstantInt::getNullValue(A->getType()));
6521 }
6522
6523 if (auto *Res = foldICmpEqualityWithOffset(
6524 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6525 return Res;
6526
6527 return nullptr;
6528}
6529
6531 ICmpInst::Predicate Pred = ICmp.getPredicate();
6532 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6533
6534 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6535 // The trunc masks high bits while the compare may effectively mask low bits.
6536 Value *X;
6537 const APInt *C;
6538 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6539 return nullptr;
6540
6541 // This matches patterns corresponding to tests of the signbit as well as:
6542 // (trunc X) pred C2 --> (X & Mask) == C
6543 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6544 /*AllowNonZeroC=*/true)) {
6545 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6546 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6547 return new ICmpInst(Res->Pred, And, C);
6548 }
6549
6550 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6551 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6552 if (II->getIntrinsicID() == Intrinsic::cttz ||
6553 II->getIntrinsicID() == Intrinsic::ctlz) {
6554 unsigned MaxRet = SrcBits;
6555 // If the "is_zero_poison" argument is set, then we know at least
6556 // one bit is set in the input, so the result is always at least one
6557 // less than the full bitwidth of that input.
6558 if (match(II->getArgOperand(1), m_One()))
6559 MaxRet--;
6560
6561 // Make sure the destination is wide enough to hold the largest output of
6562 // the intrinsic.
6563 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6564 if (Instruction *I =
6565 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6566 return I;
6567 }
6568 }
6569
6570 return nullptr;
6571}
6572
6574 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6575 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6576 Value *X;
6577 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6578 return nullptr;
6579
6580 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6581 bool IsSignedCmp = ICmp.isSigned();
6582
6583 // icmp Pred (ext X), (ext Y)
6584 Value *Y;
6585 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6586 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6587 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6588
6589 if (IsZext0 != IsZext1) {
6590 // If X and Y and both i1
6591 // (icmp eq/ne (zext X) (sext Y))
6592 // eq -> (icmp eq (or X, Y), 0)
6593 // ne -> (icmp ne (or X, Y), 0)
6594 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6595 Y->getType()->isIntOrIntVectorTy(1))
6596 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6597 Constant::getNullValue(X->getType()));
6598
6599 // If we have mismatched casts and zext has the nneg flag, we can
6600 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6601
6602 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6603 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6604
6605 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6606 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6607
6608 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6609 IsSignedExt = true;
6610 else
6611 return nullptr;
6612 }
6613
6614 // Not an extension from the same type?
6615 Type *XTy = X->getType(), *YTy = Y->getType();
6616 if (XTy != YTy) {
6617 // One of the casts must have one use because we are creating a new cast.
6618 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6619 return nullptr;
6620 // Extend the narrower operand to the type of the wider operand.
6621 CastInst::CastOps CastOpcode =
6622 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6623 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6624 X = Builder.CreateCast(CastOpcode, X, YTy);
6625 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6626 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6627 else
6628 return nullptr;
6629 }
6630
6631 // (zext X) == (zext Y) --> X == Y
6632 // (sext X) == (sext Y) --> X == Y
6633 if (ICmp.isEquality())
6634 return new ICmpInst(ICmp.getPredicate(), X, Y);
6635
6636 // A signed comparison of sign extended values simplifies into a
6637 // signed comparison.
6638 if (IsSignedCmp && IsSignedExt)
6639 return new ICmpInst(ICmp.getPredicate(), X, Y);
6640
6641 // The other three cases all fold into an unsigned comparison.
6642 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6643 }
6644
6645 // Below here, we are only folding a compare with constant.
6646 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6647 if (!C)
6648 return nullptr;
6649
6650 // If a lossless truncate is possible...
6651 Type *SrcTy = CastOp0->getSrcTy();
6652 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6653 if (Res) {
6654 if (ICmp.isEquality())
6655 return new ICmpInst(ICmp.getPredicate(), X, Res);
6656
6657 // A signed comparison of sign extended values simplifies into a
6658 // signed comparison.
6659 if (IsSignedExt && IsSignedCmp)
6660 return new ICmpInst(ICmp.getPredicate(), X, Res);
6661
6662 // The other three cases all fold into an unsigned comparison.
6663 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6664 }
6665
6666 // The re-extended constant changed, partly changed (in the case of a vector),
6667 // or could not be determined to be equal (in the case of a constant
6668 // expression), so the constant cannot be represented in the shorter type.
6669 // All the cases that fold to true or false will have already been handled
6670 // by simplifyICmpInst, so only deal with the tricky case.
6671 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6672 return nullptr;
6673
6674 // Is source op positive?
6675 // icmp ult (sext X), C --> icmp sgt X, -1
6676 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6678
6679 // Is source op negative?
6680 // icmp ugt (sext X), C --> icmp slt X, 0
6681 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6683}
6684
6685/// Handle icmp (cast x), (cast or constant).
6687 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6688 // icmp compares only pointer's value.
6689 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6690 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6691 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6692 if (SimplifiedOp0 || SimplifiedOp1)
6693 return new ICmpInst(ICmp.getPredicate(),
6694 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6695 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6696
6697 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6698 Value *Op1 = ICmp.getOperand(1);
6699 if (!CastOp0)
6700 return nullptr;
6701 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6702 return nullptr;
6703
6704 Value *Op0Src = CastOp0->getOperand(0);
6705 Type *SrcTy = CastOp0->getSrcTy();
6706 Type *DestTy = CastOp0->getDestTy();
6707
6708 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6709 // integer type is the same size as the pointer type.
6710 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6711 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6712 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6713 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6714 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6715 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6716 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6717 };
6718 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6719 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6720 Value *NewOp1 = nullptr;
6721 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6722 NewOp1 = PtrToIntOp1->getOperand(0);
6723 HasPtrToInt = true;
6724 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6725 NewOp1 = PtrToAddrOp1->getOperand(0);
6726 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6727 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6728 }
6729
6730 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6731 // check PtrWidth.
6732 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6733 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6734 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6735 }
6736
6737 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6738 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6739 CompatibleSizes(DestTy, SrcTy)) {
6740 Value *NewOp1 = nullptr;
6741 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6742 Value *IntSrc = IntToPtrOp1->getOperand(0);
6743 if (IntSrc->getType() == Op0Src->getType())
6744 NewOp1 = IntToPtrOp1->getOperand(0);
6745 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6746 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6747 }
6748
6749 if (NewOp1)
6750 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6751 }
6752
6753 if (Instruction *R = foldICmpWithTrunc(ICmp))
6754 return R;
6755
6756 return foldICmpWithZextOrSext(ICmp);
6757}
6758
6760 bool IsSigned) {
6761 switch (BinaryOp) {
6762 default:
6763 llvm_unreachable("Unsupported binary op");
6764 case Instruction::Add:
6765 case Instruction::Sub:
6766 return match(RHS, m_Zero());
6767 case Instruction::Mul:
6768 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6769 match(RHS, m_One());
6770 }
6771}
6772
6775 bool IsSigned, Value *LHS, Value *RHS,
6776 Instruction *CtxI) const {
6777 switch (BinaryOp) {
6778 default:
6779 llvm_unreachable("Unsupported binary op");
6780 case Instruction::Add:
6781 if (IsSigned)
6782 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6783 else
6784 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6785 case Instruction::Sub:
6786 if (IsSigned)
6787 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6788 else
6789 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6790 case Instruction::Mul:
6791 if (IsSigned)
6792 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6793 else
6794 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6795 }
6796}
6797
6798bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6799 bool IsSigned, Value *LHS,
6800 Value *RHS, Instruction &OrigI,
6801 Value *&Result,
6802 Constant *&Overflow) {
6803 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6804 std::swap(LHS, RHS);
6805
6806 // If the overflow check was an add followed by a compare, the insertion point
6807 // may be pointing to the compare. We want to insert the new instructions
6808 // before the add in case there are uses of the add between the add and the
6809 // compare.
6810 Builder.SetInsertPoint(&OrigI);
6811
6812 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6813 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6814 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6815
6816 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6817 Result = LHS;
6818 Overflow = ConstantInt::getFalse(OverflowTy);
6819 return true;
6820 }
6821
6822 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6824 return false;
6827 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6828 Result->takeName(&OrigI);
6829 Overflow = ConstantInt::getTrue(OverflowTy);
6830 return true;
6832 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6833 Result->takeName(&OrigI);
6834 Overflow = ConstantInt::getFalse(OverflowTy);
6835 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6836 if (IsSigned)
6837 Inst->setHasNoSignedWrap();
6838 else
6839 Inst->setHasNoUnsignedWrap();
6840 }
6841 return true;
6842 }
6843
6844 llvm_unreachable("Unexpected overflow result");
6845}
6846
6847/// Recognize and process idiom involving test for unsigned
6848/// overflow.
6849///
6850/// The caller has matched a pattern of the form:
6851/// I = cmp u (add(zext A, zext B), V
6852/// I = cmp u (mul(zext A, zext B), V
6853/// The function checks if this is a test for overflow and if so replaces
6854/// addition/multiplication with call to the umul intrinsic or the canonical
6855/// form of uadd overflow.
6856///
6857/// \param I Compare instruction.
6858/// \param Val Result of add/mul instruction. It is one of the arguments of
6859/// the compare instruction. Must be of integer type.
6860/// \param OtherVal The other argument of compare instruction.
6861/// \returns Instruction which must replace the compare instruction, NULL if no
6862/// replacement required.
6864 const APInt *OtherVal,
6865 InstCombinerImpl &IC) {
6866 // Don't bother doing this transformation for pointers, don't do it for
6867 // vectors.
6868 if (!isa<IntegerType>(Val->getType()))
6869 return nullptr;
6870
6871 auto *Instr = cast<Instruction>(Val);
6872 unsigned Opcode = Instr->getOpcode();
6873 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6874
6875 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6876 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6877 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6878
6879 // Calculate type and width of the result produced by add/mul.with.overflow.
6880 Type *TyA = A->getType(), *TyB = B->getType();
6881 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6882 WidthB = TyB->getPrimitiveSizeInBits();
6883 unsigned ResultWidth;
6884 Type *ResultType;
6885 if (WidthB > WidthA) {
6886 ResultWidth = WidthB;
6887 ResultType = TyB;
6888 } else {
6889 ResultWidth = WidthA;
6890 ResultType = TyA;
6891 }
6892
6893 // In order to replace the original result with a narrower one, all uses must
6894 // ignore upper bits of the result. The number of used low bits must be not
6895 // greater than the width of add or mul.with.overflow.
6896 if (Val->hasNUsesOrMore(2))
6897 for (User *U : Val->users()) {
6898 if (U == &I)
6899 continue;
6900 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6901 // Check if truncation ignores bits above ResultWidth.
6902 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6903 if (TruncWidth > ResultWidth)
6904 return nullptr;
6905 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6906 // Check if AND ignores bits above ResultWidth.
6907 if (BO->getOpcode() != Instruction::And)
6908 return nullptr;
6909 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6910 const APInt &CVal = CI->getValue();
6911 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6912 return nullptr;
6913 } else {
6914 // In this case we could have the operand of the binary operation
6915 // being defined in another block, and performing the replacement
6916 // could break the dominance relation.
6917 return nullptr;
6918 }
6919 } else {
6920 // Other uses prohibit this transformation.
6921 return nullptr;
6922 }
6923 }
6924
6925 // Recognize patterns
6926 switch (I.getPredicate()) {
6927 case ICmpInst::ICMP_UGT: {
6928 // Recognize pattern:
6929 // val = add/mul(zext A, zext B)
6930 // cmp ugt val, max
6931 APInt MaxVal = APInt::getMaxValue(ResultWidth);
6932 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6933 if (MaxVal.eq(*OtherVal))
6934 break; // Recognized
6935 return nullptr;
6936 }
6937
6938 case ICmpInst::ICMP_ULT: {
6939 // Recognize pattern:
6940 // val = add/mul(zext A, zext B)
6941 // cmp ult val, max + 1
6942 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
6943 if (MaxVal.eq(*OtherVal))
6944 break; // Recognized
6945 return nullptr;
6946 }
6947
6948 default:
6949 return nullptr;
6950 }
6951
6952 InstCombiner::BuilderTy &Builder = IC.Builder;
6953 Builder.SetInsertPoint(Instr);
6954
6955 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6956 Value *ResultA = A, *ResultB = B;
6957 if (WidthA < ResultWidth)
6958 ResultA = Builder.CreateZExt(A, ResultType);
6959 if (WidthB < ResultWidth)
6960 ResultB = Builder.CreateZExt(B, ResultType);
6961
6962 Value *ArithResult;
6963 Value *OverflowCheck;
6964
6965 if (Opcode == Instruction::Add) {
6966 // Canonical add overflow check: add + compare
6967 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
6968 // Overflow if result < either operand (for unsigned add)
6969 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6970 OverflowCheck =
6971 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
6972 else
6973 OverflowCheck =
6974 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
6975 } else {
6976 // For multiplication, the intrinsic is actually the canonical form
6977 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
6978 ResultType, {ResultA, ResultB},
6979 /*FMFSource=*/nullptr, "umul");
6980 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
6981 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
6982 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6983 OverflowCheck = Builder.CreateNot(OverflowCheck);
6984 }
6985
6986 IC.addToWorklist(Instr);
6987
6988 // Replace uses of the original add/mul result with the new arithmetic result
6989 if (Val->hasNUsesOrMore(2)) {
6990 for (User *U : make_early_inc_range(Val->users())) {
6991 if (U == &I)
6992 continue;
6993 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6994 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6995 IC.replaceInstUsesWith(*TI, ArithResult);
6996 else
6997 TI->setOperand(0, ArithResult);
6998 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6999 assert(BO->getOpcode() == Instruction::And);
7000 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
7001 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
7002 APInt ShortMask = CI->getValue().trunc(ResultWidth);
7003 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
7004 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
7005 IC.replaceInstUsesWith(*BO, Zext);
7006 } else {
7007 llvm_unreachable("Unexpected Binary operation");
7008 }
7010 }
7011 }
7012
7013 return IC.replaceInstUsesWith(I, OverflowCheck);
7014}
7015
7016/// When performing a comparison against a constant, it is possible that not all
7017/// the bits in the LHS are demanded. This helper method computes the mask that
7018/// IS demanded.
7020 const APInt *RHS;
7021 if (!match(I.getOperand(1), m_APInt(RHS)))
7023
7024 // If this is a normal comparison, it demands all bits. If it is a sign bit
7025 // comparison, it only demands the sign bit.
7026 bool UnusedBit;
7027 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
7029
7030 switch (I.getPredicate()) {
7031 // For a UGT comparison, we don't care about any bits that
7032 // correspond to the trailing ones of the comparand. The value of these
7033 // bits doesn't impact the outcome of the comparison, because any value
7034 // greater than the RHS must differ in a bit higher than these due to carry.
7035 case ICmpInst::ICMP_UGT:
7036 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
7037
7038 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7039 // Any value less than the RHS must differ in a higher bit because of carries.
7040 case ICmpInst::ICMP_ULT:
7041 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
7042
7043 default:
7045 }
7046}
7047
7048/// Check that one use is in the same block as the definition and all
7049/// other uses are in blocks dominated by a given block.
7050///
7051/// \param DI Definition
7052/// \param UI Use
7053/// \param DB Block that must dominate all uses of \p DI outside
7054/// the parent block
7055/// \return true when \p UI is the only use of \p DI in the parent block
7056/// and all other uses of \p DI are in blocks dominated by \p DB.
7057///
7059 const Instruction *UI,
7060 const BasicBlock *DB) const {
7061 assert(DI && UI && "Instruction not defined\n");
7062 // Ignore incomplete definitions.
7063 if (!DI->getParent())
7064 return false;
7065 // DI and UI must be in the same block.
7066 if (DI->getParent() != UI->getParent())
7067 return false;
7068 // Protect from self-referencing blocks.
7069 if (DI->getParent() == DB)
7070 return false;
7071 for (const User *U : DI->users()) {
7072 auto *Usr = cast<Instruction>(U);
7073 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7074 return false;
7075 }
7076 return true;
7077}
7078
7079/// Return true when the instruction sequence within a block is select-cmp-br.
7081 const BasicBlock *BB = SI->getParent();
7082 if (!BB)
7083 return false;
7084 auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
7085 if (!BI)
7086 return false;
7087 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7088 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7089 return false;
7090 return true;
7091}
7092
7093/// True when a select result is replaced by one of its operands
7094/// in select-icmp sequence. This will eventually result in the elimination
7095/// of the select.
7096///
7097/// \param SI Select instruction
7098/// \param Icmp Compare instruction
7099/// \param SIOpd Operand that replaces the select
7100///
7101/// Notes:
7102/// - The replacement is global and requires dominator information
7103/// - The caller is responsible for the actual replacement
7104///
7105/// Example:
7106///
7107/// entry:
7108/// %4 = select i1 %3, %C* %0, %C* null
7109/// %5 = icmp eq %C* %4, null
7110/// br i1 %5, label %9, label %7
7111/// ...
7112/// ; <label>:7 ; preds = %entry
7113/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7114/// ...
7115///
7116/// can be transformed to
7117///
7118/// %5 = icmp eq %C* %0, null
7119/// %6 = select i1 %3, i1 %5, i1 true
7120/// br i1 %6, label %9, label %7
7121/// ...
7122/// ; <label>:7 ; preds = %entry
7123/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7124///
7125/// Similar when the first operand of the select is a constant or/and
7126/// the compare is for not equal rather than equal.
7127///
7128/// NOTE: The function is only called when the select and compare constants
7129/// are equal, the optimization can work only for EQ predicates. This is not a
7130/// major restriction since a NE compare should be 'normalized' to an equal
7131/// compare, which usually happens in the combiner and test case
7132/// select-cmp-br.ll checks for it.
7134 const ICmpInst *Icmp,
7135 const unsigned SIOpd) {
7136 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7138 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7139 // The check for the single predecessor is not the best that can be
7140 // done. But it protects efficiently against cases like when SI's
7141 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7142 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7143 // replaced can be reached on either path. So the uniqueness check
7144 // guarantees that the path all uses of SI (outside SI's parent) are on
7145 // is disjoint from all other paths out of SI. But that information
7146 // is more expensive to compute, and the trade-off here is in favor
7147 // of compile-time. It should also be noticed that we check for a single
7148 // predecessor and not only uniqueness. This to handle the situation when
7149 // Succ and Succ1 points to the same basic block.
7150 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7151 NumSel++;
7152 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7153 return true;
7154 }
7155 }
7156 return false;
7157}
7158
7159/// Try to fold the comparison based on range information we can get by checking
7160/// whether bits are known to be zero or one in the inputs.
7162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7163 Type *Ty = Op0->getType();
7164 ICmpInst::Predicate Pred = I.getPredicate();
7165
7166 // Get scalar or pointer size.
7167 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7168 ? Ty->getScalarSizeInBits()
7169 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7170
7171 if (!BitWidth)
7172 return nullptr;
7173
7174 KnownBits Op0Known(BitWidth);
7175 KnownBits Op1Known(BitWidth);
7176
7177 {
7178 // Don't use dominating conditions when folding icmp using known bits. This
7179 // may convert signed into unsigned predicates in ways that other passes
7180 // (especially IndVarSimplify) may not be able to reliably undo.
7181 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7183 Op0Known, Q))
7184 return &I;
7185
7186 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7187 return &I;
7188 }
7189
7190 // If an unsigned samesign comparison is not poison, both operands have the
7191 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7192 // values so the existing range folds can use that constraint.
7193 if (I.hasSameSign() && I.isUnsigned()) {
7194 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7195 if (To.isNegative() || To.isNonNegative())
7196 return;
7197 if (From.isNegative())
7198 To.makeNegative();
7199 else if (From.isNonNegative())
7200 To.makeNonNegative();
7201 };
7202 PropagateSignBit(Op0Known, Op1Known);
7203 PropagateSignBit(Op1Known, Op0Known);
7204 }
7205
7206 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7207 return new ICmpInst(
7208 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7209 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7210 return new ICmpInst(
7211 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7212
7213 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7214 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7215
7216 // Given the known and unknown bits, compute a range that the LHS could be
7217 // in. Compute the Min, Max and RHS values based on the known bits. For the
7218 // EQ and NE we use unsigned values.
7219 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7220 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7221 if (I.isSigned()) {
7222 Op0Min = Op0Known.getSignedMinValue();
7223 Op0Max = Op0Known.getSignedMaxValue();
7224 Op1Min = Op1Known.getSignedMinValue();
7225 Op1Max = Op1Known.getSignedMaxValue();
7226 } else {
7227 Op0Min = Op0Known.getMinValue();
7228 Op0Max = Op0Known.getMaxValue();
7229 Op1Min = Op1Known.getMinValue();
7230 Op1Max = Op1Known.getMaxValue();
7231 }
7232
7233 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7234 // min/max canonical compare with some other compare. That could lead to
7235 // conflict with select canonicalization and infinite looping.
7236 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7237 auto isMinMaxCmp = [&](Instruction &Cmp) {
7238 if (!Cmp.hasOneUse())
7239 return false;
7240 Value *A, *B;
7241 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7243 return false;
7244 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7245 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7246 };
7247 if (!isMinMaxCmp(I)) {
7248 switch (Pred) {
7249 default:
7250 break;
7251 case ICmpInst::ICMP_ULT: {
7252 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7253 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7254 const APInt *CmpC;
7255 if (match(Op1, m_APInt(CmpC))) {
7256 // A <u C -> A == C-1 if min(A)+1 == C
7257 if (*CmpC == Op0Min + 1)
7258 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7259 ConstantInt::get(Op1->getType(), *CmpC - 1));
7260 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7261 // exceeds the log2 of C.
7262 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7264 Constant::getNullValue(Op1->getType()));
7265 }
7266 break;
7267 }
7268 case ICmpInst::ICMP_UGT: {
7269 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7270 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7271 const APInt *CmpC;
7272 if (match(Op1, m_APInt(CmpC))) {
7273 // A >u C -> A == C+1 if max(a)-1 == C
7274 if (*CmpC == Op0Max - 1)
7275 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7276 ConstantInt::get(Op1->getType(), *CmpC + 1));
7277 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7278 // exceeds the log2 of C.
7279 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7280 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7281 Constant::getNullValue(Op1->getType()));
7282 }
7283 break;
7284 }
7285 case ICmpInst::ICMP_SLT: {
7286 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7287 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7288 const APInt *CmpC;
7289 if (match(Op1, m_APInt(CmpC))) {
7290 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7291 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7292 ConstantInt::get(Op1->getType(), *CmpC - 1));
7293 }
7294 break;
7295 }
7296 case ICmpInst::ICMP_SGT: {
7297 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7298 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7299 const APInt *CmpC;
7300 if (match(Op1, m_APInt(CmpC))) {
7301 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7302 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7303 ConstantInt::get(Op1->getType(), *CmpC + 1));
7304 }
7305 break;
7306 }
7307 }
7308 }
7309
7310 // Based on the range information we know about the LHS, see if we can
7311 // simplify this comparison. For example, (x&4) < 8 is always true.
7312 switch (Pred) {
7313 default:
7314 break;
7315 case ICmpInst::ICMP_EQ:
7316 case ICmpInst::ICMP_NE: {
7317 // If all bits are known zero except for one, then we know at most one bit
7318 // is set. If the comparison is against zero, then this is a check to see if
7319 // *that* bit is set.
7320 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7321 if (Op1Known.isZero()) {
7322 // If the LHS is an AND with the same constant, look through it.
7323 Value *LHS = nullptr;
7324 const APInt *LHSC;
7325 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7326 *LHSC != Op0KnownZeroInverted)
7327 LHS = Op0;
7328
7329 Value *X;
7330 const APInt *C1;
7331 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7332 Type *XTy = X->getType();
7333 unsigned Log2C1 = C1->countr_zero();
7334 APInt C2 = Op0KnownZeroInverted;
7335 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7336 if (C2Pow2.isPowerOf2()) {
7337 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7338 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7339 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7340 unsigned Log2C2 = C2Pow2.countr_zero();
7341 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7342 auto NewPred =
7344 return new ICmpInst(NewPred, X, CmpC);
7345 }
7346 }
7347 }
7348
7349 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7350 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7351 (Op0Known & Op1Known) == Op0Known)
7352 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7353 ConstantInt::getNullValue(Op1->getType()));
7354 break;
7355 }
7356 case ICmpInst::ICMP_SGE:
7357 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7358 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7359 break;
7360 case ICmpInst::ICMP_SLE:
7361 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7362 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7363 break;
7364 case ICmpInst::ICMP_UGE:
7365 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7366 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7367 break;
7368 case ICmpInst::ICMP_ULE:
7369 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7370 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7371 break;
7372 }
7373
7374 // Turn a signed comparison into an unsigned one if both operands are known to
7375 // have the same sign. Set samesign if possible (except for equality
7376 // predicates).
7377 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7378 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7379 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7380 I.setPredicate(I.getUnsignedPredicate());
7381 I.setSameSign();
7382 return &I;
7383 }
7384
7385 return nullptr;
7386}
7387
7388/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7389/// then try to reduce patterns based on that limit.
7391 Value *X, *Y;
7392 CmpPredicate Pred;
7393
7394 // X must be 0 and bool must be true for "ULT":
7395 // X <u (zext i1 Y) --> (X == 0) & Y
7396 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7397 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7398 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7399
7400 // X must be 0 or bool must be true for "ULE":
7401 // X <=u (sext i1 Y) --> (X == 0) | Y
7402 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7403 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7404 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7405
7406 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7407 CmpPredicate Pred1, Pred2;
7408 const APInt *C;
7409 Instruction *ExtI;
7410 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7413 m_APInt(C)))))) &&
7414 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7415 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7416 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7417 auto CreateRangeCheck = [&] {
7418 Value *CmpV1 =
7419 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7420 Value *CmpV2 = Builder.CreateICmp(
7421 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7423 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7424 CmpV1, CmpV2);
7425 };
7426 if (C->isZero()) {
7427 if (Pred2 == ICmpInst::ICMP_EQ) {
7428 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7429 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7430 return replaceInstUsesWith(
7431 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7432 } else if (!IsSExt || HasOneUse) {
7433 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7434 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7435 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7436 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7437 return CreateRangeCheck();
7438 }
7439 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7440 if (Pred2 == ICmpInst::ICMP_NE) {
7441 // icmp eq X, (zext (icmp ne X, 1)) --> false
7442 // icmp ne X, (zext (icmp ne X, 1)) --> true
7443 // icmp eq X, (sext (icmp ne X, -1)) --> false
7444 // icmp ne X, (sext (icmp ne X, -1)) --> true
7445 return replaceInstUsesWith(
7446 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7447 } else if (!IsSExt || HasOneUse) {
7448 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7449 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7450 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7451 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7452 return CreateRangeCheck();
7453 }
7454 } else {
7455 // when C != 0 && C != 1:
7456 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7457 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7458 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7459 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7460 // when C != 0 && C != -1:
7461 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7462 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7463 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7464 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7465 return ICmpInst::Create(
7466 Instruction::ICmp, Pred1, X,
7467 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7468 ? (IsSExt ? -1 : 1)
7469 : 0));
7470 }
7471 }
7472
7473 return nullptr;
7474}
7475
7476/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7477/// it into the appropriate icmp lt or icmp gt instruction. This transform
7478/// allows them to be folded in visitICmpInst.
7480 CmpPredicate Pred = I.getCmpPredicate();
7481 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7483 return nullptr;
7484
7485 Value *Op0 = I.getOperand(0);
7486 Value *Op1 = I.getOperand(1);
7487 auto *Op1C = dyn_cast<Constant>(Op1);
7488 if (!Op1C)
7489 return nullptr;
7490
7491 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7492 if (!FlippedStrictness)
7493 return nullptr;
7494
7495 auto *NewCmp =
7496 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7497 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7498 return NewCmp;
7499}
7500
7501/// If we have a comparison with a non-canonical predicate, if we can update
7502/// all the users, invert the predicate and adjust all the users.
7504 // Is the predicate already canonical?
7505 CmpInst::Predicate Pred = I.getPredicate();
7507 return nullptr;
7508
7509 // Can all users be adjusted to predicate inversion?
7510 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7511 return nullptr;
7512
7513 // Ok, we can canonicalize comparison!
7514 // Let's first invert the comparison's predicate.
7515 I.setPredicate(CmpInst::getInversePredicate(Pred));
7516 I.setName(I.getName() + ".not");
7517
7518 // And, adapt users.
7520
7521 return &I;
7522}
7523
7524/// Integer compare with boolean values can always be turned into bitwise ops.
7526 InstCombiner::BuilderTy &Builder) {
7527 Value *A = I.getOperand(0), *B = I.getOperand(1);
7528 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7529
7530 // A boolean compared to true/false can be simplified to Op0/true/false in
7531 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7532 // Cases not handled by InstSimplify are always 'not' of Op0.
7533 if (match(B, m_Zero())) {
7534 switch (I.getPredicate()) {
7535 case CmpInst::ICMP_EQ: // A == 0 -> !A
7536 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7537 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7539 default:
7540 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7541 }
7542 } else if (match(B, m_One())) {
7543 switch (I.getPredicate()) {
7544 case CmpInst::ICMP_NE: // A != 1 -> !A
7545 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7546 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7548 default:
7549 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7550 }
7551 }
7552
7553 switch (I.getPredicate()) {
7554 default:
7555 llvm_unreachable("Invalid icmp instruction!");
7556 case ICmpInst::ICMP_EQ:
7557 // icmp eq i1 A, B -> ~(A ^ B)
7558 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7559
7560 case ICmpInst::ICMP_NE:
7561 // icmp ne i1 A, B -> A ^ B
7562 return BinaryOperator::CreateXor(A, B);
7563
7564 case ICmpInst::ICMP_UGT:
7565 // icmp ugt -> icmp ult
7566 std::swap(A, B);
7567 [[fallthrough]];
7568 case ICmpInst::ICMP_ULT:
7569 // icmp ult i1 A, B -> ~A & B
7570 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7571
7572 case ICmpInst::ICMP_SGT:
7573 // icmp sgt -> icmp slt
7574 std::swap(A, B);
7575 [[fallthrough]];
7576 case ICmpInst::ICMP_SLT:
7577 // icmp slt i1 A, B -> A & ~B
7578 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7579
7580 case ICmpInst::ICMP_UGE:
7581 // icmp uge -> icmp ule
7582 std::swap(A, B);
7583 [[fallthrough]];
7584 case ICmpInst::ICMP_ULE:
7585 // icmp ule i1 A, B -> ~A | B
7586 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7587
7588 case ICmpInst::ICMP_SGE:
7589 // icmp sge -> icmp sle
7590 std::swap(A, B);
7591 [[fallthrough]];
7592 case ICmpInst::ICMP_SLE:
7593 // icmp sle i1 A, B -> A | ~B
7594 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7595 }
7596}
7597
7598// Transform pattern like:
7599// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7600// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7601// Into:
7602// (X l>> Y) != 0
7603// (X l>> Y) == 0
7605 InstCombiner::BuilderTy &Builder) {
7606 CmpPredicate Pred, NewPred;
7607 Value *X, *Y;
7608 if (match(&Cmp,
7609 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7610 switch (Pred) {
7611 case ICmpInst::ICMP_ULE:
7612 NewPred = ICmpInst::ICMP_NE;
7613 break;
7614 case ICmpInst::ICMP_UGT:
7615 NewPred = ICmpInst::ICMP_EQ;
7616 break;
7617 default:
7618 return nullptr;
7619 }
7620 } else if (match(&Cmp, m_c_ICmp(Pred,
7623 m_Add(m_Shl(m_One(), m_Value(Y)),
7624 m_AllOnes()))),
7625 m_Value(X)))) {
7626 // The variant with 'add' is not canonical, (the variant with 'not' is)
7627 // we only get it because it has extra uses, and can't be canonicalized,
7628
7629 switch (Pred) {
7630 case ICmpInst::ICMP_ULT:
7631 NewPred = ICmpInst::ICMP_NE;
7632 break;
7633 case ICmpInst::ICMP_UGE:
7634 NewPred = ICmpInst::ICMP_EQ;
7635 break;
7636 default:
7637 return nullptr;
7638 }
7639 } else
7640 return nullptr;
7641
7642 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7643 Constant *Zero = Constant::getNullValue(NewX->getType());
7644 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7645}
7646
7648 InstCombiner::BuilderTy &Builder) {
7649 const CmpInst::Predicate Pred = Cmp.getPredicate();
7650 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7651 Value *V1, *V2;
7652
7653 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7654 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7655 if (auto *I = dyn_cast<Instruction>(V))
7656 I->copyIRFlags(&Cmp);
7657 Module *M = Cmp.getModule();
7659 M, Intrinsic::vector_reverse, V->getType());
7660 return CallInst::Create(F, V);
7661 };
7662
7663 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7664 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7665 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7666 (LHS->hasOneUse() || RHS->hasOneUse()))
7667 return createCmpReverse(Pred, V1, V2);
7668
7669 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7670 if (LHS->hasOneUse() && isSplatValue(RHS))
7671 return createCmpReverse(Pred, V1, RHS);
7672 }
7673 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7674 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7675 return createCmpReverse(Pred, LHS, V2);
7676
7677 ArrayRef<int> M;
7678 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7679 return nullptr;
7680
7681 // If both arguments of the cmp are shuffles that use the same mask and
7682 // shuffle within a single vector, move the shuffle after the cmp:
7683 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7684 Type *V1Ty = V1->getType();
7685 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7686 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7687 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7688 return new ShuffleVectorInst(NewCmp, M);
7689 }
7690
7691 // Try to canonicalize compare with splatted operand and splat constant.
7692 // TODO: We could generalize this for more than splats. See/use the code in
7693 // InstCombiner::foldVectorBinop().
7694 Constant *C;
7695 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7696 return nullptr;
7697
7698 // Length-changing splats are ok, so adjust the constants as needed:
7699 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7700 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7701 int MaskSplatIndex;
7702 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7703 // We allow poison in matching, but this transform removes it for safety.
7704 // Demanded elements analysis should be able to recover some/all of that.
7705 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7706 ScalarC);
7707 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7708 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7709 return new ShuffleVectorInst(NewCmp, NewM);
7710 }
7711
7712 return nullptr;
7713}
7714
7715// extract(uadd.with.overflow(A, B), 0) ult A
7716// -> extract(uadd.with.overflow(A, B), 1)
7718 CmpInst::Predicate Pred = I.getPredicate();
7719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7720
7721 Value *UAddOv;
7722 Value *A, *B;
7723 auto UAddOvResultPat = m_ExtractValue<0>(
7725 if (match(Op0, UAddOvResultPat) &&
7726 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7727 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7728 (match(A, m_One()) || match(B, m_One()))) ||
7729 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7730 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7731 // extract(uadd.with.overflow(A, B), 0) < A
7732 // extract(uadd.with.overflow(A, 1), 0) == 0
7733 // extract(uadd.with.overflow(A, -1), 0) != -1
7734 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7735 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7736 (Op0 == A || Op0 == B))
7737 // A > extract(uadd.with.overflow(A, B), 0)
7738 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7739 else
7740 return nullptr;
7741
7742 return ExtractValueInst::Create(UAddOv, 1);
7743}
7744
7746 if (!I.getOperand(0)->getType()->isPointerTy() ||
7748 I.getParent()->getParent(),
7749 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7750 return nullptr;
7751 }
7752 Value *Ptr;
7753 if (match(I.getOperand(0),
7755 match(I.getOperand(1), m_Zero())) {
7756 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), Ptr,
7757 I.getOperand(1));
7758 }
7759 return nullptr;
7760}
7761
7763 IRBuilderBase &Builder) {
7764 if (!ICmpInst::isEquality(I.getPredicate()))
7765 return nullptr;
7766
7767 // The caller puts constants after non-constants.
7768 Value *Op = I.getOperand(0);
7769 Value *Const = I.getOperand(1);
7770
7771 // For Cond an equality condition, fold
7772 //
7773 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7774 // icmp (eq|ne) Op, (Zero|AllOnes)
7775 //
7776 // with a bitcast.
7777 Value *Vec;
7778 if ((match(Const, m_ZeroInt()) &&
7780 m_Value(Vec))))) ||
7781 (match(Const, m_AllOnes()) &&
7783 m_Value(Vec)))))) {
7784 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7785 if (!VecTy)
7786 return nullptr;
7787 Type *VecEltTy = VecTy->getElementType();
7788 unsigned ScalarBW =
7789 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7790 if (!DL.fitsInLegalInteger(ScalarBW))
7791 return nullptr;
7792 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7793 Value *NewConst = match(Const, m_ZeroInt())
7794 ? ConstantInt::get(ScalarTy, 0)
7795 : ConstantInt::getAllOnesValue(ScalarTy);
7796 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7797 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7798 }
7799 return nullptr;
7800}
7801
7802/// This function folds patterns produced by lowering of reduce idioms, such as
7803/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7804/// attempts to generate fewer number of scalar comparisons instead of vector
7805/// comparisons when possible.
7807 InstCombiner::BuilderTy &Builder,
7808 const DataLayout &DL) {
7809 if (I.getType()->isVectorTy())
7810 return nullptr;
7811 CmpPredicate OuterPred, InnerPred;
7812 Value *LHS, *RHS;
7813
7814 // Match lowering of @llvm.vector.reduce.and. Turn
7815 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7816 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7817 /// %res = icmp <pred> i8 %scalar_ne, 0
7818 ///
7819 /// into
7820 ///
7821 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7822 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7823 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7824 ///
7825 /// for <pred> in {ne, eq}.
7826 if (!match(&I, m_ICmp(OuterPred,
7828 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7829 m_Zero())))
7830 return nullptr;
7831 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7832 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7833 return nullptr;
7834 unsigned NumBits =
7835 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7836 // TODO: Relax this to "not wider than max legal integer type"?
7837 if (!DL.isLegalInteger(NumBits))
7838 return nullptr;
7839
7840 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7841 auto *ScalarTy = Builder.getIntNTy(NumBits);
7842 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7843 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7844 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7845 I.getName());
7846 }
7847
7848 return nullptr;
7849}
7850
7851// This helper will be called with icmp operands in both orders.
7853 Value *Op0, Value *Op1,
7854 ICmpInst &CtxI) {
7855 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7856 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7857 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CtxI))
7858 return NI;
7859
7860 if (auto *SI = dyn_cast<SelectInst>(Op0))
7861 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CtxI))
7862 return NI;
7863
7864 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7865 if (Instruction *Res = foldICmpWithMinMax(CtxI, MinMax, Op1, Pred))
7866 return Res;
7867
7868 if (Instruction *Res = foldICmpWithClamp(CtxI, Op1, MinMax))
7869 return Res;
7870 }
7871
7872 {
7873 Value *X;
7874 const APInt *C;
7875 // icmp X+Cst, X
7876 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7877 return foldICmpAddOpConst(X, *C, Pred);
7878 }
7879
7880 // abs(X) >= X --> true
7881 // abs(X) u<= X --> true
7882 // abs(X) < X --> false
7883 // abs(X) u> X --> false
7884 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7885 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7886 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7887 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7888 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7889 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7890 {
7891 Value *X;
7892 Constant *C;
7894 match(Op1, m_Specific(X))) {
7895 Value *NullValue = Constant::getNullValue(X->getType());
7896 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7897 const APInt SMin =
7898 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7899 bool IsIntMinPosion = C->isAllOnesValue();
7900 switch (Pred) {
7901 case CmpInst::ICMP_ULE:
7902 case CmpInst::ICMP_SGE:
7903 return replaceInstUsesWith(CtxI, ConstantInt::getTrue(CtxI.getType()));
7904 case CmpInst::ICMP_UGT:
7905 case CmpInst::ICMP_SLT:
7907 case CmpInst::ICMP_UGE:
7908 case CmpInst::ICMP_SLE:
7909 case CmpInst::ICMP_EQ: {
7910 return replaceInstUsesWith(
7911 CtxI, IsIntMinPosion
7912 ? Builder.CreateICmpSGT(X, AllOnesValue)
7913 : Builder.CreateICmpULT(
7914 X, ConstantInt::get(X->getType(), SMin + 1)));
7915 }
7916 case CmpInst::ICMP_ULT:
7917 case CmpInst::ICMP_SGT:
7918 case CmpInst::ICMP_NE: {
7919 return replaceInstUsesWith(
7920 CtxI, IsIntMinPosion
7921 ? Builder.CreateICmpSLT(X, NullValue)
7922 : Builder.CreateICmpUGT(
7923 X, ConstantInt::get(X->getType(), SMin)));
7924 }
7925 default:
7926 llvm_unreachable("Invalid predicate!");
7927 }
7928 }
7929 }
7930
7931 {
7932 // For a nonzero constant C:
7933 // usub.sat(X, C) == X --> X == 0
7934 // usub.sat(X, C) != X --> X != 0
7935 // usub.sat(X, C) < X --> X != 0
7937 m_NonZeroInt())) &&
7938 (CmpInst::isEquality(Pred) || Pred == ICmpInst::ICMP_ULT)) {
7939 ICmpInst::Predicate NewPred =
7940 CmpInst::isEquality(Pred) ? Pred.dropSameSign() : ICmpInst::ICMP_NE;
7941 return new ICmpInst(NewPred, Op1, Constant::getNullValue(Op1->getType()));
7942 }
7943 }
7944
7945 const SimplifyQuery Q = SQ.getWithInstruction(&CtxI);
7946 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7947 return replaceInstUsesWith(CtxI, V);
7948
7949 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7950 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7951 {
7952 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7953 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7955 }
7956
7957 if (!ICmpInst::isUnsigned(Pred) &&
7958 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7959 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7961 }
7962 }
7963
7964 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7965 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7966 {
7967 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7968 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7970 }
7971
7972 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7973 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7974 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7976 }
7977 }
7978
7979 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7980 // -> icmp X, (add nsw/nuw Y, K >> L)
7981 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7982 Value *X;
7983 uint64_t ShAmt;
7984 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7985 !CtxI.isSigned()) {
7986 if (ShAmt >= X->getType()->getScalarSizeInBits())
7987 return nullptr;
7988 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7989 ShiftSemantics::Unsigned, &CtxI)) {
7990 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7992 return new ICmpInst(Pred, X, NewOp1);
7993 }
7994 }
7995
7996 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7997 !CtxI.isUnsigned()) {
7998 if (ShAmt >= X->getType()->getScalarSizeInBits())
7999 return nullptr;
8000 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
8001 ShiftSemantics::Signed, &CtxI)) {
8002 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
8004 return new ICmpInst(Pred, X, NewOp1);
8005 }
8006 }
8007 return nullptr;
8008}
8009
8011 bool Changed = false;
8012 const SimplifyQuery Q = SQ.getWithInstruction(&I);
8013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8014 unsigned Op0Cplxity = getComplexity(Op0);
8015 unsigned Op1Cplxity = getComplexity(Op1);
8016
8017 /// Orders the operands of the compare so that they are listed from most
8018 /// complex to least complex. This puts constants before unary operators,
8019 /// before binary operators.
8020 if (Op0Cplxity < Op1Cplxity) {
8021 I.swapOperands();
8022 std::swap(Op0, Op1);
8023 Changed = true;
8024 }
8025
8026 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
8027 return replaceInstUsesWith(I, V);
8028
8029 // Comparing -val or val with non-zero is the same as just comparing val
8030 // ie, abs(val) != 0 -> val != 0
8031 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
8032 Value *Cond, *SelectTrue, *SelectFalse;
8033 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
8034 m_Value(SelectFalse)))) {
8035 if (Value *V = dyn_castNegVal(SelectTrue)) {
8036 if (V == SelectFalse)
8037 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8038 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
8039 if (V == SelectTrue)
8040 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8041 }
8042 }
8043 }
8044
8046 return Res;
8047
8048 if (Op0->getType()->isIntOrIntVectorTy(1))
8050 return Res;
8051
8053 return Res;
8054
8056 return Res;
8057
8059 return Res;
8060
8062 return Res;
8063
8065 return Res;
8066
8068 return Res;
8069
8071 return Res;
8072
8073 // Test if the ICmpInst instruction is used exclusively by a select as
8074 // part of a minimum or maximum operation. If so, refrain from doing
8075 // any other folding. This helps out other analyses which understand
8076 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8077 // and CodeGen. And in this case, at least one of the comparison
8078 // operands has at least one user besides the compare (the select),
8079 // which would often largely negate the benefit of folding anyway.
8080 //
8081 // Do the same for the other patterns recognized by matchSelectPattern.
8082 if (I.hasOneUse())
8083 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8084 Value *A, *B;
8086 if (SPR.Flavor != SPF_UNKNOWN)
8087 return nullptr;
8088 }
8089
8090 // Do this after checking for min/max to prevent infinite looping.
8091 if (Instruction *Res = foldICmpWithZero(I))
8092 return Res;
8093
8094 Value *X;
8095 const APInt *C;
8096 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8097 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8098 match(Op1, m_Not(m_Specific(X)))) {
8099 if (C->isNonNegative())
8100 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8101 Constant::getNullValue(X->getType()));
8102 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8103 ConstantInt::get(X->getType(), ~*C));
8104 }
8105
8106 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8107 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8108 match(Op1, m_Not(m_Specific(X)))) {
8109 if (C->isNonNegative())
8110 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8111 Constant::getAllOnesValue(X->getType()));
8112 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8113 ConstantInt::get(X->getType(), ~*C));
8114 }
8115
8116 // FIXME: We only do this after checking for min/max to prevent infinite
8117 // looping caused by a reverse canonicalization of these patterns for min/max.
8118 // FIXME: The organization of folds is a mess. These would naturally go into
8119 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8120 // down here after the min/max restriction.
8121 ICmpInst::Predicate Pred = I.getPredicate();
8122 if (match(Op1, m_APInt(C))) {
8123 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8124 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8125 Constant *Zero = Constant::getNullValue(Op0->getType());
8126 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8127 }
8128
8129 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8130 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8132 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8133 }
8134 }
8135
8136 // The folds in here may rely on wrapping flags and special constants, so
8137 // they can break up min/max idioms in some cases but not seemingly similar
8138 // patterns.
8139 // FIXME: It may be possible to enhance select folding to make this
8140 // unnecessary. It may also be moot if we canonicalize to min/max
8141 // intrinsics.
8142 if (Instruction *Res = foldICmpBinOp(I, Q))
8143 return Res;
8144
8146 return Res;
8147
8148 // Try to match comparison as a sign bit test. Intentionally do this after
8149 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8150 if (Instruction *New = foldSignBitTest(I))
8151 return New;
8152
8153 if (auto *PN = dyn_cast<PHINode>(Op0))
8154 if (Instruction *NV = foldOpIntoPhi(I, PN))
8155 return NV;
8156 if (auto *PN = dyn_cast<PHINode>(Op1))
8157 if (Instruction *NV = foldOpIntoPhi(I, PN))
8158 return NV;
8159
8161 return Res;
8162
8163 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8164 return Res;
8165 if (Instruction *Res =
8166 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8167 return Res;
8168
8169 if (I.isCommutative()) {
8170 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8171 replaceOperand(I, 0, Pair->first);
8172 replaceOperand(I, 1, Pair->second);
8173 return &I;
8174 }
8175 }
8176
8177 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8178 // when all select arms are constants, via truth table.
8180 return R;
8181
8182 // In case of a comparison with two select instructions having the same
8183 // condition, check whether one of the resulting branches can be simplified.
8184 // If so, just compare the other branch and select the appropriate result.
8185 // For example:
8186 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8187 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8188 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8189 // The icmp will result false for the false value of selects and the result
8190 // will depend upon the comparison of true values of selects if %cmp is
8191 // true. Thus, transform this into:
8192 // %cmp = icmp slt i32 %y, %z
8193 // %sel = select i1 %cond, i1 %cmp, i1 false
8194 // This handles similar cases to transform.
8195 {
8196 Value *Cond, *A, *B, *C, *D;
8197 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8199 (Op0->hasOneUse() || Op1->hasOneUse())) {
8200 // Check whether comparison of TrueValues can be simplified
8201 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8202 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8203 return SelectInst::Create(Cond, Res, NewICMP, /*NameStr=*/"",
8204 /*InsertBefore=*/nullptr,
8205 cast<Instruction>(Op0));
8206 }
8207 // Check whether comparison of FalseValues can be simplified
8208 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8209 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8210 return SelectInst::Create(Cond, NewICMP, Res, /*NameStr=*/"",
8211 /*InsertBefore=*/nullptr,
8212 cast<Instruction>(Op0));
8213 }
8214 }
8215 }
8216
8217 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8218 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8219 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8220 {
8221 Value *A, *B;
8222 CmpPredicate CmpPred;
8223 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8225 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8226 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8227 bool I0NUW = I0->hasNoUnsignedWrap();
8228 bool I1NUW = I1->hasNoUnsignedWrap();
8229 bool I0NSW = I0->hasNoSignedWrap();
8230 bool I1NSW = I1->hasNoSignedWrap();
8231 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8232 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8233 (ICmpInst::isEquality(Pred) &&
8234 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8235 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8236 ConstantInt::get(Op0->getType(), 0));
8237 }
8238 }
8239 }
8240
8241 // Try to optimize equality comparisons against alloca-based pointers.
8242 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8243 assert(Op1->getType()->isPointerTy() &&
8244 "Comparing pointer with non-pointer?");
8245 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8246 if (foldAllocaCmp(Alloca))
8247 return nullptr;
8248 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8249 if (foldAllocaCmp(Alloca))
8250 return nullptr;
8251 }
8252
8253 if (Instruction *Res = foldICmpBitCast(I))
8254 return Res;
8255
8256 // TODO: Hoist this above the min/max bailout.
8258 return R;
8259
8260 // icmp (zext X), (and (trunc Y), Mask) -> icmp X, trunc Y IFF Mask exactly
8261 // covers the bits of X
8262 {
8263 Value *Y;
8264 const APInt *Mask;
8265 if (match(I.getOperand(1), m_ZExt(m_Value(X))) &&
8266 match(I.getOperand(0),
8267 m_OneUse(m_And(m_Trunc(m_Value(Y)), m_APInt(Mask))))) {
8268 Type *SmallType = X->getType();
8269 unsigned SmallWidth = SmallType->getScalarSizeInBits();
8270 if (Mask->isMask(SmallWidth) &&
8271 shouldChangeType(I.getOperand(0)->getType(), SmallType)) {
8272 Value *NewTrunc = Builder.CreateTrunc(Y, SmallType);
8273 return new ICmpInst(I.getUnsignedPredicate(), NewTrunc, X);
8274 }
8275 }
8276 }
8277
8278 {
8279 Value *X, *Y;
8280 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8281 // and (X & ~Y) != 0 --> (X & Y) == 0
8282 // if A is a power of 2.
8283 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8284 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8285 I.isEquality())
8286 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8287 Op1);
8288
8289 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8290 if (Op0->getType()->isIntOrIntVectorTy()) {
8291 bool ConsumesOp0, ConsumesOp1;
8292 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8293 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8294 (ConsumesOp0 || ConsumesOp1)) {
8295 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8296 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8297 assert(InvOp0 && InvOp1 &&
8298 "Mismatch between isFreeToInvert and getFreelyInverted");
8299 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8300 }
8301 }
8302
8303 Instruction *AddI = nullptr;
8305 m_Instruction(AddI))) &&
8306 isa<IntegerType>(X->getType())) {
8307 Value *Result;
8308 Constant *Overflow;
8309 // m_UAddWithOverflow can match patterns that do not include an explicit
8310 // "add" instruction, so check the opcode of the matched op.
8311 if (AddI->getOpcode() == Instruction::Add &&
8312 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8313 Result, Overflow)) {
8314 replaceInstUsesWith(*AddI, Result);
8315 eraseInstFromFunction(*AddI);
8316 return replaceInstUsesWith(I, Overflow);
8317 }
8318 }
8319
8320 // (zext X) + (zext Y) --> add + overflow check.
8321 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8322 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8323 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8324 match(Op1, m_APInt(C))) {
8325 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8326 return R;
8327 }
8328
8329 // Signbit test folds
8330 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8331 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8332 Instruction *ExtI;
8333 if ((I.isUnsigned() || I.isEquality()) &&
8334 match(Op1,
8336 Y->getType()->getScalarSizeInBits() == 1 &&
8337 (Op0->hasOneUse() || Op1->hasOneUse())) {
8338 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8339 Instruction *ShiftI;
8340 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8342 OpWidth - 1))))) {
8343 unsigned ExtOpc = ExtI->getOpcode();
8344 unsigned ShiftOpc = ShiftI->getOpcode();
8345 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8346 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8347 Value *SLTZero =
8348 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8349 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8350 return replaceInstUsesWith(I, Cmp);
8351 }
8352 }
8353 }
8354 }
8355
8356 if (Instruction *Res = foldICmpEquality(I))
8357 return Res;
8358
8360 return Res;
8361
8362 if (Instruction *Res = foldICmpOfUAddOv(I))
8363 return Res;
8364
8366 return Res;
8367
8368 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8369 // an i1 which indicates whether or not we successfully did the swap.
8370 //
8371 // Replace comparisons between the old value and the expected value with the
8372 // indicator that 'cmpxchg' returns.
8373 //
8374 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8375 // spuriously fail. In those cases, the old value may equal the expected
8376 // value but it is possible for the swap to not occur.
8377 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8378 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8379 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8380 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8381 !ACXI->isWeak())
8382 return ExtractValueInst::Create(ACXI, 1);
8383
8385 return Res;
8386
8387 if (I.getType()->isVectorTy())
8388 if (Instruction *Res = foldVectorCmp(I, Builder))
8389 return Res;
8390
8392 return Res;
8393
8395 return Res;
8396
8397 {
8398 Value *A;
8399 const APInt *C1, *C2;
8400 ICmpInst::Predicate Pred = I.getPredicate();
8401 if (ICmpInst::isEquality(Pred)) {
8402 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8403 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8404 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8405 match(Op1, m_APInt(C2))) {
8406 Type *InputTy = A->getType();
8407 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8408 // c2 must be non-negative at the bitwidth of a.
8409 if (C2->getActiveBits() < InputBitWidth) {
8410 APInt TruncC1 = C1->trunc(InputBitWidth);
8411 // Check if there are 1s in C1 high bits of size InputBitWidth.
8412 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8413 TruncC1.setBit(InputBitWidth - 1);
8414 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8415 return new ICmpInst(
8416 Pred, AndInst,
8417 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8418 }
8419 }
8420 }
8421 }
8422
8423 return Changed ? &I : nullptr;
8424}
8425
8426/// Fold fcmp ([us]itofp x, cst) if possible.
8428 Instruction *LHSI,
8429 Constant *RHSC) {
8430 const APFloat *RHS;
8431 if (!match(RHSC, m_APFloat(RHS)))
8432 return nullptr;
8433
8434 // Get the width of the mantissa. We don't want to hack on conversions that
8435 // might lose information from the integer, e.g. "i64 -> float"
8436 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8437 if (MantissaWidth == -1)
8438 return nullptr; // Unknown.
8439
8440 Type *IntTy = LHSI->getOperand(0)->getType();
8441 unsigned IntWidth = IntTy->getScalarSizeInBits();
8442 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8443
8444 if (I.isEquality()) {
8445 FCmpInst::Predicate P = I.getPredicate();
8446 bool IsExact = false;
8447 APSInt RHSCvt(IntWidth, LHSUnsigned);
8448 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8449
8450 // If the floating point constant isn't an integer value, we know if we will
8451 // ever compare equal / not equal to it.
8452 if (!IsExact) {
8453 // TODO: Can never be -0.0 and other non-representable values
8454 APFloat RHSRoundInt(*RHS);
8456 if (*RHS != RHSRoundInt) {
8458 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8459
8461 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8462 }
8463 }
8464
8465 // TODO: If the constant is exactly representable, is it always OK to do
8466 // equality compares as integer?
8467 }
8468
8469 // Check to see that the input is converted from an integer type that is small
8470 // enough that preserves all bits. TODO: check here for "known" sign bits.
8471 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8472
8473 // Following test does NOT adjust IntWidth downwards for signed inputs,
8474 // because the most negative value still requires all the mantissa bits
8475 // to distinguish it from one less than that value.
8476 if ((int)IntWidth > MantissaWidth) {
8477 // Conversion would lose accuracy. Check if loss can impact comparison.
8478 int Exp = ilogb(*RHS);
8479 if (Exp == APFloat::IEK_Inf) {
8480 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8481 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8482 // Conversion could create infinity.
8483 return nullptr;
8484 } else {
8485 // Note that if RHS is zero or NaN, then Exp is negative
8486 // and first condition is trivially false.
8487 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8488 // Conversion could affect comparison.
8489 return nullptr;
8490 }
8491 }
8492
8493 // Otherwise, we can potentially simplify the comparison. We know that it
8494 // will always come through as an integer value and we know the constant is
8495 // not a NAN (it would have been previously simplified).
8496 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8497
8499 switch (I.getPredicate()) {
8500 default:
8501 llvm_unreachable("Unexpected predicate!");
8502 case FCmpInst::FCMP_UEQ:
8503 case FCmpInst::FCMP_OEQ:
8504 Pred = ICmpInst::ICMP_EQ;
8505 break;
8506 case FCmpInst::FCMP_UGT:
8507 case FCmpInst::FCMP_OGT:
8508 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8509 break;
8510 case FCmpInst::FCMP_UGE:
8511 case FCmpInst::FCMP_OGE:
8512 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8513 break;
8514 case FCmpInst::FCMP_ULT:
8515 case FCmpInst::FCMP_OLT:
8516 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8517 break;
8518 case FCmpInst::FCMP_ULE:
8519 case FCmpInst::FCMP_OLE:
8520 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8521 break;
8522 case FCmpInst::FCMP_UNE:
8523 case FCmpInst::FCMP_ONE:
8524 Pred = ICmpInst::ICMP_NE;
8525 break;
8526 case FCmpInst::FCMP_ORD:
8527 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8528 case FCmpInst::FCMP_UNO:
8529 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8530 }
8531
8532 // Now we know that the APFloat is a normal number, zero or inf.
8533
8534 // See if the FP constant is too large for the integer. For example,
8535 // comparing an i8 to 300.0.
8536 if (!LHSUnsigned) {
8537 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8538 // and large values.
8539 APFloat SMax(RHS->getSemantics());
8540 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8542 if (SMax < *RHS) { // smax < 13123.0
8543 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8544 Pred == ICmpInst::ICMP_SLE)
8545 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8546 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8547 }
8548 } else {
8549 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8550 // +INF and large values.
8551 APFloat UMax(RHS->getSemantics());
8552 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8554 if (UMax < *RHS) { // umax < 13123.0
8555 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8556 Pred == ICmpInst::ICMP_ULE)
8557 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8558 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8559 }
8560 }
8561
8562 if (!LHSUnsigned) {
8563 // See if the RHS value is < SignedMin.
8564 APFloat SMin(RHS->getSemantics());
8565 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8567 if (SMin > *RHS) { // smin > 12312.0
8568 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8569 Pred == ICmpInst::ICMP_SGE)
8570 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8571 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8572 }
8573 } else {
8574 // See if the RHS value is < UnsignedMin.
8575 APFloat UMin(RHS->getSemantics());
8576 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8578 if (UMin > *RHS) { // umin > 12312.0
8579 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8580 Pred == ICmpInst::ICMP_UGE)
8581 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8582 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8583 }
8584 }
8585
8586 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8587 // [0, UMAX], but it may still be fractional. Check whether this is the case
8588 // using the IsExact flag.
8589 // Don't do this for zero, because -0.0 is not fractional.
8590 APSInt RHSInt(IntWidth, LHSUnsigned);
8591 bool IsExact;
8592 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8593 if (!RHS->isZero()) {
8594 if (!IsExact) {
8595 // If we had a comparison against a fractional value, we have to adjust
8596 // the compare predicate and sometimes the value. RHSC is rounded towards
8597 // zero at this point.
8598 switch (Pred) {
8599 default:
8600 llvm_unreachable("Unexpected integer comparison!");
8601 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8602 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8603 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8604 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8605 case ICmpInst::ICMP_ULE:
8606 // (float)int <= 4.4 --> int <= 4
8607 // (float)int <= -4.4 --> false
8608 if (RHS->isNegative())
8609 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8610 break;
8611 case ICmpInst::ICMP_SLE:
8612 // (float)int <= 4.4 --> int <= 4
8613 // (float)int <= -4.4 --> int < -4
8614 if (RHS->isNegative())
8615 Pred = ICmpInst::ICMP_SLT;
8616 break;
8617 case ICmpInst::ICMP_ULT:
8618 // (float)int < -4.4 --> false
8619 // (float)int < 4.4 --> int <= 4
8620 if (RHS->isNegative())
8621 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8622 Pred = ICmpInst::ICMP_ULE;
8623 break;
8624 case ICmpInst::ICMP_SLT:
8625 // (float)int < -4.4 --> int < -4
8626 // (float)int < 4.4 --> int <= 4
8627 if (!RHS->isNegative())
8628 Pred = ICmpInst::ICMP_SLE;
8629 break;
8630 case ICmpInst::ICMP_UGT:
8631 // (float)int > 4.4 --> int > 4
8632 // (float)int > -4.4 --> true
8633 if (RHS->isNegative())
8634 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8635 break;
8636 case ICmpInst::ICMP_SGT:
8637 // (float)int > 4.4 --> int > 4
8638 // (float)int > -4.4 --> int >= -4
8639 if (RHS->isNegative())
8640 Pred = ICmpInst::ICMP_SGE;
8641 break;
8642 case ICmpInst::ICMP_UGE:
8643 // (float)int >= -4.4 --> true
8644 // (float)int >= 4.4 --> int > 4
8645 if (RHS->isNegative())
8646 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8647 Pred = ICmpInst::ICMP_UGT;
8648 break;
8649 case ICmpInst::ICMP_SGE:
8650 // (float)int >= -4.4 --> int >= -4
8651 // (float)int >= 4.4 --> int > 4
8652 if (!RHS->isNegative())
8653 Pred = ICmpInst::ICMP_SGT;
8654 break;
8655 }
8656 }
8657 }
8658
8659 // Lower this FP comparison into an appropriate integer version of the
8660 // comparison.
8661 return new ICmpInst(Pred, LHSI->getOperand(0),
8662 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8663}
8664
8665/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8666/// where all true/false values are constants that allow the compare to be
8667/// constant-folded for every combination of C1 and C2.
8668/// We compute a 4-entry truth table and use createLogicFromTable to
8669/// synthesize a boolean expression of C1 and C2.
8671 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8672 Value *C1, *C2;
8673 Constant *TV1, *FV1, *TV2, *FV2;
8674
8675 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8676 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8677 return nullptr;
8678
8679 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8680 return nullptr;
8681
8682 unsigned Pred = I.getPredicate();
8683 const DataLayout &DL = I.getDataLayout();
8684
8685 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8686 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8687 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8688 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8689
8690 if (!Res00 || !Res01 || !Res10 || !Res11)
8691 return nullptr;
8692
8693 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8694 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8695 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8696 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8697 return nullptr;
8698
8699 std::bitset<4> Table;
8700 if (!Res00->isNullValue())
8701 Table.set(0);
8702 if (!Res01->isNullValue())
8703 Table.set(1);
8704 if (!Res10->isNullValue())
8705 Table.set(2);
8706 if (!Res11->isNullValue())
8707 Table.set(3);
8708
8709 Value *Res = createLogicFromTable(Table, C1, C2, Builder,
8710 Op0->hasOneUse() && Op1->hasOneUse());
8711 if (!Res)
8712 return nullptr;
8713 return replaceInstUsesWith(I, Res);
8714}
8715
8716/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8718 Constant *RHSC) {
8719 // When C is not 0.0 and infinities are not allowed:
8720 // (C / X) < 0.0 is a sign-bit test of X
8721 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8722 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8723 //
8724 // Proof:
8725 // Multiply (C / X) < 0.0 by X * X / C.
8726 // - X is non zero, if it is the flag 'ninf' is violated.
8727 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8728 // the predicate. C is also non zero by definition.
8729 //
8730 // Thus X * X / C is non zero and the transformation is valid. [qed]
8731
8732 FCmpInst::Predicate Pred = I.getPredicate();
8733
8734 // Check that predicates are valid.
8735 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8736 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8737 return nullptr;
8738
8739 // Check that RHS operand is zero.
8740 if (!match(RHSC, m_AnyZeroFP()))
8741 return nullptr;
8742
8743 // Check fastmath flags ('ninf').
8744 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8745 return nullptr;
8746
8747 // Check the properties of the dividend. It must not be zero to avoid a
8748 // division by zero (see Proof).
8749 const APFloat *C;
8750 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8751 return nullptr;
8752
8753 if (C->isZero())
8754 return nullptr;
8755
8756 // Get swapped predicate if necessary.
8757 if (C->isNegative())
8758 Pred = I.getSwappedPredicate();
8759
8760 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8761}
8762
8763// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8764// Patterns include:
8765// fptrunc(x) < C --> x < ext(C)
8766// fptrunc(x) <= C --> x <= ext(C)
8767// fptrunc(x) > C --> x > ext(C)
8768// fptrunc(x) >= C --> x >= ext(C)
8769// fptrunc(x) ord/uno C --> x ord/uno 0
8770// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8771// due to precision loss.
8773 const Constant &C) {
8774 FCmpInst::Predicate Pred = I.getPredicate();
8775 Type *DestType = FPTrunc.getOperand(0)->getType();
8776
8777 const APFloat *CValue;
8778 // TODO: support vec
8779 if (!match(&C, m_APFloat(CValue)))
8780 return nullptr;
8781
8782 // Handle ord/uno
8783 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8784 assert(!CValue->isNaN() &&
8785 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8786 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8787 ConstantFP::getZero(DestType), "", &I);
8788 }
8789
8790 // Handle <, >, <=, >=
8791 bool RoundDown = false;
8792
8793 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8794 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8795 RoundDown = true;
8796 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8797 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8798 RoundDown = false;
8799 else
8800 return nullptr;
8801
8802 if (CValue->isNaN() || CValue->isInfinity())
8803 return nullptr;
8804
8805 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8806 bool LosesInfo;
8807 APFloat Dest = Src;
8808 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8809 return Dest;
8810 };
8811
8812 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8813 APFloat NextValue = Value;
8814 NextValue.next(RoundDown);
8815 return NextValue;
8816 };
8817
8818 APFloat NextCValue = NextValue(*CValue, RoundDown);
8819
8820 const fltSemantics &DestFltSema =
8821 DestType->getScalarType()->getFltSemantics();
8822
8823 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8824 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8825
8826 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8827 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8828 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8829 // value of 'CValue'.
8830 if (NextCValue.isInfinity()) {
8831 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8832 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8833
8834 ExtNextCValue = ExtCValue + Bias;
8835 }
8836
8837 APFloat ExtMidValue =
8838 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8839
8840 const fltSemantics &SrcFltSema =
8841 C.getType()->getScalarType()->getFltSemantics();
8842
8843 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8844 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8845 if (MidValue != *CValue)
8846 ExtMidValue.next(!RoundDown);
8847
8848 // Check whether 'ExtMidValue' is a valid result since the assumption on
8849 // imaged 'NextCValue' might not hold for new float types.
8850 // ppc_fp128 can't pass here when converting from max float because of
8851 // APFloat implementation.
8852 if (NextCValue.isInfinity()) {
8853 // ExtMidValue --- narrowed ---> Finite
8854 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8855 return nullptr;
8856
8857 // NextExtMidValue --- narrowed ---> Infinity
8858 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8859 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8860 return nullptr;
8861 }
8862
8863 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8864 ConstantFP::get(DestType, ExtMidValue), "", &I);
8865}
8866
8867/// Optimize fabs(X) compared with zero.
8869 Value *X;
8870 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8871 return nullptr;
8872
8873 const APFloat *C;
8874 if (!match(I.getOperand(1), m_APFloat(C)))
8875 return nullptr;
8876
8877 if (!C->isPosZero()) {
8878 if (!C->isSmallestNormalized())
8879 return nullptr;
8880
8881 const Function *F = I.getFunction();
8882 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8883 if (Mode.Input == DenormalMode::PreserveSign ||
8885
8886 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8887 Constant *Zero = ConstantFP::getZero(X->getType());
8888 return new FCmpInst(P, X, Zero, "", I);
8889 };
8890
8891 switch (I.getPredicate()) {
8892 case FCmpInst::FCMP_OLT:
8893 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8894 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8895 case FCmpInst::FCMP_UGE:
8896 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8897 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8898 case FCmpInst::FCMP_OGE:
8899 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8900 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8901 case FCmpInst::FCMP_ULT:
8902 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8903 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8904 default:
8905 break;
8906 }
8907 }
8908
8909 return nullptr;
8910 }
8911
8912 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8913 I->setPredicate(P);
8914 return IC.replaceOperand(*I, 0, X);
8915 };
8916
8917 switch (I.getPredicate()) {
8918 case FCmpInst::FCMP_UGE:
8919 case FCmpInst::FCMP_OLT:
8920 // fabs(X) >= 0.0 --> true
8921 // fabs(X) < 0.0 --> false
8922 llvm_unreachable("fcmp should have simplified");
8923
8924 case FCmpInst::FCMP_OGT:
8925 // fabs(X) > 0.0 --> X != 0.0
8926 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8927
8928 case FCmpInst::FCMP_UGT:
8929 // fabs(X) u> 0.0 --> X u!= 0.0
8930 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8931
8932 case FCmpInst::FCMP_OLE:
8933 // fabs(X) <= 0.0 --> X == 0.0
8934 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8935
8936 case FCmpInst::FCMP_ULE:
8937 // fabs(X) u<= 0.0 --> X u== 0.0
8938 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8939
8940 case FCmpInst::FCMP_OGE:
8941 // fabs(X) >= 0.0 --> !isnan(X)
8942 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8943 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8944
8945 case FCmpInst::FCMP_ULT:
8946 // fabs(X) u< 0.0 --> isnan(X)
8947 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8948 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8949
8950 case FCmpInst::FCMP_OEQ:
8951 case FCmpInst::FCMP_UEQ:
8952 case FCmpInst::FCMP_ONE:
8953 case FCmpInst::FCMP_UNE:
8954 case FCmpInst::FCMP_ORD:
8955 case FCmpInst::FCMP_UNO:
8956 // Look through the fabs() because it doesn't change anything but the sign.
8957 // fabs(X) == 0.0 --> X == 0.0,
8958 // fabs(X) != 0.0 --> X != 0.0
8959 // isnan(fabs(X)) --> isnan(X)
8960 // !isnan(fabs(X) --> !isnan(X)
8961 return replacePredAndOp0(&I, I.getPredicate(), X);
8962
8963 default:
8964 return nullptr;
8965 }
8966}
8967
8968/// Optimize sqrt(X) compared with zero.
8970 Value *X;
8971 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8972 return nullptr;
8973
8974 if (!match(I.getOperand(1), m_PosZeroFP()))
8975 return nullptr;
8976
8977 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8978 I.setPredicate(P);
8979 return IC.replaceOperand(I, 0, X);
8980 };
8981
8982 // Clear ninf flag if sqrt doesn't have it.
8983 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8984 I.setHasNoInfs(false);
8985
8986 switch (I.getPredicate()) {
8987 case FCmpInst::FCMP_OLT:
8988 case FCmpInst::FCMP_UGE:
8989 // sqrt(X) < 0.0 --> false
8990 // sqrt(X) u>= 0.0 --> true
8991 llvm_unreachable("fcmp should have simplified");
8992 case FCmpInst::FCMP_ULT:
8993 case FCmpInst::FCMP_ULE:
8994 case FCmpInst::FCMP_OGT:
8995 case FCmpInst::FCMP_OGE:
8996 case FCmpInst::FCMP_OEQ:
8997 case FCmpInst::FCMP_UNE:
8998 // sqrt(X) u< 0.0 --> X u< 0.0
8999 // sqrt(X) u<= 0.0 --> X u<= 0.0
9000 // sqrt(X) > 0.0 --> X > 0.0
9001 // sqrt(X) >= 0.0 --> X >= 0.0
9002 // sqrt(X) == 0.0 --> X == 0.0
9003 // sqrt(X) u!= 0.0 --> X u!= 0.0
9004 return IC.replaceOperand(I, 0, X);
9005
9006 case FCmpInst::FCMP_OLE:
9007 // sqrt(X) <= 0.0 --> X == 0.0
9008 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
9009 case FCmpInst::FCMP_UGT:
9010 // sqrt(X) u> 0.0 --> X u!= 0.0
9011 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
9012 case FCmpInst::FCMP_UEQ:
9013 // sqrt(X) u== 0.0 --> X u<= 0.0
9014 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
9015 case FCmpInst::FCMP_ONE:
9016 // sqrt(X) != 0.0 --> X > 0.0
9017 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
9018 case FCmpInst::FCMP_ORD:
9019 // !isnan(sqrt(X)) --> X >= 0.0
9020 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
9021 case FCmpInst::FCMP_UNO:
9022 // isnan(sqrt(X)) --> X u< 0.0
9023 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
9024 default:
9025 llvm_unreachable("Unexpected predicate!");
9026 }
9027}
9028
9030 CmpInst::Predicate Pred = I.getPredicate();
9031 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9032
9033 // Canonicalize fneg as Op1.
9034 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
9035 std::swap(Op0, Op1);
9036 Pred = I.getSwappedPredicate();
9037 }
9038
9039 if (!match(Op1, m_FNeg(m_Specific(Op0))))
9040 return nullptr;
9041
9042 // Replace the negated operand with 0.0:
9043 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
9044 Constant *Zero = ConstantFP::getZero(Op0->getType());
9045 return new FCmpInst(Pred, Op0, Zero, "", &I);
9046}
9047
9049 Constant *RHSC, InstCombinerImpl &CI) {
9050 const CmpInst::Predicate Pred = I.getPredicate();
9051 Value *X = LHSI->getOperand(0);
9052 Value *Y = LHSI->getOperand(1);
9053 switch (Pred) {
9054 default:
9055 break;
9056 case FCmpInst::FCMP_UGT:
9057 case FCmpInst::FCMP_ULT:
9058 case FCmpInst::FCMP_UNE:
9059 case FCmpInst::FCMP_OEQ:
9060 case FCmpInst::FCMP_OGE:
9061 case FCmpInst::FCMP_OLE:
9062 // The optimization is not valid if X and Y are infinities of the same
9063 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9064 // flag then we can assume we do not have that case. Otherwise we might be
9065 // able to prove that either X or Y is not infinity.
9066 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9070 break;
9071
9072 [[fallthrough]];
9073 case FCmpInst::FCMP_OGT:
9074 case FCmpInst::FCMP_OLT:
9075 case FCmpInst::FCMP_ONE:
9076 case FCmpInst::FCMP_UEQ:
9077 case FCmpInst::FCMP_UGE:
9078 case FCmpInst::FCMP_ULE:
9079 // fcmp pred (x - y), 0 --> fcmp pred x, y
9080 if (match(RHSC, m_AnyZeroFP()) &&
9081 I.getFunction()->getDenormalMode(
9082 LHSI->getType()->getScalarType()->getFltSemantics()) ==
9084 CI.replaceOperand(I, 0, X);
9085 CI.replaceOperand(I, 1, Y);
9086 I.setHasNoInfs(LHSI->hasNoInfs());
9087 if (LHSI->hasNoNaNs())
9088 I.setHasNoNaNs(true);
9089 return &I;
9090 }
9091 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9092 // where C and Y can't be arbitrary floating-point values.
9093 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9094 // to `1.0f`, so the source compare is false while the rewritten compare is
9095 // true.
9096 // We need to make sure (C - Y) never rounds back to C
9097 const APFloat *C;
9098 Value *IntSrc;
9099 if (match(RHSC, m_APFloat(C)) &&
9100 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9101 C->isNormal()) {
9102 // Requirements on C and Y:
9103 // 1. C is finite, nonzero, normal.
9104 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9105 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9106 // must be integer-valued with an absolute value of at least 1;
9107 // as long as the step size near C does not exceed 1,
9108 // C - Y cannot be rounded back to C when Y != 0.
9109 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9110 // 0, 0` for ordered and unordered predicates as long as C is finite and
9111 // nonzero.
9112 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9113 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9114 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9115 I.setPredicate(I.getSwappedPredicate());
9116 CI.replaceOperand(I, 0, Y);
9117 CI.replaceOperand(I, 1, ZeroC);
9118 return &I;
9119 }
9120 }
9121 break;
9122 }
9123
9124 return nullptr;
9125}
9126
9127/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9128/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9129/// float when the uitofp casts are exact and C is in the valid range.
9130///
9131/// Since exact uitofp means distinct integers map to distinct floats, the only
9132/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9133/// There are no values in the open interval (0, 1), so:
9134/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9135// fabs(..) >= C where C >= 1.0 -> a != b
9136///
9137/// The same logic applies to sitofp.
9139 Value *FAbsArg;
9140 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9141 return nullptr;
9142
9143 const APFloat *C;
9144 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9145 return nullptr;
9146
9147 FCmpInst::Predicate Pred = I.getPredicate();
9148 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9149 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9150 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9151 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9152 if (!IsStrictLt && !IsStrictGt && !IsGe)
9153 return nullptr;
9154
9155 APFloat One = APFloat::getOne(C->getSemantics());
9156 APFloat::cmpResult Cmp = C->compare(One);
9157
9158 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9159 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9160 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9161 return nullptr;
9162 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9163 return nullptr;
9164 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9165 return nullptr;
9166 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9167 return nullptr;
9168
9169 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9170 Value *A, *B;
9171 bool IsSigned;
9172 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9173 IsSigned = false;
9174 } else if (match(FAbsArg,
9176 IsSigned = true;
9177 } else {
9178 return nullptr;
9179 }
9180
9181 // A and B must have the same integer type
9182 if (A->getType() != B->getType())
9183 return nullptr;
9184
9185 Type *FPTy = FAbsArg->getType();
9186 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9187 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9188 return nullptr;
9189 ICmpInst::Predicate ResultPred =
9190 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9191 return new ICmpInst(ResultPred, A, B);
9192}
9193
9195 InstCombinerImpl &IC) {
9196 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9197 Type *OpType = LHS->getType();
9198 CmpInst::Predicate Pred = I.getPredicate();
9199
9202
9203 if (!FloorX && !CeilX) {
9206 std::swap(LHS, RHS);
9207 Pred = I.getSwappedPredicate();
9208 }
9209 }
9210
9211 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9212 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9213 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9214 // where pred is oeq, one, ord, ueq, une, uno.
9215 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9216 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9217 }
9218
9219 switch (Pred) {
9220 case FCmpInst::FCMP_OLE:
9221 // fcmp ole floor(x), x => fcmp ord x, 0
9222 if (FloorX)
9224 "", &I);
9225 break;
9226 case FCmpInst::FCMP_OGT:
9227 // fcmp ogt floor(x), x => false
9228 if (FloorX)
9229 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9230 break;
9231 case FCmpInst::FCMP_OGE:
9232 // fcmp oge ceil(x), x => fcmp ord x, 0
9233 if (CeilX)
9235 "", &I);
9236 break;
9237 case FCmpInst::FCMP_OLT:
9238 // fcmp olt ceil(x), x => false
9239 if (CeilX)
9240 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9241 break;
9242 case FCmpInst::FCMP_ULE:
9243 // fcmp ule floor(x), x => true
9244 if (FloorX)
9245 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9246 break;
9247 case FCmpInst::FCMP_UGT:
9248 // fcmp ugt floor(x), x => fcmp uno x, 0
9249 if (FloorX)
9251 "", &I);
9252 break;
9253 case FCmpInst::FCMP_UGE:
9254 // fcmp uge ceil(x), x => true
9255 if (CeilX)
9256 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9257 break;
9258 case FCmpInst::FCMP_ULT:
9259 // fcmp ult ceil(x), x => fcmp uno x, 0
9260 if (CeilX)
9262 "", &I);
9263 break;
9264 default:
9265 break;
9266 }
9267
9268 return nullptr;
9269}
9270
9271/// Returns true if a select that implements a min/max is redundant and
9272/// select result can be replaced with its non-constant operand, e.g.,
9273/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9274/// where C is the FP constant equal to the minimum integer value
9275/// representable by A.
9277 Value *B) {
9278 const APFloat *APF;
9279 if (!match(B, m_APFloat(APF)))
9280 return false;
9281
9282 auto *I = dyn_cast<Instruction>(A);
9283 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9284 I->getOpcode() == Instruction::UIToFP))
9285 return false;
9286
9287 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9288 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9289 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9290 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9291 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9292 APSInt ConvertedInt(BitWidth, IsUnsigned);
9293 bool IsExact;
9295 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9296 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9297}
9298
9300 bool Changed = false;
9301
9302 /// Orders the operands of the compare so that they are listed from most
9303 /// complex to least complex. This puts constants before unary operators,
9304 /// before binary operators.
9305 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9306 I.swapOperands();
9307 Changed = true;
9308 }
9309
9310 const CmpInst::Predicate Pred = I.getPredicate();
9311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9312 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9313 SQ.getWithInstruction(&I)))
9314 return replaceInstUsesWith(I, V);
9315
9316 // Simplify 'fcmp pred X, X'
9317 Type *OpType = Op0->getType();
9318 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9319 if (Op0 == Op1) {
9320 switch (Pred) {
9321 default:
9322 break;
9323 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9324 case FCmpInst::FCMP_ULT: // True if unordered or less than
9325 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9326 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9327 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9328 I.setPredicate(FCmpInst::FCMP_UNO);
9329 I.setOperand(1, Constant::getNullValue(OpType));
9330 return &I;
9331
9332 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9333 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9334 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9335 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9336 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9337 I.setPredicate(FCmpInst::FCMP_ORD);
9338 I.setOperand(1, Constant::getNullValue(OpType));
9339 return &I;
9340 }
9341 }
9342
9343 if (I.isCommutative()) {
9344 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9345 replaceOperand(I, 0, Pair->first);
9346 replaceOperand(I, 1, Pair->second);
9347 return &I;
9348 }
9349 }
9350
9351 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9352 // then canonicalize the operand to 0.0.
9353 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9354 if (!match(Op0, m_PosZeroFP()) &&
9355 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9356 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9357
9358 if (!match(Op1, m_PosZeroFP()) &&
9359 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9360 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9361 }
9362
9363 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9364 Value *X, *Y;
9365 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9366 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9367
9369 return R;
9370
9371 // Test if the FCmpInst instruction is used exclusively by a select as
9372 // part of a minimum or maximum operation. If so, refrain from doing
9373 // any other folding. This helps out other analyses which understand
9374 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9375 // and CodeGen. And in this case, at least one of the comparison
9376 // operands has at least one user besides the compare (the select),
9377 // which would often largely negate the benefit of folding anyway.
9378 if (I.hasOneUse())
9379 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9380 Value *A, *B;
9382 bool IsRedundantMinMaxClamp =
9383 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9385 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9386 return nullptr;
9387 }
9388
9389 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9390 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9391 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9392 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9393
9394 // Canonicalize:
9395 // fcmp olt X, +inf -> fcmp one X, +inf
9396 // fcmp ole X, +inf -> fcmp ord X, 0
9397 // fcmp ogt X, +inf -> false
9398 // fcmp oge X, +inf -> fcmp oeq X, +inf
9399 // fcmp ult X, +inf -> fcmp une X, +inf
9400 // fcmp ule X, +inf -> true
9401 // fcmp ugt X, +inf -> fcmp uno X, 0
9402 // fcmp uge X, +inf -> fcmp ueq X, +inf
9403 // fcmp olt X, -inf -> false
9404 // fcmp ole X, -inf -> fcmp oeq X, -inf
9405 // fcmp ogt X, -inf -> fcmp one X, -inf
9406 // fcmp oge X, -inf -> fcmp ord X, 0
9407 // fcmp ult X, -inf -> fcmp uno X, 0
9408 // fcmp ule X, -inf -> fcmp ueq X, -inf
9409 // fcmp ugt X, -inf -> fcmp une X, -inf
9410 // fcmp uge X, -inf -> true
9411 const APFloat *C;
9412 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9413 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9414 default:
9415 break;
9416 case FCmpInst::FCMP_ORD:
9417 case FCmpInst::FCMP_UNO:
9420 case FCmpInst::FCMP_OGT:
9421 case FCmpInst::FCMP_ULE:
9422 llvm_unreachable("Should be simplified by InstSimplify");
9423 case FCmpInst::FCMP_OLT:
9424 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9425 case FCmpInst::FCMP_OLE:
9426 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9427 "", &I);
9428 case FCmpInst::FCMP_OGE:
9429 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9430 case FCmpInst::FCMP_ULT:
9431 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9432 case FCmpInst::FCMP_UGT:
9433 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9434 "", &I);
9435 case FCmpInst::FCMP_UGE:
9436 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9437 }
9438 }
9439
9440 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9441 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9442 if (match(Op1, m_PosZeroFP()) &&
9444 X->getType()->isIntOrIntVectorTy() &&
9445 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9446 .inputsMayBeZero()) {
9448 if (Pred == FCmpInst::FCMP_OEQ)
9449 IntPred = ICmpInst::ICMP_EQ;
9450 else if (Pred == FCmpInst::FCMP_UNE)
9451 IntPred = ICmpInst::ICMP_NE;
9452
9453 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9454 Type *IntTy = X->getType();
9455 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9456 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9457 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9458 }
9459 }
9460
9461 // Handle fcmp with instruction LHS and constant RHS.
9462 Instruction *LHSI;
9463 Constant *RHSC;
9464 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9465 switch (LHSI->getOpcode()) {
9466 case Instruction::Select:
9467 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9468 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9470 return replaceOperand(I, 0, X);
9472 return NV;
9473 break;
9474 case Instruction::FSub:
9475 if (LHSI->hasOneUse())
9476 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9477 return NV;
9478 break;
9479 case Instruction::PHI:
9480 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9481 return NV;
9482 break;
9483 case Instruction::SIToFP:
9484 case Instruction::UIToFP:
9485 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9486 return NV;
9487 break;
9488 case Instruction::FDiv:
9489 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9490 return NV;
9491 break;
9492 case Instruction::Load:
9493 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9495 cast<LoadInst>(LHSI), GEP, I.getPredicate(), RHSC, I))
9496 return Res;
9497 break;
9498 case Instruction::FPTrunc:
9499 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9500 return NV;
9501 break;
9502 }
9503 }
9504
9505 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9506 return R;
9507
9508 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9509 return R;
9510
9511 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9512 return R;
9513
9514 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9515 return R;
9516
9518 return R;
9519
9520 if (match(Op0, m_FNeg(m_Value(X)))) {
9521 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9522 Constant *C;
9523 if (match(Op1, m_Constant(C)))
9524 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9525 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9526 }
9527
9528 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9529 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9530 return new FCmpInst(Pred, X, Op1, "", &I);
9531
9532 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9533 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9534 return new FCmpInst(Pred, Op0, Y, "", &I);
9535
9536 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9537 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9538 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9539 X->getType() == Y->getType())
9540 return new FCmpInst(Pred, X, Y, "", &I);
9541
9542 if (match(Op0, m_FPExt(m_Value(X)))) {
9543 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9544 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9545 return new FCmpInst(Pred, X, Y, "", &I);
9546
9547 const APFloat *C;
9548 if (match(Op1, m_APFloat(C))) {
9549 const fltSemantics &FPSem =
9550 X->getType()->getScalarType()->getFltSemantics();
9551 bool Lossy;
9552 APFloat TruncC = *C;
9554
9555 if (Lossy) {
9556 // X can't possibly equal the higher-precision constant, so reduce any
9557 // equality comparison.
9558 // TODO: Other predicates can be handled via getFCmpCode().
9559 switch (Pred) {
9560 case FCmpInst::FCMP_OEQ:
9561 // X is ordered and equal to an impossible constant --> false
9562 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9563 case FCmpInst::FCMP_ONE:
9564 // X is ordered and not equal to an impossible constant --> ordered
9565 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9566 ConstantFP::getZero(X->getType()));
9567 case FCmpInst::FCMP_UEQ:
9568 // X is unordered or equal to an impossible constant --> unordered
9569 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9570 ConstantFP::getZero(X->getType()));
9571 case FCmpInst::FCMP_UNE:
9572 // X is unordered or not equal to an impossible constant --> true
9573 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9574 default:
9575 break;
9576 }
9577 }
9578
9579 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9580 // Avoid lossy conversions and denormals.
9581 // Zero is a special case that's OK to convert.
9582 APFloat Fabs = TruncC;
9583 Fabs.clearSign();
9584 if (!Lossy &&
9585 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9586 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9587 return new FCmpInst(Pred, X, NewC, "", &I);
9588 }
9589 }
9590 }
9591
9592 // Convert a sign-bit test of an FP value into a cast and integer compare.
9593 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9594 // TODO: Handle non-zero compare constants.
9595 // TODO: Handle other predicates.
9597 m_Value(X)))) &&
9598 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9599 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9600 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9601 IntType = VectorType::get(IntType, VecTy->getElementCount());
9602
9603 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9604 if (Pred == FCmpInst::FCMP_OLT) {
9605 Value *IntX = Builder.CreateBitCast(X, IntType);
9606 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9607 ConstantInt::getNullValue(IntType));
9608 }
9609 }
9610
9611 {
9612 Value *CanonLHS = nullptr;
9614 // (canonicalize(x) == x) => (x == x)
9615 if (CanonLHS == Op1)
9616 return new FCmpInst(Pred, Op1, Op1, "", &I);
9617
9618 Value *CanonRHS = nullptr;
9620 // (x == canonicalize(x)) => (x == x)
9621 if (CanonRHS == Op0)
9622 return new FCmpInst(Pred, Op0, Op0, "", &I);
9623
9624 // (canonicalize(x) == canonicalize(y)) => (x == y)
9625 if (CanonLHS && CanonRHS)
9626 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9627 }
9628
9629 if (I.getType()->isVectorTy())
9630 if (Instruction *Res = foldVectorCmp(I, Builder))
9631 return Res;
9632
9633 return Changed ? &I : nullptr;
9634}
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:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define Check(C,...)
Hexagon Common GEP
static Instruction * foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
static Instruction * foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize fabs(X) compared with zero.
static void collectOffsetOp(Value *V, SmallVectorImpl< OffsetOp > &Offsets, bool AllowRecursion)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW, const DataLayout &DL, SetVector< Value * > &Explored, InstCombiner &IC)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A, Value *B)
Returns true if a select that implements a min/max is redundant and select result can be replaced wit...
static Instruction * foldICmpEqualityWithOffset(ICmpInst &I, InstCombiner::BuilderTy &Builder, const SimplifyQuery &SQ)
Offset both sides of an equality icmp to see if we can save some instructions: icmp eq/ne X,...
static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
static Instruction * foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL, IRBuilderBase &Builder)
static Instruction * foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * foldVectorCmp(CmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q, unsigned Depth=0)
static Value * createLogicFromTable(const std::bitset< 4 > &Table, Value *Op0, Value *Op1, IRBuilderBase &Builder, bool HasOneUse)
static Instruction * foldICmpOfUAddOv(ICmpInst &I)
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
static Instruction * foldICmpInvariantGroup(ICmpInst &I)
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static Instruction * foldReductionIdiom(ICmpInst &I, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
This function folds patterns produced by lowering of reduce idioms, such as llvm.vector....
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
static Instruction * foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI, Constant *RHSC, InstCombinerImpl &CI)
static Value * foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or, InstCombiner::BuilderTy &Builder)
Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
static Value * foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0, Value *Op1, const SimplifyQuery &Q, InstCombiner &IC)
Some comparisons can be simplified.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
static Instruction * foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl nuw C2, Y), C.
static Instruction * foldFCmpWithFloorAndCeil(FCmpInst &I, InstCombinerImpl &IC)
static Instruction * foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * processUZExtIdiom(ICmpInst &I, Value *Val, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for unsigned overflow.
static Instruction * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize sqrt(X) compared with zero.
static Instruction * foldFCmpFNegCommonOp(FCmpInst &I)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
static Instruction * foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
Fold an icmp with LLVM intrinsics.
static Instruction * foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpPow2Test(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW, const DataLayout &DL, SetVector< Value * > &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
static Instruction * foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc, const Constant &C)
static Instruction * foldICmpXNegX(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombinerImpl &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
static Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, const DataLayout &DL, InstCombiner &IC)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
static Instruction * foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs, const APInt &CRhs, InstCombiner::BuilderTy &Builder, const SimplifyQuery &Q)
static Instruction * foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC)
Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b where 'pred' is olt, ult, ogt,...
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned)
static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q)
Return true if X is a multiple of C.
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
static Instruction * foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
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:6045
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:5974
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1083
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:61
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 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
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2801
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2819
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
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 isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp: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:267
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
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 isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h: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.