LLVM 24.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
35#include <bitset>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42// How many times is a select replaced by one of its operands?
43STATISTIC(NumSel, "Number of select opts");
44
45namespace llvm {
47}
48
49/// Compute Result = In1+In2, returning true if the result overflowed for this
50/// type.
51static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
52 bool IsSigned = false) {
53 bool Overflow;
54 if (IsSigned)
55 Result = In1.sadd_ov(In2, Overflow);
56 else
57 Result = In1.uadd_ov(In2, Overflow);
58
59 return Overflow;
60}
61
62/// Compute Result = In1-In2, returning true if the result overflowed for this
63/// type.
64static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
65 bool IsSigned = false) {
66 bool Overflow;
67 if (IsSigned)
68 Result = In1.ssub_ov(In2, Overflow);
69 else
70 Result = In1.usub_ov(In2, Overflow);
71
72 return Overflow;
73}
74
75/// Given an icmp instruction, return true if any use of this comparison is a
76/// branch on sign bit comparison.
77static bool hasBranchUse(ICmpInst &I) {
78 for (auto *U : I.users())
79 if (isa<CondBrInst>(U))
80 return true;
81 return false;
82}
83
84/// Returns true if the exploded icmp can be expressed as a signed comparison
85/// to zero and updates the predicate accordingly.
86/// The signedness of the comparison is preserved.
87/// TODO: Refactor with decomposeBitTestICmp()?
88static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
89 if (!ICmpInst::isSigned(Pred))
90 return false;
91
92 if (C.isZero())
93 return ICmpInst::isRelational(Pred);
94
95 if (C.isOne()) {
96 if (Pred == ICmpInst::ICMP_SLT) {
97 Pred = ICmpInst::ICMP_SLE;
98 return true;
99 }
100 } else if (C.isAllOnes()) {
101 if (Pred == ICmpInst::ICMP_SGT) {
102 Pred = ICmpInst::ICMP_SGE;
103 return true;
104 }
105 }
106
107 return false;
108}
109
110/// This is called when we see this pattern:
111/// cmp pred (load (gep GV, ...)), cmpcst
112/// where GV is a global variable with a constant initializer. Try to simplify
113/// this into some simple computation that does not need the load. For example
114/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
115///
116/// If AndCst is non-null, then the loaded value is masked with that constant
117/// before doing the comparison. This handles cases like "A[i]&4 == 0".
119 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
121 if (LI->isVolatile() || !GV || !GV->isConstant() ||
122 !GV->hasDefinitiveInitializer())
123 return nullptr;
124
125 Type *EltTy = LI->getType();
126 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
127 if (EltSize.isScalable())
128 return nullptr;
129
131 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
132 return nullptr;
133
134 Constant *Init = GV->getInitializer();
135 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
136
137 Value *Idx = Expr.Index;
138 const APInt &Stride = Expr.Scale;
139 const APInt &ConstOffset = Expr.Offset;
140
141 // Allow an additional context offset, but only within the stride.
142 if (!ConstOffset.ult(Stride))
143 return nullptr;
144
145 // Don't handle overlapping loads for now.
146 if (!Stride.uge(EltSize.getFixedValue()))
147 return nullptr;
148
149 // Don't blow up on huge arrays.
150 uint64_t ArrayElementCount =
151 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
152 Stride.getZExtValue());
153 if (ArrayElementCount > MaxArraySizeForCombine)
154 return nullptr;
155
156 enum { Overdefined = -3, Undefined = -2 };
157
158 // Variables for our state machines.
159
160 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
161 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
162 // and 87 is the second (and last) index. FirstTrueElement is -2 when
163 // undefined, otherwise set to the first true element. SecondTrueElement is
164 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
165 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
166
167 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
168 // form "i != 47 & i != 87". Same state transitions as for true elements.
169 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
170
171 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
172 /// define a state machine that triggers for ranges of values that the index
173 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
174 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
175 /// index in the range (inclusive). We use -2 for undefined here because we
176 /// use relative comparisons and don't want 0-1 to match -1.
177 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
178
179 // MagicBitvector - This is a magic bitvector where we set a bit if the
180 // comparison is true for element 'i'. If there are 64 elements or less in
181 // the array, this will fully represent all the comparison results.
182 uint64_t MagicBitvector = 0;
183
184 // Scan the array and see if one of our patterns matches.
185 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
186 APInt Offset = ConstOffset;
187 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
189 if (!Elt)
190 return nullptr;
191
192 // If the element is masked, handle it.
193 if (AndCst) {
194 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
195 if (!Elt)
196 return nullptr;
197 }
198
199 // Find out if the comparison would be true or false for the i'th element.
201 CompareRHS, DL, &TLI);
202 if (!C)
203 return nullptr;
204
205 // If the result is undef for this element, ignore it.
206 if (isa<UndefValue>(C)) {
207 // Extend range state machines to cover this element in case there is an
208 // undef in the middle of the range.
209 if (TrueRangeEnd == (int)i - 1)
210 TrueRangeEnd = i;
211 if (FalseRangeEnd == (int)i - 1)
212 FalseRangeEnd = i;
213 continue;
214 }
215
216 // If we can't compute the result for any of the elements, we have to give
217 // up evaluating the entire conditional.
218 if (!isa<ConstantInt>(C))
219 return nullptr;
220
221 // Otherwise, we know if the comparison is true or false for this element,
222 // update our state machines.
223 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
224
225 // State machine for single/double/range index comparison.
226 if (IsTrueForElt) {
227 // Update the TrueElement state machine.
228 if (FirstTrueElement == Undefined)
229 FirstTrueElement = TrueRangeEnd = i; // First true element.
230 else {
231 // Update double-compare state machine.
232 if (SecondTrueElement == Undefined)
233 SecondTrueElement = i;
234 else
235 SecondTrueElement = Overdefined;
236
237 // Update range state machine.
238 if (TrueRangeEnd == (int)i - 1)
239 TrueRangeEnd = i;
240 else
241 TrueRangeEnd = Overdefined;
242 }
243 } else {
244 // Update the FalseElement state machine.
245 if (FirstFalseElement == Undefined)
246 FirstFalseElement = FalseRangeEnd = i; // First false element.
247 else {
248 // Update double-compare state machine.
249 if (SecondFalseElement == Undefined)
250 SecondFalseElement = i;
251 else
252 SecondFalseElement = Overdefined;
253
254 // Update range state machine.
255 if (FalseRangeEnd == (int)i - 1)
256 FalseRangeEnd = i;
257 else
258 FalseRangeEnd = Overdefined;
259 }
260 }
261
262 // If this element is in range, update our magic bitvector.
263 if (i < 64 && IsTrueForElt)
264 MagicBitvector |= 1ULL << i;
265
266 // If all of our states become overdefined, bail out early. Since the
267 // predicate is expensive, only check it every 8 elements. This is only
268 // really useful for really huge arrays.
269 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
270 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
271 FalseRangeEnd == Overdefined)
272 return nullptr;
273 }
274
275 // Now that we've scanned the entire array, emit our new comparison(s). We
276 // order the state machines in complexity of the generated code.
277
278 // If inbounds keyword is not present, Idx * Stride can overflow.
279 // Let's assume that Stride is 2 and the wanted value is at offset 0.
280 // Then, there are two possible values for Idx to match offset 0:
281 // 0x00..00, 0x80..00.
282 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
283 // comparison is false if Idx was 0x80..00.
284 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
285 auto MaskIdx = [&](Value *Idx) {
286 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
288 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
289 Idx = Builder.CreateAnd(Idx, Mask);
290 }
291 return Idx;
292 };
293
294 // If the comparison is only true for one or two elements, emit direct
295 // comparisons.
296 if (SecondTrueElement != Overdefined) {
297 Idx = MaskIdx(Idx);
298 // None true -> false.
299 if (FirstTrueElement == Undefined)
300 return replaceInstUsesWith(ICI, Builder.getFalse());
301
302 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
303
304 // True for one element -> 'i == 47'.
305 if (SecondTrueElement == Undefined)
306 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
307
308 // True for two elements -> 'i == 47 | i == 72'.
309 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
310 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
311 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
312 return BinaryOperator::CreateOr(C1, C2);
313 }
314
315 // If the comparison is only false for one or two elements, emit direct
316 // comparisons.
317 if (SecondFalseElement != Overdefined) {
318 Idx = MaskIdx(Idx);
319 // None false -> true.
320 if (FirstFalseElement == Undefined)
321 return replaceInstUsesWith(ICI, Builder.getTrue());
322
323 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
324
325 // False for one element -> 'i != 47'.
326 if (SecondFalseElement == Undefined)
327 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
328
329 // False for two elements -> 'i != 47 & i != 72'.
330 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
331 Value *SecondFalseIdx =
332 ConstantInt::get(Idx->getType(), SecondFalseElement);
333 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
334 return BinaryOperator::CreateAnd(C1, C2);
335 }
336
337 // If the comparison can be replaced with a range comparison for the elements
338 // where it is true, emit the range check.
339 if (TrueRangeEnd != Overdefined) {
340 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
341 Idx = MaskIdx(Idx);
342
343 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
344 if (FirstTrueElement) {
345 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
346 Idx = Builder.CreateAdd(Idx, Offs);
347 }
348
349 Value *End =
350 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
351 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
352 }
353
354 // False range check.
355 if (FalseRangeEnd != Overdefined) {
356 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
357 Idx = MaskIdx(Idx);
358 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
359 if (FirstFalseElement) {
360 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
361 Idx = Builder.CreateAdd(Idx, Offs);
362 }
363
364 Value *End =
365 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
366 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
367 }
368
369 // If a magic bitvector captures the entire comparison state
370 // of this load, replace it with computation that does:
371 // ((magic_cst >> i) & 1) != 0
372 {
373 Type *Ty = nullptr;
374
375 // Look for an appropriate type:
376 // - The type of Idx if the magic fits
377 // - The smallest fitting legal type
378 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
379 Ty = Idx->getType();
380 else
381 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
382
383 if (Ty) {
384 Idx = MaskIdx(Idx);
385 Value *V = Builder.CreateIntCast(Idx, Ty, false);
386 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
387 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
388 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
389 }
390 }
391
392 return nullptr;
393}
394
395/// Returns true if we can rewrite Start as a GEP with pointer Base
396/// and some integer offset. The nodes that need to be re-written
397/// for this transformation will be added to Explored.
399 const DataLayout &DL,
400 SetVector<Value *> &Explored) {
401 SmallVector<Value *, 16> WorkList(1, Start);
402 Explored.insert(Base);
403
404 // The following traversal gives us an order which can be used
405 // when doing the final transformation. Since in the final
406 // transformation we create the PHI replacement instructions first,
407 // we don't have to get them in any particular order.
408 //
409 // However, for other instructions we will have to traverse the
410 // operands of an instruction first, which means that we have to
411 // do a post-order traversal.
412 while (!WorkList.empty()) {
414
415 while (!WorkList.empty()) {
416 if (Explored.size() >= 100)
417 return false;
418
419 Value *V = WorkList.back();
420
421 if (Explored.contains(V)) {
422 WorkList.pop_back();
423 continue;
424 }
425
427 // We've found some value that we can't explore which is different from
428 // the base. Therefore we can't do this transformation.
429 return false;
430
431 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
432 // Only allow inbounds GEPs with at most one variable offset.
433 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
434 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
435 return false;
436
437 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
438 if (!Explored.contains(GEP->getOperand(0)))
439 WorkList.push_back(GEP->getOperand(0));
440 }
441
442 if (WorkList.back() == V) {
443 WorkList.pop_back();
444 // We've finished visiting this node, mark it as such.
445 Explored.insert(V);
446 }
447
448 if (auto *PN = dyn_cast<PHINode>(V)) {
449 // We cannot transform PHIs on unsplittable basic blocks.
450 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
451 return false;
452 Explored.insert(PN);
453 PHIs.insert(PN);
454 }
455 }
456
457 // Explore the PHI nodes further.
458 for (auto *PN : PHIs)
459 for (Value *Op : PN->incoming_values())
460 if (!Explored.contains(Op))
461 WorkList.push_back(Op);
462 }
463
464 // Make sure that we can do this. Since we can't insert GEPs in a basic
465 // block before a PHI node, we can't easily do this transformation if
466 // we have PHI node users of transformed instructions.
467 for (Value *Val : Explored) {
468 for (Value *Use : Val->uses()) {
469
470 auto *PHI = dyn_cast<PHINode>(Use);
471 auto *Inst = dyn_cast<Instruction>(Val);
472
473 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
474 !Explored.contains(PHI))
475 continue;
476
477 if (PHI->getParent() == Inst->getParent())
478 return false;
479 }
480 }
481 return true;
482}
483
484// Sets the appropriate insert point on Builder where we can add
485// a replacement Instruction for V (if that is possible).
486static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
487 bool Before = true) {
488 if (auto *PHI = dyn_cast<PHINode>(V)) {
489 BasicBlock *Parent = PHI->getParent();
490 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
491 return;
492 }
493 if (auto *I = dyn_cast<Instruction>(V)) {
494 if (!Before)
495 I = &*std::next(I->getIterator());
496 Builder.SetInsertPoint(I);
497 return;
498 }
499 if (auto *A = dyn_cast<Argument>(V)) {
500 // Set the insertion point in the entry block.
501 BasicBlock &Entry = A->getParent()->getEntryBlock();
502 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
503 return;
504 }
505 // Otherwise, this is a constant and we don't need to set a new
506 // insertion point.
507 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
508}
509
510/// Returns a re-written value of Start as an indexed GEP using Base as a
511/// pointer.
513 const DataLayout &DL,
514 SetVector<Value *> &Explored,
515 InstCombiner &IC) {
516 // Perform all the substitutions. This is a bit tricky because we can
517 // have cycles in our use-def chains.
518 // 1. Create the PHI nodes without any incoming values.
519 // 2. Create all the other values.
520 // 3. Add the edges for the PHI nodes.
521 // 4. Emit GEPs to get the original pointers.
522 // 5. Remove the original instructions.
523 Type *IndexType = IntegerType::get(
524 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
525
527 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
528
529 // Create the new PHI nodes, without adding any incoming values.
530 for (Value *Val : Explored) {
531 if (Val == Base)
532 continue;
533 // Create empty phi nodes. This avoids cyclic dependencies when creating
534 // the remaining instructions.
535 if (auto *PHI = dyn_cast<PHINode>(Val))
536 NewInsts[PHI] =
537 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
538 PHI->getName() + ".idx", PHI->getIterator());
539 }
540 IRBuilder<> Builder(Base->getContext());
541
542 // Create all the other instructions.
543 for (Value *Val : Explored) {
544 if (NewInsts.contains(Val))
545 continue;
546
547 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
548 setInsertionPoint(Builder, GEP);
549 Value *Op = NewInsts[GEP->getOperand(0)];
550 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
552 NewInsts[GEP] = OffsetV;
553 else
554 NewInsts[GEP] = Builder.CreateAdd(
555 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
556 /*NUW=*/NW.hasNoUnsignedWrap(),
557 /*NSW=*/NW.hasNoUnsignedSignedWrap());
558 continue;
559 }
560 if (isa<PHINode>(Val))
561 continue;
562
563 llvm_unreachable("Unexpected instruction type");
564 }
565
566 // Add the incoming values to the PHI nodes.
567 for (Value *Val : Explored) {
568 if (Val == Base)
569 continue;
570 // All the instructions have been created, we can now add edges to the
571 // phi nodes.
572 if (auto *PHI = dyn_cast<PHINode>(Val)) {
573 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
574 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
575 Value *NewIncoming = PHI->getIncomingValue(I);
576
577 auto It = NewInsts.find(NewIncoming);
578 if (It != NewInsts.end())
579 NewIncoming = It->second;
580
581 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
582 }
583 }
584 }
585
586 for (Value *Val : Explored) {
587 if (Val == Base)
588 continue;
589
590 setInsertionPoint(Builder, Val, false);
591 // Create GEP for external users.
592 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
593 Val->getName() + ".ptr", NW);
594 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
595 // Add old instruction to worklist for DCE. We don't directly remove it
596 // here because the original compare is one of the users.
598 }
599
600 return NewInsts[Start];
601}
602
603/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
604/// We can look through PHIs, GEPs and casts in order to determine a common base
605/// between GEPLHS and RHS.
608 const DataLayout &DL,
609 InstCombiner &IC) {
610 // FIXME: Support vector of pointers.
611 if (GEPLHS->getType()->isVectorTy())
612 return nullptr;
613
614 if (!GEPLHS->hasAllConstantIndices())
615 return nullptr;
616
617 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
618 Value *PtrBase =
620 /*AllowNonInbounds*/ false);
621
622 // Bail if we looked through addrspacecast.
623 if (PtrBase->getType() != GEPLHS->getType())
624 return nullptr;
625
626 // The set of nodes that will take part in this transformation.
627 SetVector<Value *> Nodes;
628 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
629 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
630 return nullptr;
631
632 // We know we can re-write this as
633 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
634 // Since we've only looked through inbouds GEPs we know that we
635 // can't have overflow on either side. We can therefore re-write
636 // this as:
637 // OFFSET1 cmp OFFSET2
638 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
639
640 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
641 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
642 // offset. Since Index is the offset of LHS to the base pointer, we will now
643 // compare the offsets instead of comparing the pointers.
645 IC.Builder.getInt(Offset), NewRHS);
646}
647
648/// Fold comparisons between a GEP instruction and something else. At this point
649/// we know that the GEP is on the LHS of the comparison.
652 // Don't transform signed compares of GEPs into index compares. Even if the
653 // GEP is inbounds, the final add of the base pointer can have signed overflow
654 // and would change the result of the icmp.
655 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
656 // the maximum signed value for the pointer type.
658 return nullptr;
659
660 // Look through bitcasts and addrspacecasts. We do not however want to remove
661 // 0 GEPs.
662 if (!isa<GetElementPtrInst>(RHS))
663 RHS = RHS->stripPointerCasts();
664
665 auto CanFold = [Cond](GEPNoWrapFlags NW) {
667 return true;
668
669 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
671 return NW != GEPNoWrapFlags::none();
672 };
673
674 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
675 if (!NW.hasNoUnsignedWrap()) {
676 // Convert signed to unsigned comparison.
677 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
678 }
679
680 auto *I = new ICmpInst(Cond, Op1, Op2);
681 I->setSameSign(NW.hasNoUnsignedSignedWrap());
682 return I;
683 };
684
686 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
687 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
688 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
689 Value *Offset =
690 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
691 return NewICmp(Base.LHSNW, Offset,
692 Constant::getNullValue(Offset->getType()));
693 }
694
695 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
697 !NullPointerIsDefined(I.getFunction(),
698 RHS->getType()->getPointerAddressSpace())) {
699 // For most address spaces, an allocation can't be placed at null, but null
700 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
701 // the only valid inbounds address derived from null, is null itself.
702 // Thus, we have four cases to consider:
703 // 1) Base == nullptr, Offset == 0 -> inbounds, null
704 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
705 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
706 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
707 //
708 // (Note if we're indexing a type of size 0, that simply collapses into one
709 // of the buckets above.)
710 //
711 // In general, we're allowed to make values less poison (i.e. remove
712 // sources of full UB), so in this case, we just select between the two
713 // non-poison cases (1 and 4 above).
714 //
715 // For vectors, we apply the same reasoning on a per-lane basis.
716 auto *Base = GEPLHS->getPointerOperand();
717 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
718 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
719 Base = Builder.CreateVectorSplat(EC, Base);
720 }
721 return new ICmpInst(Cond, Base,
723 cast<Constant>(RHS), Base->getType()));
724 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
725 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
726
727 // If the base pointers are different, but the indices are the same, just
728 // compare the base pointer.
729 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
730 bool IndicesTheSame =
731 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
732 GEPLHS->getPointerOperand()->getType() ==
733 GEPRHS->getPointerOperand()->getType() &&
734 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
735 if (IndicesTheSame)
736 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
737 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
738 IndicesTheSame = false;
739 break;
740 }
741
742 // If all indices are the same, just compare the base pointers.
743 Type *BaseType = GEPLHS->getOperand(0)->getType();
744 if (IndicesTheSame &&
745 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
746 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
747
748 // If we're comparing GEPs with two base pointers that only differ in type
749 // and both GEPs have only constant indices or just one use, then fold
750 // the compare with the adjusted indices.
751 // FIXME: Support vector of pointers.
752 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
753 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
754 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
755 GEPLHS->getOperand(0)->stripPointerCasts() ==
756 GEPRHS->getOperand(0)->stripPointerCasts() &&
757 !GEPLHS->getType()->isVectorTy()) {
758 Value *LOffset = EmitGEPOffset(GEPLHS);
759 Value *ROffset = EmitGEPOffset(GEPRHS);
760
761 // If we looked through an addrspacecast between different sized address
762 // spaces, the LHS and RHS pointers are different sized
763 // integers. Truncate to the smaller one.
764 Type *LHSIndexTy = LOffset->getType();
765 Type *RHSIndexTy = ROffset->getType();
766 if (LHSIndexTy != RHSIndexTy) {
767 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
768 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
769 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
770 } else
771 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
772 }
773
775 LOffset, ROffset);
776 return replaceInstUsesWith(I, Cmp);
777 }
778 }
779
780 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
781 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
782 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
783 // If the GEPs only differ by one index, compare it.
784 unsigned NumDifferences = 0; // Keep track of # differences.
785 unsigned DiffOperand = 0; // The operand that differs.
786 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
787 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
788 Type *LHSType = GEPLHS->getOperand(i)->getType();
789 Type *RHSType = GEPRHS->getOperand(i)->getType();
790 // FIXME: Better support for vector of pointers.
791 if (LHSType->getPrimitiveSizeInBits() !=
792 RHSType->getPrimitiveSizeInBits() ||
793 (GEPLHS->getType()->isVectorTy() &&
794 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
795 // Irreconcilable differences.
796 NumDifferences = 2;
797 break;
798 }
799
800 if (NumDifferences++)
801 break;
802 DiffOperand = i;
803 }
804
805 if (NumDifferences == 0) // SAME GEP?
806 return replaceInstUsesWith(
807 I, // No comparison is needed here.
808 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
809 // If two GEPs only differ by an index, compare them.
810 // Note that nowrap flags are always needed when comparing two indices.
811 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
812 Value *LHSV = GEPLHS->getOperand(DiffOperand);
813 Value *RHSV = GEPRHS->getOperand(DiffOperand);
814 return NewICmp(NW, LHSV, RHSV);
815 }
816 }
817
818 if (Base.Ptr && !Base.isExpensive()) {
819 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
820 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
821
822 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
823 // Without the flags, we can still fold if the offsets are constant and
824 // they cross the base's alignment boundary the same number of times, so
825 // either both arguments will wrap, or none of them will.
826 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
827 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
828 APInt LOff(BW, 0);
829 APInt ROff(BW, 0);
831 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
832 RHS->stripAndAccumulateConstantOffsets(
833 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
834 DoFold =
837 }
838
839 if (DoFold) {
840 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
841 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
842 /*RewriteGEP=*/true);
843 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
844 /*RewriteGEP=*/true);
845 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
846 }
847 }
848 }
849
850 // Try convert this to an indexed compare by looking through PHIs/casts as a
851 // last resort.
852 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
853}
854
856 // It would be tempting to fold away comparisons between allocas and any
857 // pointer not based on that alloca (e.g. an argument). However, even
858 // though such pointers cannot alias, they can still compare equal.
859 //
860 // But LLVM doesn't specify where allocas get their memory, so if the alloca
861 // doesn't escape we can argue that it's impossible to guess its value, and we
862 // can therefore act as if any such guesses are wrong.
863 //
864 // However, we need to ensure that this folding is consistent: We can't fold
865 // one comparison to false, and then leave a different comparison against the
866 // same value alone (as it might evaluate to true at runtime, leading to a
867 // contradiction). As such, this code ensures that all comparisons are folded
868 // at the same time, and there are no other escapes.
869
870 struct CmpCaptureTracker : public CaptureTracker {
871 AllocaInst *Alloca;
872 bool Captured = false;
873 /// The value of the map is a bit mask of which icmp operands the alloca is
874 /// used in.
876
877 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
878
879 void tooManyUses() override { Captured = true; }
880
881 Action captured(const Use *U, UseCaptureInfo CI) override {
882 // TODO(captures): Use UseCaptureInfo.
883 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
884 // We need to check that U is based *only* on the alloca, and doesn't
885 // have other contributions from a select/phi operand.
886 // TODO: We could check whether getUnderlyingObjects() reduces to one
887 // object, which would allow looking through phi nodes.
888 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
889 // Collect equality icmps of the alloca, and don't treat them as
890 // captures.
891 ICmps[ICmp] |= 1u << U->getOperandNo();
892 return Continue;
893 }
894
895 Captured = true;
896 return Stop;
897 }
898 };
899
900 CmpCaptureTracker Tracker(Alloca);
901 PointerMayBeCaptured(Alloca, &Tracker);
902 if (Tracker.Captured)
903 return false;
904
905 bool Changed = false;
906 for (auto [ICmp, Operands] : Tracker.ICmps) {
907 switch (Operands) {
908 case 1:
909 case 2: {
910 // The alloca is only used in one icmp operand. Assume that the
911 // equality is false.
912 auto *Res = ConstantInt::get(ICmp->getType(),
913 ICmp->getPredicate() == ICmpInst::ICMP_NE);
914 replaceInstUsesWith(*ICmp, Res);
916 Changed = true;
917 break;
918 }
919 case 3:
920 // Both icmp operands are based on the alloca, so this is comparing
921 // pointer offsets, without leaking any information about the address
922 // of the alloca. Ignore such comparisons.
923 break;
924 default:
925 llvm_unreachable("Cannot happen");
926 }
927 }
928
929 return Changed;
930}
931
932/// Fold "icmp pred (X+C), X".
934 CmpPredicate Pred) {
935 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
936 // so the values can never be equal. Similarly for all other "or equals"
937 // operators.
938 assert(!!C && "C should not be zero!");
939
940 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
941 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
942 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
943 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
944 Constant *R =
945 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
946 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
947 }
948
949 // (X+1) >u X --> X <u (0-1) --> X != 255
950 // (X+2) >u X --> X <u (0-2) --> X <u 254
951 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
952 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
953 return new ICmpInst(ICmpInst::ICMP_ULT, X,
954 ConstantInt::get(X->getType(), -C));
955
956 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
957
958 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
959 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
960 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
961 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
962 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
963 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
964 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
965 return new ICmpInst(ICmpInst::ICMP_SGT, X,
966 ConstantInt::get(X->getType(), SMax - C));
967
968 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
969 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
970 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
971 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
972 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
973 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
974
975 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
976 return new ICmpInst(ICmpInst::ICMP_SLT, X,
977 ConstantInt::get(X->getType(), SMax - (C - 1)));
978}
979
980/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
981/// (icmp eq/ne A, Log2(AP2/AP1)) ->
982/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
984 const APInt &AP1,
985 const APInt &AP2) {
986 assert(I.isEquality() && "Cannot fold icmp gt/lt");
987
988 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
989 if (I.getPredicate() == I.ICMP_NE)
990 Pred = CmpInst::getInversePredicate(Pred);
991 return new ICmpInst(Pred, LHS, RHS);
992 };
993
994 // Don't bother doing any work for cases which InstSimplify handles.
995 if (AP2.isZero())
996 return nullptr;
997
998 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
999 if (IsAShr) {
1000 if (AP2.isAllOnes())
1001 return nullptr;
1002 if (AP2.isNegative() != AP1.isNegative())
1003 return nullptr;
1004 if (AP2.sgt(AP1))
1005 return nullptr;
1006 }
1007
1008 if (!AP1)
1009 // 'A' must be large enough to shift out the highest set bit.
1010 return getICmp(I.ICMP_UGT, A,
1011 ConstantInt::get(A->getType(), AP2.logBase2()));
1012
1013 if (AP1 == AP2)
1014 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1015
1016 int Shift;
1017 if (IsAShr && AP1.isNegative())
1018 Shift = AP1.countl_one() - AP2.countl_one();
1019 else
1020 Shift = AP1.countl_zero() - AP2.countl_zero();
1021
1022 if (Shift > 0) {
1023 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1024 // There are multiple solutions if we are comparing against -1 and the LHS
1025 // of the ashr is not a power of two.
1026 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1027 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1028 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1029 } else if (AP1 == AP2.lshr(Shift)) {
1030 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1031 }
1032 }
1033
1034 // Shifting const2 will never be equal to const1.
1035 // FIXME: This should always be handled by InstSimplify?
1036 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1037 return replaceInstUsesWith(I, TorF);
1038}
1039
1040/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1041/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1043 const APInt &AP1,
1044 const APInt &AP2) {
1045 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1046
1047 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1048 if (I.getPredicate() == I.ICMP_NE)
1049 Pred = CmpInst::getInversePredicate(Pred);
1050 return new ICmpInst(Pred, LHS, RHS);
1051 };
1052
1053 // Don't bother doing any work for cases which InstSimplify handles.
1054 if (AP2.isZero())
1055 return nullptr;
1056
1057 unsigned AP2TrailingZeros = AP2.countr_zero();
1058
1059 if (!AP1 && AP2TrailingZeros != 0)
1060 return getICmp(
1061 I.ICMP_UGE, A,
1062 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1063
1064 if (AP1 == AP2)
1065 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1066
1067 // Get the distance between the lowest bits that are set.
1068 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1069
1070 if (Shift > 0 && AP2.shl(Shift) == AP1)
1071 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1072
1073 // Shifting const2 will never be equal to const1.
1074 // FIXME: This should always be handled by InstSimplify?
1075 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1076 return replaceInstUsesWith(I, TorF);
1077}
1078
1079/// The caller has matched a pattern of the form:
1080/// I = icmp ugt (add (add A, B), CI2), CI1
1081/// If this is of the form:
1082/// sum = a + b
1083/// if (sum+128 >u 255)
1084/// Then replace it with llvm.sadd.with.overflow.i8.
1085///
1087 ConstantInt *CI2, ConstantInt *CI1,
1088 InstCombinerImpl &IC) {
1089 // The transformation we're trying to do here is to transform this into an
1090 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1091 // with a narrower add, and discard the add-with-constant that is part of the
1092 // range check (if we can't eliminate it, this isn't profitable).
1093
1094 // In order to eliminate the add-with-constant, the compare can be its only
1095 // use.
1096 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1097 if (!AddWithCst->hasOneUse())
1098 return nullptr;
1099
1100 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1101 if (!CI2->getValue().isPowerOf2())
1102 return nullptr;
1103 unsigned NewWidth = CI2->getValue().countr_zero();
1104 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1105 return nullptr;
1106
1107 // The width of the new add formed is 1 more than the bias.
1108 ++NewWidth;
1109
1110 // Check to see that CI1 is an all-ones value with NewWidth bits.
1111 if (CI1->getBitWidth() == NewWidth ||
1112 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1113 return nullptr;
1114
1115 // This is only really a signed overflow check if the inputs have been
1116 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1117 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1118 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1119 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1120 return nullptr;
1121
1122 // In order to replace the original add with a narrower
1123 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1124 // and truncates that discard the high bits of the add. Verify that this is
1125 // the case.
1126 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1127 for (User *U : OrigAdd->users()) {
1128 if (U == AddWithCst)
1129 continue;
1130
1131 // Only accept truncates for now. We would really like a nice recursive
1132 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1133 // chain to see which bits of a value are actually demanded. If the
1134 // original add had another add which was then immediately truncated, we
1135 // could still do the transformation.
1137 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1138 return nullptr;
1139 }
1140
1141 // If the pattern matches, truncate the inputs to the narrower type and
1142 // use the sadd_with_overflow intrinsic to efficiently compute both the
1143 // result and the overflow bit.
1144 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1146 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1147
1148 InstCombiner::BuilderTy &Builder = IC.Builder;
1149
1150 // Put the new code above the original add, in case there are any uses of the
1151 // add between the add and the compare.
1152 Builder.SetInsertPoint(OrigAdd);
1153
1154 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1155 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1156 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1157 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1158 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1159
1160 // The inner add was the result of the narrow add, zero extended to the
1161 // wider type. Replace it with the result computed by the intrinsic.
1162 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1163 IC.eraseInstFromFunction(*OrigAdd);
1164
1165 // The original icmp gets replaced with the overflow value.
1166 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1167}
1168
1169/// If we have:
1170/// icmp eq/ne (urem/srem %x, %y), 0
1171/// iff %y is a power-of-two, we can replace this with a bit test:
1172/// icmp eq/ne (and %x, (add %y, -1)), 0
1174 // This fold is only valid for equality predicates.
1175 if (!I.isEquality())
1176 return nullptr;
1177 CmpPredicate Pred;
1178 Value *X, *Y, *Zero;
1179 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1180 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1181 return nullptr;
1182 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1183 return nullptr;
1184 // This may increase instruction count, we don't enforce that Y is a constant.
1185 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1186 Value *Masked = Builder.CreateAnd(X, Mask);
1187 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1188}
1189
1190/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1191/// by one-less-than-bitwidth into a sign test on the original value.
1193 Instruction *Val;
1194 CmpPredicate Pred;
1195 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1196 return nullptr;
1197
1198 Value *X;
1199 Type *XTy;
1200
1201 Constant *C;
1202 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1203 XTy = X->getType();
1204 unsigned XBitWidth = XTy->getScalarSizeInBits();
1206 APInt(XBitWidth, XBitWidth - 1))))
1207 return nullptr;
1208 } else if (isa<BinaryOperator>(Val) &&
1210 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1211 /*AnalyzeForSignBitExtraction=*/true))) {
1212 XTy = X->getType();
1213 } else
1214 return nullptr;
1215
1216 return ICmpInst::Create(Instruction::ICmp,
1220}
1221
1222// Handle icmp pred X, 0
1224 CmpInst::Predicate Pred = Cmp.getPredicate();
1225 if (!match(Cmp.getOperand(1), m_Zero()))
1226 return nullptr;
1227
1228 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1229 if (Pred == ICmpInst::ICMP_SGT) {
1230 Value *A, *B;
1231 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1232 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1233 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1234 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1235 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1236 }
1237 }
1238
1240 return New;
1241
1242 // Given:
1243 // icmp eq/ne (urem %x, %y), 0
1244 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1245 // icmp eq/ne %x, 0
1246 Value *X, *Y;
1247 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1248 ICmpInst::isEquality(Pred)) {
1249 KnownBits XKnown = computeKnownBits(X, &Cmp);
1250 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1251 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1252 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1253 }
1254
1255 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1256 // odd/non-zero/there is no overflow.
1257 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1258 ICmpInst::isEquality(Pred)) {
1259
1260 KnownBits XKnown = computeKnownBits(X, &Cmp);
1261 // if X % 2 != 0
1262 // (icmp eq/ne Y)
1263 if (XKnown.countMaxTrailingZeros() == 0)
1264 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1265
1266 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1267 // if Y % 2 != 0
1268 // (icmp eq/ne X)
1269 if (YKnown.countMaxTrailingZeros() == 0)
1270 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1271
1272 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1273 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1274 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1275 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1276 // but to avoid unnecessary work, first just if this is an obvious case.
1277
1278 // if X non-zero and NoOverflow(X * Y)
1279 // (icmp eq/ne Y)
1280 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1281 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1282
1283 // if Y non-zero and NoOverflow(X * Y)
1284 // (icmp eq/ne X)
1285 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1286 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1287 }
1288 // Note, we are skipping cases:
1289 // if Y % 2 != 0 AND X % 2 != 0
1290 // (false/true)
1291 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1292 // (false/true)
1293 // Those can be simplified later as we would have already replaced the (icmp
1294 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1295 // will fold to a constant elsewhere.
1296 }
1297
1298 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1299 // where f(X) == 0 if and only if X == 0
1300 if (ICmpInst::isEquality(Pred))
1301 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1302 return new ICmpInst(Pred, Stripped,
1303 Constant::getNullValue(Stripped->getType()));
1304
1305 return nullptr;
1306}
1307
1308/// Fold icmp eq (num + mask) & ~mask, num
1309/// to
1310/// icmp eq (and num, mask), 0
1311/// Where mask is a low bit mask.
1313 Value *Num;
1314 CmpPredicate Pred;
1315 const APInt *Mask, *Neg;
1316
1317 if (!match(&Cmp,
1318 m_c_ICmp(Pred, m_Value(Num),
1320 m_LowBitMask(Mask))),
1321 m_APInt(Neg))))))
1322 return nullptr;
1323
1324 if (*Neg != ~*Mask)
1325 return nullptr;
1326
1327 if (!ICmpInst::isEquality(Pred))
1328 return nullptr;
1329
1330 // Create new icmp eq (num & mask), 0
1331 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1332 auto *Zero = Constant::getNullValue(Num->getType());
1333
1334 return new ICmpInst(Pred, NewAnd, Zero);
1335}
1336
1337/// Fold icmp Pred X, C.
1338/// TODO: This code structure does not make sense. The saturating add fold
1339/// should be moved to some other helper and extended as noted below (it is also
1340/// possible that code has been made unnecessary - do we canonicalize IR to
1341/// overflow/saturating intrinsics or not?).
1343 // Match the following pattern, which is a common idiom when writing
1344 // overflow-safe integer arithmetic functions. The source performs an addition
1345 // in wider type and explicitly checks for overflow using comparisons against
1346 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1347 //
1348 // TODO: This could probably be generalized to handle other overflow-safe
1349 // operations if we worked out the formulas to compute the appropriate magic
1350 // constants.
1351 //
1352 // sum = a + b
1353 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1354 CmpInst::Predicate Pred = Cmp.getPredicate();
1355 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1356 Value *A, *B;
1357 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1358 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1359 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1360 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1361 return Res;
1362
1363 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1365 if (!C)
1366 return nullptr;
1367
1368 if (auto *Phi = dyn_cast<PHINode>(Op0))
1369 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1371 for (Value *V : Phi->incoming_values()) {
1372 Constant *Res =
1374 if (!Res)
1375 return nullptr;
1376 Ops.push_back(Res);
1377 }
1378 Builder.SetInsertPoint(Phi);
1379 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1380 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1381 NewPhi->addIncoming(V, Pred);
1382 return replaceInstUsesWith(Cmp, NewPhi);
1383 }
1384
1386 return R;
1387
1388 return nullptr;
1389}
1390
1391/// Canonicalize icmp instructions based on dominating conditions.
1393 // We already checked simple implication in InstSimplify, only handle complex
1394 // cases here.
1395 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1396 const APInt *C;
1397 if (!match(Y, m_APInt(C)))
1398 return nullptr;
1399
1400 CmpInst::Predicate Pred = Cmp.getPredicate();
1402
1403 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1404 const APInt *DomC) -> Instruction * {
1405 // We have 2 compares of a variable with constants. Calculate the constant
1406 // ranges of those compares to see if we can transform the 2nd compare:
1407 // DomBB:
1408 // DomCond = icmp DomPred X, DomC
1409 // br DomCond, CmpBB, FalseBB
1410 // CmpBB:
1411 // Cmp = icmp Pred X, C
1412 ConstantRange DominatingCR =
1413 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1414 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1415 ConstantRange Difference = DominatingCR.difference(CR);
1416 if (Intersection.isEmptySet())
1417 return replaceInstUsesWith(Cmp, Builder.getFalse());
1418 if (Difference.isEmptySet())
1419 return replaceInstUsesWith(Cmp, Builder.getTrue());
1420
1421 // Canonicalizing a sign bit comparison that gets used in a branch,
1422 // pessimizes codegen by generating branch on zero instruction instead
1423 // of a test and branch. So we avoid canonicalizing in such situations
1424 // because test and branch instruction has better branch displacement
1425 // than compare and branch instruction.
1426 bool UnusedBit;
1427 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1428 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1429 return nullptr;
1430
1431 // Avoid an infinite loop with min/max canonicalization.
1432 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1433 if (Cmp.hasOneUse() &&
1434 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1435 return nullptr;
1436
1437 if (const APInt *EqC = Intersection.getSingleElement())
1438 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1439 if (const APInt *NeC = Difference.getSingleElement())
1440 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1441 return nullptr;
1442 };
1443
1444 for (CondBrInst *BI : DC.conditionsFor(X)) {
1445 CmpPredicate DomPred;
1446 const APInt *DomC;
1447 if (!match(BI->getCondition(),
1448 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1449 continue;
1450
1451 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1452 if (DT.dominates(Edge0, Cmp.getParent())) {
1453 if (auto *V = handleDomCond(DomPred, DomC))
1454 return V;
1455 } else {
1456 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1457 if (DT.dominates(Edge1, Cmp.getParent()))
1458 if (auto *V =
1459 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1460 return V;
1461 }
1462 }
1463
1464 return nullptr;
1465}
1466
1467/// Fold icmp (trunc X), C.
1469 TruncInst *Trunc,
1470 const APInt &C) {
1471 ICmpInst::Predicate Pred = Cmp.getPredicate();
1472 Value *X = Trunc->getOperand(0);
1473 Type *SrcTy = X->getType();
1474 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1475 SrcBits = SrcTy->getScalarSizeInBits();
1476
1477 // Match (icmp pred (trunc nuw/nsw X), C)
1478 // Which we can convert to (icmp pred X, (sext/zext C))
1479 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1480 if (Trunc->hasNoSignedWrap())
1481 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1482 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1483 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1484 }
1485
1486 if (C.isOne() && C.getBitWidth() > 1) {
1487 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1488 Value *V = nullptr;
1489 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1490 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1491 ConstantInt::get(V->getType(), 1));
1492 }
1493
1494 // TODO: Handle non-equality predicates.
1495 Value *Y;
1496 const APInt *Pow2;
1497 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1498 DstBits > Pow2->logBase2()) {
1499 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1500 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1501 // iff N > log2(Pow2)
1502 if (C.isZero()) {
1503 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1504 return new ICmpInst(NewPred, Y,
1505 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1506 }
1507 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1508 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1509 if (C.isPowerOf2())
1510 return new ICmpInst(
1511 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1512 }
1513
1514 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1515 // Canonicalize to a mask and wider compare if the wide type is suitable:
1516 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1517 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1518 Constant *Mask =
1519 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1520 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1521 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1522 return new ICmpInst(Pred, And, WideC);
1523 }
1524
1525 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1526 // of the high bits truncated out of x are known.
1528
1529 // If all the high bits are known, we can do this xform.
1530 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1531 // Pull in the high bits from known-ones set.
1532 APInt NewRHS = C.zext(SrcBits);
1533 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1534 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1535 }
1536 }
1537
1538 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1539 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1540 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1541 Value *ShOp;
1542 uint64_t ShAmt;
1543 bool TrueIfSigned;
1544 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1545 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1546 DstBits == SrcBits - ShAmt) {
1547 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1549 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1551 }
1552
1553 return nullptr;
1554}
1555
1556/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1557/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1560 const SimplifyQuery &Q) {
1561 Value *X, *Y;
1562 CmpPredicate Pred;
1563 bool YIsSExt = false;
1564 // Try to match icmp (trunc X), (trunc Y)
1565 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1566 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1567 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1568 if (Cmp.isSigned()) {
1569 // For signed comparisons, both truncs must be nsw.
1570 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1571 return nullptr;
1572 } else {
1573 // For unsigned and equality comparisons, either both must be nuw or
1574 // both must be nsw, we don't care which.
1575 if (!NoWrapFlags)
1576 return nullptr;
1577 }
1578
1579 if (X->getType() != Y->getType() &&
1580 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1581 return nullptr;
1582 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1583 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1584 std::swap(X, Y);
1585 Pred = Cmp.getSwappedPredicate(Pred);
1586 }
1587 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1588 }
1589 // Try to match icmp (trunc nuw X), (zext Y)
1590 else if (!Cmp.isSigned() &&
1591 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1592 m_OneUse(m_ZExt(m_Value(Y)))))) {
1593 // Can fold trunc nuw + zext for unsigned and equality predicates.
1594 }
1595 // Try to match icmp (trunc nsw X), (sext Y)
1596 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1598 // Can fold trunc nsw + zext/sext for all predicates.
1599 YIsSExt =
1600 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1601 } else
1602 return nullptr;
1603
1604 Type *TruncTy = Cmp.getOperand(0)->getType();
1605 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1606
1607 // If this transform will end up changing from desirable types -> undesirable
1608 // types skip it.
1609 if (isDesirableIntType(TruncBits) &&
1610 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1611 return nullptr;
1612
1613 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1614 return new ICmpInst(Pred, X, NewY);
1615}
1616
1617/// Fold icmp (xor X, Y), C.
1620 const APInt &C) {
1621 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1622 return I;
1623
1624 Value *X = Xor->getOperand(0);
1625 Value *Y = Xor->getOperand(1);
1626 const APInt *XorC;
1627 if (!match(Y, m_APInt(XorC)))
1628 return nullptr;
1629
1630 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1631 // fold the xor.
1632 ICmpInst::Predicate Pred = Cmp.getPredicate();
1633 bool TrueIfSigned = false;
1634 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1635
1636 // If the sign bit of the XorCst is not set, there is no change to
1637 // the operation, just stop using the Xor.
1638 if (!XorC->isNegative())
1639 return replaceOperand(Cmp, 0, X);
1640
1641 // Emit the opposite comparison.
1642 if (TrueIfSigned)
1643 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1644 ConstantInt::getAllOnesValue(X->getType()));
1645 else
1646 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1647 ConstantInt::getNullValue(X->getType()));
1648 }
1649
1650 if (Xor->hasOneUse()) {
1651 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1652 if (!Cmp.isEquality() && XorC->isSignMask()) {
1653 Pred = Cmp.getFlippedSignednessPredicate();
1654 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1655 }
1656
1657 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1658 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1659 Pred = Cmp.getFlippedSignednessPredicate();
1660 Pred = Cmp.getSwappedPredicate(Pred);
1661 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1662 }
1663 }
1664
1665 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1666 if (Pred == ICmpInst::ICMP_UGT) {
1667 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1668 if (*XorC == ~C && (C + 1).isPowerOf2())
1669 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1670 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1671 if (*XorC == C && (C + 1).isPowerOf2())
1672 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1673 }
1674 if (Pred == ICmpInst::ICMP_ULT) {
1675 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1676 if (*XorC == -C && C.isPowerOf2())
1677 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1678 ConstantInt::get(X->getType(), ~C));
1679 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1680 if (*XorC == C && (-C).isPowerOf2())
1681 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1682 ConstantInt::get(X->getType(), ~C));
1683 }
1684 return nullptr;
1685}
1686
1687/// For power-of-2 C:
1688/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1689/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1692 const APInt &C) {
1693 CmpInst::Predicate Pred = Cmp.getPredicate();
1694 APInt PowerOf2;
1695 if (Pred == ICmpInst::ICMP_ULT)
1696 PowerOf2 = C;
1697 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1698 PowerOf2 = C + 1;
1699 else
1700 return nullptr;
1701 if (!PowerOf2.isPowerOf2())
1702 return nullptr;
1703 Value *X;
1704 const APInt *ShiftC;
1706 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1707 return nullptr;
1708 uint64_t Shift = ShiftC->getLimitedValue();
1709 Type *XType = X->getType();
1710 if (Shift == 0 || PowerOf2.isMinSignedValue())
1711 return nullptr;
1712 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1713 APInt Bound =
1714 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1715 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1716}
1717
1718/// Fold icmp (and (sh X, Y), C2), C1.
1721 const APInt &C1,
1722 const APInt &C2) {
1723 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1724 if (!Shift || !Shift->isShift())
1725 return nullptr;
1726
1727 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1728 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1729 // code produced by the clang front-end, for bitfield access.
1730 // This seemingly simple opportunity to fold away a shift turns out to be
1731 // rather complicated. See PR17827 for details.
1732 unsigned ShiftOpcode = Shift->getOpcode();
1733 bool IsShl = ShiftOpcode == Instruction::Shl;
1734 const APInt *C3;
1735 if (match(Shift->getOperand(1), m_APInt(C3))) {
1736 APInt NewAndCst, NewCmpCst;
1737 bool AnyCmpCstBitsShiftedOut;
1738 if (ShiftOpcode == Instruction::Shl) {
1739 // For a left shift, we can fold if the comparison is not signed. We can
1740 // also fold a signed comparison if the mask value and comparison value
1741 // are not negative. These constraints may not be obvious, but we can
1742 // prove that they are correct using an SMT solver.
1743 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1744 return nullptr;
1745
1746 NewCmpCst = C1.lshr(*C3);
1747 NewAndCst = C2.lshr(*C3);
1748 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1749 } else if (ShiftOpcode == Instruction::LShr) {
1750 // For a logical right shift, we can fold if the comparison is not signed.
1751 // We can also fold a signed comparison if the shifted mask value and the
1752 // shifted comparison value are not negative. These constraints may not be
1753 // obvious, but we can prove that they are correct using an SMT solver.
1754 NewCmpCst = C1.shl(*C3);
1755 NewAndCst = C2.shl(*C3);
1756 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1757 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1758 return nullptr;
1759 } else {
1760 // For an arithmetic shift, check that both constants don't use (in a
1761 // signed sense) the top bits being shifted out.
1762 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1763 NewCmpCst = C1.shl(*C3);
1764 NewAndCst = C2.shl(*C3);
1765 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1766 if (NewAndCst.ashr(*C3) != C2)
1767 return nullptr;
1768 }
1769
1770 if (AnyCmpCstBitsShiftedOut) {
1771 // If we shifted bits out, the fold is not going to work out. As a
1772 // special case, check to see if this means that the result is always
1773 // true or false now.
1774 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1775 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1776 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1777 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1778 } else {
1779 Value *NewAnd = Builder.CreateAnd(
1780 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1781 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1782 ConstantInt::get(And->getType(), NewCmpCst));
1783 }
1784 }
1785
1786 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1787 // preferable because it allows the C2 << Y expression to be hoisted out of a
1788 // loop if Y is invariant and X is not.
1789 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1790 !Shift->isArithmeticShift() &&
1791 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1792 // Compute C2 << Y.
1793 Value *NewShift =
1794 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1795 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1796
1797 // Compute X & (C2 << Y).
1798 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1799 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1800 }
1801
1802 return nullptr;
1803}
1804
1805/// Fold icmp (and X, C2), C1.
1808 const APInt &C1) {
1809 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1810
1811 // icmp ne (and X, 1), 0 --> trunc X to i1
1812 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1813 return new TruncInst(And->getOperand(0), Cmp.getType());
1814
1815 const APInt *C2;
1816 Value *X;
1817 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1818 return nullptr;
1819
1820 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1821 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1822 C2->isNegatedPowerOf2())
1823 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1824 ConstantInt::get(X->getType(), ~*C2));
1825 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1826 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1827 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1828 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1829 ConstantInt::get(X->getType(), -*C2));
1830
1831 // Don't perform the following transforms if the AND has multiple uses
1832 if (!And->hasOneUse())
1833 return nullptr;
1834
1835 if (Cmp.isEquality() && C1.isZero()) {
1836 // Restrict this fold to single-use 'and' (PR10267).
1837 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1838 if (C2->isSignMask()) {
1839 Constant *Zero = Constant::getNullValue(X->getType());
1840 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1841 return new ICmpInst(NewPred, X, Zero);
1842 }
1843
1844 APInt NewC2 = *C2;
1845 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1846 // Set high zeros of C2 to allow matching negated power-of-2.
1847 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1848 Know.countMinLeadingZeros());
1849
1850 // Restrict this fold only for single-use 'and' (PR10267).
1851 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1852 if (NewC2.isNegatedPowerOf2()) {
1853 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1854 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1855 return new ICmpInst(NewPred, X, NegBOC);
1856 }
1857 }
1858
1859 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1860 // the input width without changing the value produced, eliminate the cast:
1861 //
1862 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1863 //
1864 // We can do this transformation if the constants do not have their sign bits
1865 // set or if it is an equality comparison. Extending a relational comparison
1866 // when we're checking the sign bit would not work.
1867 Value *W;
1868 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1869 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1870 // TODO: Is this a good transform for vectors? Wider types may reduce
1871 // throughput. Should this transform be limited (even for scalars) by using
1872 // shouldChangeType()?
1873 if (!Cmp.getType()->isVectorTy()) {
1874 Type *WideType = W->getType();
1875 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1876 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1877 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1878 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1879 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1880 }
1881 }
1882
1883 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1884 return I;
1885
1886 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1887 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1888 //
1889 // iff pred isn't signed
1890 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1891 match(And->getOperand(1), m_One())) {
1892 Constant *One = cast<Constant>(And->getOperand(1));
1893 Value *Or = And->getOperand(0);
1894 Value *A, *B, *LShr;
1895 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1896 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1897 unsigned UsesRemoved = 0;
1898 if (And->hasOneUse())
1899 ++UsesRemoved;
1900 if (Or->hasOneUse())
1901 ++UsesRemoved;
1902 if (LShr->hasOneUse())
1903 ++UsesRemoved;
1904
1905 // Compute A & ((1 << B) | 1)
1906 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1907 if (UsesRemoved >= RequireUsesRemoved) {
1908 Value *NewOr =
1909 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1910 /*HasNUW=*/true),
1911 One, Or->getName());
1912 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1913 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1914 }
1915 }
1916 }
1917
1918 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1919 // llvm.is.fpclass(X, fcInf|fcNan)
1920 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1921 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1922 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1923 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1924 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1925 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1926 Value *V;
1927 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1928 Attribute::NoImplicitFloat) &&
1929 Cmp.isEquality() &&
1931 Type *FPType = V->getType()->getScalarType();
1932 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1933 APInt ExponentMask =
1934 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1935 if (*C2 == ExponentMask) {
1936 unsigned Mask = C1.isZero()
1939 if (isICMP_NE)
1940 Mask = ~Mask & fcAllFlags;
1941 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1942 }
1943 }
1944 }
1945
1946 return nullptr;
1947}
1948
1949/// Fold icmp (and X, Y), C.
1952 const APInt &C) {
1953 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1954 return I;
1955
1956 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1957 bool TrueIfNeg;
1958 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1959 // ((X - 1) & ~X) < 0 --> X == 0
1960 // ((X - 1) & ~X) >= 0 --> X != 0
1961 Value *X;
1962 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1963 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1964 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1965 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1966 }
1967 // (X & -X) < 0 --> X == MinSignedC
1968 // (X & -X) > -1 --> X != MinSignedC
1969 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1970 Constant *MinSignedC = ConstantInt::get(
1971 X->getType(),
1972 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1973 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1974 return new ICmpInst(NewPred, X, MinSignedC);
1975 }
1976 }
1977
1978 // TODO: These all require that Y is constant too, so refactor with the above.
1979
1980 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1981 Value *X = And->getOperand(0);
1982 Value *Y = And->getOperand(1);
1983 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1984 if (auto *LI = dyn_cast<LoadInst>(X))
1985 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1986 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1987 return Res;
1988
1989 if (!Cmp.isEquality())
1990 return nullptr;
1991
1992 // X & -C == -C -> X > u ~C
1993 // X & -C != -C -> X <= u ~C
1994 // iff C is a power of 2
1995 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1996 auto NewPred =
1998 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1999 }
2000
2001 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2002 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2003 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2004 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2006 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2007 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2008 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2009 Value *And = Builder.CreateAnd(TruncY, X);
2011 }
2012 return BinaryOperator::CreateAnd(TruncY, X);
2013 }
2014
2015 // (icmp eq/ne (and (shl -1, X), Y), 0)
2016 // -> (icmp eq/ne (lshr Y, X), 0)
2017 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2018 // highly unlikely the non-zero case will ever show up in code.
2019 if (C.isZero() &&
2021 m_Value(Y))))) {
2022 Value *LShr = Builder.CreateLShr(Y, X);
2023 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2024 }
2025
2026 // (icmp eq/ne (and (add A, Addend), Msk), C)
2027 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2028 {
2029 Value *A;
2030 const APInt *Addend, *Msk;
2032 m_LowBitMask(Msk)))) &&
2033 C.ule(*Msk)) {
2034 APInt NewComperand = (C - *Addend) & *Msk;
2035 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2036 return new ICmpInst(Pred, MaskA,
2037 ConstantInt::get(MaskA->getType(), NewComperand));
2038 }
2039 }
2040
2041 return nullptr;
2042}
2043
2044/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2046 InstCombiner::BuilderTy &Builder) {
2047 // Are we using xors or subs to bitwise check for a pair or pairs of
2048 // (in)equalities? Convert to a shorter form that has more potential to be
2049 // folded even further.
2050 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2051 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2052 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2053 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2054 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2055 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2057 SmallVector<Value *, 16> WorkList(1, Or);
2058
2059 while (!WorkList.empty()) {
2060 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2061 Value *Lhs, *Rhs;
2062
2063 if (match(OrOperatorArgument,
2064 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2065 CmpValues.emplace_back(Lhs, Rhs);
2066 return;
2067 }
2068
2069 if (match(OrOperatorArgument,
2070 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2071 CmpValues.emplace_back(Lhs, Rhs);
2072 return;
2073 }
2074
2075 WorkList.push_back(OrOperatorArgument);
2076 };
2077
2078 Value *CurrentValue = WorkList.pop_back_val();
2079 Value *OrOperatorLhs, *OrOperatorRhs;
2080
2081 if (!match(CurrentValue,
2082 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2083 return nullptr;
2084 }
2085
2086 MatchOrOperatorArgument(OrOperatorRhs);
2087 MatchOrOperatorArgument(OrOperatorLhs);
2088 }
2089
2090 ICmpInst::Predicate Pred = Cmp.getPredicate();
2091 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2092 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2093 CmpValues.rbegin()->second);
2094
2095 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2096 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2097 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2098 }
2099
2100 return LhsCmp;
2101}
2102
2103/// Fold icmp (or X, Y), C.
2106 const APInt &C) {
2107 ICmpInst::Predicate Pred = Cmp.getPredicate();
2108 if (C.isOne()) {
2109 // icmp slt signum(V) 1 --> icmp slt V, 1
2110 Value *V = nullptr;
2111 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2112 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2113 ConstantInt::get(V->getType(), 1));
2114 }
2115
2116 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2117
2118 // (icmp eq/ne (or disjoint x, C0), C1)
2119 // -> (icmp eq/ne x, C0^C1)
2120 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2121 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2122 Value *NewC =
2123 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2124 return new ICmpInst(Pred, OrOp0, NewC);
2125 }
2126
2127 const APInt *MaskC;
2128 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2129 if (*MaskC == C && (C + 1).isPowerOf2()) {
2130 // X | C == C --> X <=u C
2131 // X | C != C --> X >u C
2132 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2134 return new ICmpInst(Pred, OrOp0, OrOp1);
2135 }
2136
2137 // More general: canonicalize 'equality with set bits mask' to
2138 // 'equality with clear bits mask'.
2139 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2140 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2141 if (Or->hasOneUse()) {
2142 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2143 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2144 return new ICmpInst(Pred, And, NewC);
2145 }
2146 }
2147
2148 // (X | (X-1)) s< 0 --> X s< 1
2149 // (X | (X-1)) s> -1 --> X s> 0
2150 Value *X;
2151 bool TrueIfSigned;
2152 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2154 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2155 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2156 return new ICmpInst(NewPred, X, NewC);
2157 }
2158
2159 const APInt *OrC;
2160 // icmp(X | OrC, C) --> icmp(X, 0)
2161 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2162 switch (Pred) {
2163 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2164 case ICmpInst::ICMP_SLT:
2165 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2166 case ICmpInst::ICMP_SGE:
2167 if (OrC->sge(C))
2168 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2169 break;
2170 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2171 case ICmpInst::ICMP_SLE:
2172 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2173 case ICmpInst::ICMP_SGT:
2174 if (OrC->sgt(C))
2176 ConstantInt::getNullValue(X->getType()));
2177 break;
2178 default:
2179 break;
2180 }
2181 }
2182
2183 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2184 return nullptr;
2185
2186 Value *P, *Q;
2188 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2189 // -> and (icmp eq P, null), (icmp eq Q, null).
2190 Value *CmpP =
2191 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2192 Value *CmpQ =
2193 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2194 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2195 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2196 }
2197
2198 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2199 return replaceInstUsesWith(Cmp, V);
2200
2201 return nullptr;
2202}
2203
2204/// Fold icmp (mul X, Y), C.
2207 const APInt &C) {
2208 ICmpInst::Predicate Pred = Cmp.getPredicate();
2209 Type *MulTy = Mul->getType();
2210 Value *X = Mul->getOperand(0);
2211
2212 // If comparing a square with a constant, try simplifying to comparing square
2213 // roots.
2214 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2215 APInt R = C.sqrtFloor();
2216 bool IsSqr = C == R * R;
2217
2218 // X * X eq/ne C
2219 if (Cmp.isEquality() &&
2220 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2221
2222 // If constant is not a square, eq/ne is false/true respectively
2223 if (!IsSqr)
2224 return replaceInstUsesWith(
2225 Cmp,
2226 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2227
2228 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2229 }
2230
2231 // If the multiply does not wrap
2232 // X * X pred C --> X pred R
2233 if (Mul->hasNoUnsignedWrap()) {
2234
2235 if (IsSqr)
2236 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2237
2238 // If C is not a square, we use floor/ceil of sqrt(C).
2239 //
2240 // If LT or LE, we need R to be an overestimate of sqrt(C),
2241 // then use the strict predicate (LT->LT, LE->LT).
2242 //
2243 // If GT or GE, we need R to be an underestimate of sqrt(C),
2244 // then use the strict predicate (GT->GT, GE->GT).
2245 //
2246 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2247 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2248 ++R;
2249
2250 return new ICmpInst(Cmp.getStrictPredicate(), X,
2251 ConstantInt::get(MulTy, R));
2252 }
2253 }
2254
2255 const APInt *MulC;
2256 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2257 return nullptr;
2258
2259 // If this is a test of the sign bit and the multiply is sign-preserving with
2260 // a constant operand, use the multiply LHS operand instead:
2261 // (X * +MulC) < 0 --> X < 0
2262 // (X * -MulC) < 0 --> X > 0
2263 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2264 if (MulC->isNegative())
2265 Pred = ICmpInst::getSwappedPredicate(Pred);
2266 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2267 }
2268
2269 if (MulC->isZero())
2270 return nullptr;
2271
2272 // If the multiply does not wrap or the constant is odd, try to divide the
2273 // compare constant by the multiplication factor.
2274 if (Cmp.isEquality()) {
2275 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2276 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2277 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2278 return new ICmpInst(Pred, X, NewC);
2279 }
2280
2281 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2282 // correct to transform if MulC * N == C including overflow. I.e with i8
2283 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2284 // miss that case.
2285 if (C.urem(*MulC).isZero()) {
2286 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2287 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2288 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2289 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2290 return new ICmpInst(Pred, X, NewC);
2291 }
2292 }
2293 }
2294
2295 // With a matching no-overflow guarantee, fold the constants:
2296 // (X * MulC) < C --> X < (C / MulC)
2297 // (X * MulC) > C --> X > (C / MulC)
2298 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2299 Constant *NewC = nullptr;
2300 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2301 // MININT / -1 --> overflow.
2302 if (C.isMinSignedValue() && MulC->isAllOnes())
2303 return nullptr;
2304 if (MulC->isNegative())
2305 Pred = ICmpInst::getSwappedPredicate(Pred);
2306
2307 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2308 NewC = ConstantInt::get(
2310 } else {
2311 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2312 "Unexpected predicate");
2313 NewC = ConstantInt::get(
2315 }
2316 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2317 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2318 NewC = ConstantInt::get(
2320 } else {
2321 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2322 "Unexpected predicate");
2323 NewC = ConstantInt::get(
2325 }
2326 }
2327
2328 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2329}
2330
2331/// Fold icmp (shl nuw C2, Y), C.
2333 const APInt &C) {
2334 Value *Y;
2335 const APInt *C2;
2336 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2337 return nullptr;
2338
2339 Type *ShiftType = Shl->getType();
2340 unsigned TypeBits = C.getBitWidth();
2341 ICmpInst::Predicate Pred = Cmp.getPredicate();
2342 if (Cmp.isUnsigned()) {
2343 if (C2->isZero() || C2->ugt(C))
2344 return nullptr;
2345 APInt Div, Rem;
2346 APInt::udivrem(C, *C2, Div, Rem);
2347 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2348
2349 // (1 << Y) pred C -> Y pred Log2(C)
2350 if (!CIsPowerOf2) {
2351 // (1 << Y) < 30 -> Y <= 4
2352 // (1 << Y) <= 30 -> Y <= 4
2353 // (1 << Y) >= 30 -> Y > 4
2354 // (1 << Y) > 30 -> Y > 4
2355 if (Pred == ICmpInst::ICMP_ULT)
2356 Pred = ICmpInst::ICMP_ULE;
2357 else if (Pred == ICmpInst::ICMP_UGE)
2358 Pred = ICmpInst::ICMP_UGT;
2359 }
2360
2361 unsigned CLog2 = Div.logBase2();
2362 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2363 } else if (Cmp.isSigned() && C2->isOne()) {
2364 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2365 // (1 << Y) > 0 -> Y != 31
2366 // (1 << Y) > C -> Y != 31 if C is negative.
2367 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2368 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2369
2370 // (1 << Y) < 0 -> Y == 31
2371 // (1 << Y) < 1 -> Y == 31
2372 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2373 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2374 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2375 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2376 }
2377
2378 return nullptr;
2379}
2380
2381/// Fold icmp (shl X, Y), C.
2383 BinaryOperator *Shl,
2384 const APInt &C) {
2385 const APInt *ShiftVal;
2386 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2387 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2388
2389 ICmpInst::Predicate Pred = Cmp.getPredicate();
2390 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2391 // -> (icmp pred X, Csle0)
2392 //
2393 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2394 // so X's must be what is used.
2395 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2396 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2397
2398 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2399 // -> (icmp eq/ne X, 0)
2400 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2401 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2402 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2403
2404 // (icmp slt (shl nsw X, Y), 0/1)
2405 // -> (icmp slt X, 0/1)
2406 // (icmp sgt (shl nsw X, Y), 0/-1)
2407 // -> (icmp sgt X, 0/-1)
2408 //
2409 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2410 if (Shl->hasNoSignedWrap() &&
2411 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2412 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2413 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2414
2415 const APInt *ShiftAmt;
2416 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2417 return foldICmpShlLHSC(Cmp, Shl, C);
2418
2419 // Check that the shift amount is in range. If not, don't perform undefined
2420 // shifts. When the shift is visited, it will be simplified.
2421 unsigned TypeBits = C.getBitWidth();
2422 if (ShiftAmt->uge(TypeBits))
2423 return nullptr;
2424
2425 Value *X = Shl->getOperand(0);
2426 Type *ShType = Shl->getType();
2427
2428 // NSW guarantees that we are only shifting out sign bits from the high bits,
2429 // so we can ASHR the compare constant without needing a mask and eliminate
2430 // the shift.
2431 if (Shl->hasNoSignedWrap()) {
2432 if (Pred == ICmpInst::ICMP_SGT) {
2433 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2434 APInt ShiftedC = C.ashr(*ShiftAmt);
2435 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2436 }
2437 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2438 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2439 APInt ShiftedC = C.ashr(*ShiftAmt);
2440 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2441 }
2442 if (Pred == ICmpInst::ICMP_SLT) {
2443 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2444 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2445 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2446 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2447 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2448 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2449 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2450 }
2451 }
2452
2453 // NUW guarantees that we are only shifting out zero bits from the high bits,
2454 // so we can LSHR the compare constant without needing a mask and eliminate
2455 // the shift.
2456 if (Shl->hasNoUnsignedWrap()) {
2457 if (Pred == ICmpInst::ICMP_UGT) {
2458 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2459 APInt ShiftedC = C.lshr(*ShiftAmt);
2460 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2461 }
2462 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2463 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2464 APInt ShiftedC = C.lshr(*ShiftAmt);
2465 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2466 }
2467 if (Pred == ICmpInst::ICMP_ULT) {
2468 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2469 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2470 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2471 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2472 assert(C.ugt(0) && "ult 0 should have been eliminated");
2473 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2474 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2475 }
2476 }
2477
2478 if (Cmp.isEquality() && Shl->hasOneUse()) {
2479 // Strength-reduce the shift into an 'and'.
2480 Constant *Mask = ConstantInt::get(
2481 ShType,
2482 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2483 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2484 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2485 return new ICmpInst(Pred, And, LShrC);
2486 }
2487
2488 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2489 bool TrueIfSigned = false;
2490 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2491 // (X << 31) <s 0 --> (X & 1) != 0
2492 Constant *Mask = ConstantInt::get(
2493 ShType,
2494 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2495 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2496 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2497 And, Constant::getNullValue(ShType));
2498 }
2499
2500 // Simplify 'shl' inequality test into 'and' equality test.
2501 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2502 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2503 if ((C + 1).isPowerOf2() &&
2504 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2505 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2506 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2508 And, Constant::getNullValue(ShType));
2509 }
2510 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2511 if (C.isPowerOf2() &&
2512 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2513 Value *And =
2514 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2515 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2517 And, Constant::getNullValue(ShType));
2518 }
2519 }
2520
2521 // Transform (icmp pred iM (shl iM %v, N), C)
2522 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2523 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2524 // This enables us to get rid of the shift in favor of a trunc that may be
2525 // free on the target. It has the additional benefit of comparing to a
2526 // smaller constant that may be more target-friendly.
2527 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2528 if (Shl->hasOneUse() && Amt != 0 &&
2529 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2530 ICmpInst::Predicate CmpPred = Pred;
2531 APInt RHSC = C;
2532
2533 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2534 // Try the flipped strictness predicate.
2535 // e.g.:
2536 // icmp ult i64 (shl X, 32), 8589934593 ->
2537 // icmp ule i64 (shl X, 32), 8589934592 ->
2538 // icmp ule i32 (trunc X, i32), 2 ->
2539 // icmp ult i32 (trunc X, i32), 3
2540 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2541 Pred, ConstantInt::get(ShType->getContext(), C))) {
2542 CmpPred = FlippedStrictness->first;
2543 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2544 }
2545 }
2546
2547 if (RHSC.countr_zero() >= Amt) {
2548 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2549 Constant *NewC =
2550 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2551 return new ICmpInst(CmpPred,
2552 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2553 Shl->hasNoSignedWrap()),
2554 NewC);
2555 }
2556 }
2557
2558 return nullptr;
2559}
2560
2561/// Fold icmp ({al}shr X, Y), C.
2563 BinaryOperator *Shr,
2564 const APInt &C) {
2565 // An exact shr only shifts out zero bits, so:
2566 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2567 Value *X = Shr->getOperand(0);
2568 CmpInst::Predicate Pred = Cmp.getPredicate();
2569 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2570 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2571
2572 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2573 const APInt *ShiftValC;
2574 if (match(X, m_APInt(ShiftValC))) {
2575 if (Cmp.isEquality())
2576 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2577
2578 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2579 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2580 bool TrueIfSigned;
2581 if (!IsAShr && ShiftValC->isNegative() &&
2582 isSignBitCheck(Pred, C, TrueIfSigned))
2583 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2584 Shr->getOperand(1),
2585 ConstantInt::getNullValue(X->getType()));
2586
2587 // If the shifted constant is a power-of-2, test the shift amount directly:
2588 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2589 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2590 if (!IsAShr && ShiftValC->isPowerOf2() &&
2591 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2592 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2593 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2594 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2595
2596 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2597 unsigned ShiftLZ = ShiftValC->countl_zero();
2598 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2599 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2600 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2601 }
2602 }
2603
2604 const APInt *ShiftAmtC;
2605 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2606 return nullptr;
2607
2608 // Check that the shift amount is in range. If not, don't perform undefined
2609 // shifts. When the shift is visited it will be simplified.
2610 unsigned TypeBits = C.getBitWidth();
2611 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2612 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2613 return nullptr;
2614
2615 bool IsExact = Shr->isExact();
2616 Type *ShrTy = Shr->getType();
2617 // TODO: If we could guarantee that InstSimplify would handle all of the
2618 // constant-value-based preconditions in the folds below, then we could assert
2619 // those conditions rather than checking them. This is difficult because of
2620 // undef/poison (PR34838).
2621 if (IsAShr && Shr->hasOneUse()) {
2622 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2623 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2624 // When C - 1 is a power of two and the transform can be legally
2625 // performed, prefer this form so the produced constant is close to a
2626 // power of two.
2627 // icmp slt/ult (ashr exact X, ShAmtC), C
2628 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2629 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2630 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2631 }
2632 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2633 // When ShAmtC can be shifted losslessly:
2634 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2635 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2636 APInt ShiftedC = C.shl(ShAmtVal);
2637 if (ShiftedC.ashr(ShAmtVal) == C)
2638 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2639 }
2640 if (Pred == CmpInst::ICMP_SGT) {
2641 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2642 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2643 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2644 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2645 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2646 }
2647 if (Pred == CmpInst::ICMP_UGT) {
2648 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2649 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2650 // clause accounts for that pattern.
2651 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2652 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2653 (C + 1).shl(ShAmtVal).isMinSignedValue())
2654 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2655 }
2656
2657 // If the compare constant has significant bits above the lowest sign-bit,
2658 // then convert an unsigned cmp to a test of the sign-bit:
2659 // (ashr X, ShiftC) u> C --> X s< 0
2660 // (ashr X, ShiftC) u< C --> X s> -1
2661 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2662 if (Pred == CmpInst::ICMP_UGT) {
2663 return new ICmpInst(CmpInst::ICMP_SLT, X,
2665 }
2666 if (Pred == CmpInst::ICMP_ULT) {
2667 return new ICmpInst(CmpInst::ICMP_SGT, X,
2669 }
2670 }
2671 } else if (!IsAShr) {
2672 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2673 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2674 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2675 APInt ShiftedC = C.shl(ShAmtVal);
2676 if (ShiftedC.lshr(ShAmtVal) == C)
2677 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2678 }
2679 if (Pred == CmpInst::ICMP_UGT) {
2680 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2681 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2682 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2683 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2684 }
2685 }
2686
2687 if (!Cmp.isEquality())
2688 return nullptr;
2689
2690 // Handle equality comparisons of shift-by-constant.
2691
2692 // If the comparison constant changes with the shift, the comparison cannot
2693 // succeed (bits of the comparison constant cannot match the shifted value).
2694 // This should be known by InstSimplify and already be folded to true/false.
2695 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2696 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2697 "Expected icmp+shr simplify did not occur.");
2698
2699 // If the bits shifted out are known zero, compare the unshifted value:
2700 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2701 if (Shr->isExact())
2702 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2703
2704 if (Shr->hasOneUse()) {
2705 // Canonicalize the shift into an 'and':
2706 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2707 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2708 Constant *Mask = ConstantInt::get(ShrTy, Val);
2709 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2710 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2711 }
2712
2713 return nullptr;
2714}
2715
2717 BinaryOperator *SRem,
2718 const APInt &C) {
2719 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2720 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2721 // Canonicalize unsigned predicates to signed:
2722 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2723 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2724 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2725 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2726
2727 const APInt *DivisorC;
2728 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2729 return nullptr;
2730 if (DivisorC->isZero())
2731 return nullptr;
2732
2733 APInt NormalizedC = C;
2734 if (Pred == ICmpInst::ICMP_ULT) {
2735 assert(!NormalizedC.isZero() &&
2736 "ult X, 0 should have been simplified already.");
2737 --NormalizedC;
2738 }
2739 if (C.isNegative())
2740 NormalizedC.flipAllBits();
2741 if (!NormalizedC.uge(DivisorC->abs() - 1))
2742 return nullptr;
2743
2744 Type *Ty = SRem->getType();
2745 if (Pred == ICmpInst::ICMP_UGT)
2746 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2748 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2750 }
2751 // Match an 'is positive' or 'is negative' comparison of remainder by a
2752 // constant power-of-2 value:
2753 // (X % pow2C) sgt/slt 0
2754 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2755 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2756 return nullptr;
2757
2758 // TODO: The one-use check is standard because we do not typically want to
2759 // create longer instruction sequences, but this might be a special-case
2760 // because srem is not good for analysis or codegen.
2761 if (!SRem->hasOneUse())
2762 return nullptr;
2763
2764 const APInt *DivisorC;
2765 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2766 return nullptr;
2767
2768 // For cmp_sgt/cmp_slt only zero valued C is handled.
2769 // For cmp_eq/cmp_ne only positive valued C is handled.
2770 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2771 !C.isZero()) ||
2772 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2773 !C.isStrictlyPositive()))
2774 return nullptr;
2775
2776 // Mask off the sign bit and the modulo bits (low-bits).
2777 Type *Ty = SRem->getType();
2778 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2779 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2780 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2781
2782 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2783 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2784
2785 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2786 // bit is set. Example:
2787 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2788 if (Pred == ICmpInst::ICMP_SGT)
2790
2791 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2792 // bit is set. Example:
2793 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2794 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2795}
2796
2797/// Fold icmp (udiv X, Y), C.
2799 BinaryOperator *UDiv,
2800 const APInt &C) {
2801 ICmpInst::Predicate Pred = Cmp.getPredicate();
2802 Value *X = UDiv->getOperand(0);
2803 Value *Y = UDiv->getOperand(1);
2804 Type *Ty = UDiv->getType();
2805
2806 const APInt *C2;
2807 if (!match(X, m_APInt(C2)))
2808 return nullptr;
2809
2810 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2811
2812 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2813 if (Pred == ICmpInst::ICMP_UGT) {
2814 assert(!C.isMaxValue() &&
2815 "icmp ugt X, UINT_MAX should have been simplified already.");
2816 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2817 ConstantInt::get(Ty, C2->udiv(C + 1)));
2818 }
2819
2820 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2821 if (Pred == ICmpInst::ICMP_ULT) {
2822 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2823 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2824 ConstantInt::get(Ty, C2->udiv(C)));
2825 }
2826
2827 return nullptr;
2828}
2829
2830/// Fold icmp ({su}div X, Y), C.
2832 BinaryOperator *Div,
2833 const APInt &C) {
2834 ICmpInst::Predicate Pred = Cmp.getPredicate();
2835 Value *X = Div->getOperand(0);
2836 Value *Y = Div->getOperand(1);
2837 Type *Ty = Div->getType();
2838 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2839
2840 // If unsigned division and the compare constant is bigger than
2841 // UMAX/2 (negative), there's only one pair of values that satisfies an
2842 // equality check, so eliminate the division:
2843 // (X u/ Y) == C --> (X == C) && (Y == 1)
2844 // (X u/ Y) != C --> (X != C) || (Y != 1)
2845 // Similarly, if signed division and the compare constant is exactly SMIN:
2846 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2847 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2848 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2849 (!DivIsSigned || C.isMinSignedValue())) {
2850 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2851 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2852 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2853 return BinaryOperator::Create(Logic, XBig, YOne);
2854 }
2855
2856 // Fold: icmp pred ([us]div X, C2), C -> range test
2857 // Fold this div into the comparison, producing a range check.
2858 // Determine, based on the divide type, what the range is being
2859 // checked. If there is an overflow on the low or high side, remember
2860 // it, otherwise compute the range [low, hi) bounding the new value.
2861 // See: InsertRangeTest above for the kinds of replacements possible.
2862 const APInt *C2;
2863 if (!match(Y, m_APInt(C2)))
2864 return nullptr;
2865
2866 // FIXME: If the operand types don't match the type of the divide
2867 // then don't attempt this transform. The code below doesn't have the
2868 // logic to deal with a signed divide and an unsigned compare (and
2869 // vice versa). This is because (x /s C2) <s C produces different
2870 // results than (x /s C2) <u C or (x /u C2) <s C or even
2871 // (x /u C2) <u C. Simply casting the operands and result won't
2872 // work. :( The if statement below tests that condition and bails
2873 // if it finds it.
2874 // However, when the divisor is a positive constant and the dividend is
2875 // known non-negative, sdiv is equivalent to udiv, so we can lower
2876 // DivIsSigned and proceed through the unsigned path.
2877 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2878 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2879 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2880 return nullptr;
2881 DivIsSigned = false;
2882 }
2883
2884 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2885 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2886 // division-by-constant cases should be present, we can not assert that they
2887 // have happened before we reach this icmp instruction.
2888 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2889 return nullptr;
2890
2891 // Compute Prod = C * C2. We are essentially solving an equation of
2892 // form X / C2 = C. We solve for X by multiplying C2 and C.
2893 // By solving for X, we can turn this into a range check instead of computing
2894 // a divide.
2895 APInt Prod = C * *C2;
2896
2897 // Determine if the product overflows by seeing if the product is not equal to
2898 // the divide. Make sure we do the same kind of divide as in the LHS
2899 // instruction that we're folding.
2900 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2901
2902 // If the division is known to be exact, then there is no remainder from the
2903 // divide, so the covered range size is unit, otherwise it is the divisor.
2904 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2905
2906 // Figure out the interval that is being checked. For example, a comparison
2907 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2908 // Compute this interval based on the constants involved and the signedness of
2909 // the compare/divide. This computes a half-open interval, keeping track of
2910 // whether either value in the interval overflows. After analysis each
2911 // overflow variable is set to 0 if it's corresponding bound variable is valid
2912 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2913 int LoOverflow = 0, HiOverflow = 0;
2914 APInt LoBound, HiBound;
2915
2916 if (!DivIsSigned) { // udiv
2917 // e.g. X/5 op 3 --> [15, 20)
2918 LoBound = Prod;
2919 HiOverflow = LoOverflow = ProdOV;
2920 if (!HiOverflow) {
2921 // If this is not an exact divide, then many values in the range collapse
2922 // to the same result value.
2923 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2924 }
2925 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2926 if (C.isZero()) { // (X / pos) op 0
2927 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2928 LoBound = -(RangeSize - 1);
2929 HiBound = RangeSize;
2930 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2931 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2932 HiOverflow = LoOverflow = ProdOV;
2933 if (!HiOverflow)
2934 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2935 } else { // (X / pos) op neg
2936 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2937 HiBound = Prod + 1;
2938 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2939 if (!LoOverflow) {
2940 APInt DivNeg = -RangeSize;
2941 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2942 }
2943 }
2944 } else if (C2->isNegative()) { // Divisor is < 0.
2945 if (Div->isExact())
2946 RangeSize.negate();
2947 if (C.isZero()) { // (X / neg) op 0
2948 // e.g. X/-5 op 0 --> [-4, 5)
2949 LoBound = RangeSize + 1;
2950 HiBound = -RangeSize;
2951 if (HiBound == *C2) { // -INTMIN = INTMIN
2952 HiOverflow = 1; // [INTMIN+1, overflow)
2953 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2954 }
2955 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2956 // e.g. X/-5 op 3 --> [-19, -14)
2957 HiBound = Prod + 1;
2958 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2959 if (!LoOverflow)
2960 LoOverflow =
2961 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2962 } else { // (X / neg) op neg
2963 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2964 LoOverflow = HiOverflow = ProdOV;
2965 if (!HiOverflow)
2966 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2967 }
2968
2969 // Dividing by a negative swaps the condition. LT <-> GT
2970 Pred = ICmpInst::getSwappedPredicate(Pred);
2971 }
2972
2973 switch (Pred) {
2974 default:
2975 llvm_unreachable("Unhandled icmp predicate!");
2976 case ICmpInst::ICMP_EQ:
2977 if (LoOverflow && HiOverflow)
2978 return replaceInstUsesWith(Cmp, Builder.getFalse());
2979 if (HiOverflow)
2980 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2981 X, ConstantInt::get(Ty, LoBound));
2982 if (LoOverflow)
2983 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2984 X, ConstantInt::get(Ty, HiBound));
2985 return replaceInstUsesWith(
2986 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2987 case ICmpInst::ICMP_NE:
2988 if (LoOverflow && HiOverflow)
2989 return replaceInstUsesWith(Cmp, Builder.getTrue());
2990 if (HiOverflow)
2991 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2992 X, ConstantInt::get(Ty, LoBound));
2993 if (LoOverflow)
2994 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2995 X, ConstantInt::get(Ty, HiBound));
2996 return replaceInstUsesWith(
2997 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2998 case ICmpInst::ICMP_ULT:
2999 case ICmpInst::ICMP_SLT:
3000 if (LoOverflow == +1) // Low bound is greater than input range.
3001 return replaceInstUsesWith(Cmp, Builder.getTrue());
3002 if (LoOverflow == -1) // Low bound is less than input range.
3003 return replaceInstUsesWith(Cmp, Builder.getFalse());
3004 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3005 case ICmpInst::ICMP_UGT:
3006 case ICmpInst::ICMP_SGT:
3007 if (HiOverflow == +1) // High bound greater than input range.
3008 return replaceInstUsesWith(Cmp, Builder.getFalse());
3009 if (HiOverflow == -1) // High bound less than input range.
3010 return replaceInstUsesWith(Cmp, Builder.getTrue());
3011 if (Pred == ICmpInst::ICMP_UGT)
3012 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3013 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3014 }
3015
3016 return nullptr;
3017}
3018
3019/// Fold icmp (sub X, Y), C.
3022 const APInt &C) {
3023 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3024 ICmpInst::Predicate Pred = Cmp.getPredicate();
3025 Type *Ty = Sub->getType();
3026
3027 // (SubC - Y) == C) --> Y == (SubC - C)
3028 // (SubC - Y) != C) --> Y != (SubC - C)
3029 Constant *SubC;
3030 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3031 return new ICmpInst(Pred, Y,
3032 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3033 }
3034
3035 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3036 const APInt *C2;
3037 APInt SubResult;
3038 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3039 bool HasNSW = Sub->hasNoSignedWrap();
3040 bool HasNUW = Sub->hasNoUnsignedWrap();
3041 if (match(X, m_APInt(C2)) &&
3042 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3043 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3044 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3045
3046 // X - Y == 0 --> X == Y.
3047 // X - Y != 0 --> X != Y.
3048 // TODO: We allow this with multiple uses as long as the other uses are not
3049 // in phis. The phi use check is guarding against a codegen regression
3050 // for a loop test. If the backend could undo this (and possibly
3051 // subsequent transforms), we would not need this hack.
3052 if (Cmp.isEquality() && C.isZero() &&
3053 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3054 return new ICmpInst(Pred, X, Y);
3055
3056 // The following transforms are only worth it if the only user of the subtract
3057 // is the icmp.
3058 // TODO: This is an artificial restriction for all of the transforms below
3059 // that only need a single replacement icmp. Can these use the phi test
3060 // like the transform above here?
3061 if (!Sub->hasOneUse())
3062 return nullptr;
3063
3064 if (Sub->hasNoSignedWrap()) {
3065 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3066 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3067 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3068
3069 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3070 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3071 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3072
3073 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3074 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3075 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3076
3077 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3078 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3079 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3080 }
3081
3082 if (!match(X, m_APInt(C2)))
3083 return nullptr;
3084
3085 // C2 - Y <u C -> (Y | (C - 1)) == C2
3086 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3087 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3088 (*C2 & (C - 1)) == (C - 1))
3089 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3090
3091 // C2 - Y >u C -> (Y | C) != C2
3092 // iff C2 & C == C and C + 1 is a power of 2
3093 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3094 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3095
3096 // We have handled special cases that reduce.
3097 // Canonicalize any remaining sub to add as:
3098 // (C2 - Y) > C --> (Y + ~C2) < ~C
3099 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3100 HasNUW, HasNSW);
3101 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3102}
3103
3104static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3105 Value *Op1, IRBuilderBase &Builder,
3106 bool HasOneUse) {
3107 auto FoldConstant = [&](bool Val) {
3108 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3109 if (Op0->getType()->isVectorTy())
3111 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3112 return Res;
3113 };
3114
3115 switch (Table.to_ulong()) {
3116 case 0: // 0 0 0 0
3117 return FoldConstant(false);
3118 case 1: // 0 0 0 1
3119 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3120 case 2: // 0 0 1 0
3121 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3122 case 3: // 0 0 1 1
3123 return Builder.CreateNot(Op0);
3124 case 4: // 0 1 0 0
3125 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3126 case 5: // 0 1 0 1
3127 return Builder.CreateNot(Op1);
3128 case 6: // 0 1 1 0
3129 return Builder.CreateXor(Op0, Op1);
3130 case 7: // 0 1 1 1
3131 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3132 case 8: // 1 0 0 0
3133 return Builder.CreateAnd(Op0, Op1);
3134 case 9: // 1 0 0 1
3135 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3136 case 10: // 1 0 1 0
3137 return Op1;
3138 case 11: // 1 0 1 1
3139 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3140 case 12: // 1 1 0 0
3141 return Op0;
3142 case 13: // 1 1 0 1
3143 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3144 case 14: // 1 1 1 0
3145 return Builder.CreateOr(Op0, Op1);
3146 case 15: // 1 1 1 1
3147 return FoldConstant(true);
3148 default:
3149 llvm_unreachable("Invalid Operation");
3150 }
3151 return nullptr;
3152}
3153
3155 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3156 Value *A, *B;
3157 Constant *C1, *C2, *C3, *C4;
3158 if (!match(BO->getOperand(0),
3160 !match(BO->getOperand(1),
3162 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3163 return nullptr;
3164
3165 std::bitset<4> Table;
3166 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3167 Constant *L = First ? C1 : C2;
3168 Constant *R = Second ? C3 : C4;
3169 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3170 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3171 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3172 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3173 }
3174 return std::nullopt;
3175 };
3176
3177 for (unsigned I = 0; I < 4; ++I) {
3178 bool First = (I >> 1) & 1;
3179 bool Second = I & 1;
3180 if (auto Res = ComputeTable(First, Second))
3181 Table[I] = *Res;
3182 else
3183 return nullptr;
3184 }
3185
3186 // Synthesize optimal logic.
3187 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3188 return replaceInstUsesWith(Cmp, Cond);
3189 return nullptr;
3190}
3191
3192/// Fold icmp (add X, Y), C.
3195 const APInt &C) {
3196 Value *Y = Add->getOperand(1);
3197 Value *X = Add->getOperand(0);
3198 const CmpPredicate Pred = Cmp.getCmpPredicate();
3199
3200 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3201 // when C <= (1 << ShAmtC).
3202 const APInt *ShAmtC;
3203 Value *A;
3204 unsigned BitWidth = C.getBitWidth();
3205 if (Pred == ICmpInst::ICMP_ULT &&
3206 match(Add,
3207 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3208 ShAmtC->ult(BitWidth) &&
3209 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3210 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3211
3212 const APInt *C2;
3213 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3214 return nullptr;
3215
3216 // Fold icmp pred (add X, C2), C.
3217 Type *Ty = Add->getType();
3218
3219 // If the add does not wrap, we can always adjust the compare by subtracting
3220 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3221 // have been canonicalized to SGT/SLT/UGT/ULT.
3222 if (Add->hasNoUnsignedWrap() &&
3223 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3224 bool Overflow;
3225 APInt NewC = C.usub_ov(*C2, Overflow);
3226 // If there is overflow, the result must be true or false.
3227 if (!Overflow)
3228 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3229 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3230 }
3231
3232 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3233
3234 if (Add->hasNoSignedWrap() &&
3235 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3236 bool Overflow;
3237 APInt NewC = C.ssub_ov(*C2, Overflow);
3238 if (!Overflow)
3239 // icmp samesign ugt/ult (add nsw X, C2), C
3240 // -> icmp sgt/slt X, (C - C2)
3241 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3242 }
3243
3244 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3245 C.isNonNegative() && (C - *C2).isNonNegative() &&
3246 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3247 .add(*C2)
3248 .isAllNonNegative())
3249 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3250 ConstantInt::get(Ty, C - *C2));
3251
3252 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3253 const APInt &Upper = CR.getUpper();
3254 const APInt &Lower = CR.getLower();
3255 if (Cmp.isSigned()) {
3256 if (Lower.isSignMask())
3257 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3258 if (Upper.isSignMask())
3259 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3260 } else {
3261 if (Lower.isMinValue())
3262 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3263 if (Upper.isMinValue())
3264 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3265 }
3266
3267 // This set of folds is intentionally placed after folds that use no-wrapping
3268 // flags because those folds are likely better for later analysis/codegen.
3269 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3270 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3271
3272 // Fold compare with offset to opposite sign compare if it eliminates offset:
3273 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3274 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3275 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3276
3277 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3278 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3279 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3280
3281 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3282 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3283 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3284
3285 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3286 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3287 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3288
3289 // (X + -1) <u C --> X <=u C (if X is never null)
3290 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3291 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3292 if (llvm::isKnownNonZero(X, Q))
3293 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3294 }
3295
3296 if (!Add->hasOneUse())
3297 return nullptr;
3298
3299 // X+C <u C2 -> (X & -C2) == C
3300 // iff C & (C2-1) == 0
3301 // C2 is a power of 2
3302 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3303 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3305
3306 // X+C2 <u C -> (X & C) == 2C
3307 // iff C == -(C2)
3308 // C2 is a power of 2
3309 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3310 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3311 ConstantInt::get(Ty, C * 2));
3312
3313 // X+C >u C2 -> (X & ~C2) != C
3314 // iff C & C2 == 0
3315 // C2+1 is a power of 2
3316 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3317 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3319
3320 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3321 // to the ult form.
3322 // X+C2 >u C -> X+(C2-C-1) <u ~C
3323 if (Pred == ICmpInst::ICMP_UGT)
3324 return new ICmpInst(ICmpInst::ICMP_ULT,
3325 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3326 ConstantInt::get(Ty, ~C));
3327
3328 // zext(V) + C2 pred C -> V + C3 pred' C4
3329 Value *V;
3330 if (match(X, m_ZExt(m_Value(V)))) {
3331 Type *NewCmpTy = V->getType();
3332 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3333 if (shouldChangeType(Ty, NewCmpTy)) {
3334 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3335 CmpInst::Predicate EquivPred;
3336 APInt EquivInt;
3337 APInt EquivOffset;
3338
3339 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3340 return new ICmpInst(
3341 EquivPred,
3342 EquivOffset.isZero()
3343 ? V
3344 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3345 ConstantInt::get(NewCmpTy, EquivInt));
3346 }
3347 }
3348
3349 return nullptr;
3350}
3351
3353 Value *&RHS, ConstantInt *&Less,
3354 ConstantInt *&Equal,
3355 ConstantInt *&Greater) {
3356 // TODO: Generalize this to work with other comparison idioms or ensure
3357 // they get canonicalized into this form.
3358
3359 // select i1 (a == b),
3360 // i32 Equal,
3361 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3362 // where Equal, Less and Greater are placeholders for any three constants.
3363 CmpPredicate PredA;
3364 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3365 !ICmpInst::isEquality(PredA))
3366 return false;
3367 Value *EqualVal = SI->getTrueValue();
3368 Value *UnequalVal = SI->getFalseValue();
3369 // We still can get non-canonical predicate here, so canonicalize.
3370 if (PredA == ICmpInst::ICMP_NE)
3371 std::swap(EqualVal, UnequalVal);
3372 if (!match(EqualVal, m_ConstantInt(Equal)))
3373 return false;
3374 CmpPredicate PredB;
3375 Value *LHS2, *RHS2;
3376 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3377 m_ConstantInt(Less), m_ConstantInt(Greater))))
3378 return false;
3379 // We can get predicate mismatch here, so canonicalize if possible:
3380 // First, ensure that 'LHS' match.
3381 if (LHS2 != LHS) {
3382 // x sgt y <--> y slt x
3383 std::swap(LHS2, RHS2);
3384 PredB = ICmpInst::getSwappedPredicate(PredB);
3385 }
3386 if (LHS2 != LHS)
3387 return false;
3388 // We also need to canonicalize 'RHS'.
3389 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3390 // x sgt C-1 <--> x sge C <--> not(x slt C)
3391 auto FlippedStrictness =
3393 if (!FlippedStrictness)
3394 return false;
3395 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3396 "basic correctness failure");
3397 RHS2 = FlippedStrictness->second;
3398 // And kind-of perform the result swap.
3399 std::swap(Less, Greater);
3400 PredB = ICmpInst::ICMP_SLT;
3401 }
3402 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3403}
3404
3407 ConstantInt *C) {
3408
3409 assert(C && "Cmp RHS should be a constant int!");
3410 // If we're testing a constant value against the result of a three way
3411 // comparison, the result can be expressed directly in terms of the
3412 // original values being compared. Note: We could possibly be more
3413 // aggressive here and remove the hasOneUse test. The original select is
3414 // really likely to simplify or sink when we remove a test of the result.
3415 Value *OrigLHS, *OrigRHS;
3416 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3417 if (Cmp.hasOneUse() &&
3418 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3419 C3GreaterThan)) {
3420 assert(C1LessThan && C2Equal && C3GreaterThan);
3421
3422 bool TrueWhenLessThan = ICmpInst::compare(
3423 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3424 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3425 Cmp.getPredicate());
3426 bool TrueWhenGreaterThan = ICmpInst::compare(
3427 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3428
3429 // This generates the new instruction that will replace the original Cmp
3430 // Instruction. Instead of enumerating the various combinations when
3431 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3432 // false, we rely on chaining of ORs and future passes of InstCombine to
3433 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3434
3435 // When none of the three constants satisfy the predicate for the RHS (C),
3436 // the entire original Cmp can be simplified to a false.
3437 Value *Cond = Builder.getFalse();
3438 if (TrueWhenLessThan)
3439 Cond = Builder.CreateOr(
3440 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3441 if (TrueWhenEqual)
3442 Cond = Builder.CreateOr(
3443 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3444 if (TrueWhenGreaterThan)
3445 Cond = Builder.CreateOr(
3446 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3447
3448 return replaceInstUsesWith(Cmp, Cond);
3449 }
3450 return nullptr;
3451}
3452
3454 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3455 if (!Bitcast)
3456 return nullptr;
3457
3458 ICmpInst::Predicate Pred = Cmp.getPredicate();
3459 Value *Op1 = Cmp.getOperand(1);
3460 Value *BCSrcOp = Bitcast->getOperand(0);
3461 Type *SrcType = Bitcast->getSrcTy();
3462 Type *DstType = Bitcast->getType();
3463
3464 // Make sure the bitcast doesn't change between scalar and vector and
3465 // doesn't change the number of vector elements.
3466 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3467 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3468 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3469 Value *X;
3470 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3471 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3472 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3473 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3474 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3475 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3476 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3477 match(Op1, m_Zero()))
3478 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3479
3480 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3481 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3482 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3483
3484 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3485 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3486 return new ICmpInst(Pred, X,
3487 ConstantInt::getAllOnesValue(X->getType()));
3488 }
3489
3490 // Zero-equality checks are preserved through unsigned floating-point casts:
3491 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3492 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3493 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3494 if (Cmp.isEquality() && match(Op1, m_Zero()))
3495 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3496
3497 const APInt *C;
3498 bool TrueIfSigned;
3499 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3500 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3501 // the FP extend/truncate because that cast does not change the sign-bit.
3502 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3503 // The sign-bit is always the most significant bit in those types.
3504 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3505 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3506 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3507 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3508 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3509 Type *XType = X->getType();
3510
3511 // We can't currently handle Power style floating point operations here.
3512 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3513 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3514 if (auto *XVTy = dyn_cast<VectorType>(XType))
3515 NewType = VectorType::get(NewType, XVTy->getElementCount());
3516 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3517 if (TrueIfSigned)
3518 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3519 ConstantInt::getNullValue(NewType));
3520 else
3521 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3523 }
3524 }
3525
3526 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3527 Type *FPType = SrcType->getScalarType();
3528 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3529 Attribute::NoImplicitFloat) &&
3530 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3531 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3532 if (Mask & (fcInf | fcZero)) {
3533 if (Pred == ICmpInst::ICMP_NE)
3534 Mask = ~Mask;
3535 return replaceInstUsesWith(Cmp,
3536 Builder.createIsFPClass(BCSrcOp, Mask));
3537 }
3538 }
3539 }
3540 }
3541
3542 const APInt *C;
3543 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3544 !SrcType->isIntOrIntVectorTy())
3545 return nullptr;
3546
3547 // If this is checking if all elements of a vector compare are set or not,
3548 // invert the casted vector equality compare and test if all compare
3549 // elements are clear or not. Compare against zero is generally easier for
3550 // analysis and codegen.
3551 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3552 // Example: are all elements equal? --> are zero elements not equal?
3553 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3554 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3555 if (Value *NotBCSrcOp =
3556 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3557 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3558 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3559 }
3560 }
3561
3562 // If this is checking if all elements of an extended vector are clear or not,
3563 // compare in a narrow type to eliminate the extend:
3564 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3565 Value *X;
3566 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3567 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3568 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3569 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3570 Value *NewCast = Builder.CreateBitCast(X, NewType);
3571 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3572 }
3573 }
3574
3575 // Folding: icmp <pred> iN X, C
3576 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3577 // and C is a splat of a K-bit pattern
3578 // and SC is a constant vector = <C', C', C', ..., C'>
3579 // Into:
3580 // %E = extractelement <M x iK> %vec, i32 C'
3581 // icmp <pred> iK %E, trunc(C)
3582 Value *Vec;
3583 ArrayRef<int> Mask;
3584 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3585 // Check whether every element of Mask is the same constant
3586 if (all_equal(Mask)) {
3587 auto *VecTy = cast<VectorType>(SrcType);
3588 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3589 if (C->isSplat(EltTy->getBitWidth())) {
3590 // Fold the icmp based on the value of C
3591 // If C is M copies of an iK sized bit pattern,
3592 // then:
3593 // => %E = extractelement <N x iK> %vec, i64 Elem
3594 // icmp <pred> iK %SplatVal, <pattern>
3595 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3596 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3597 return new ICmpInst(Pred, Extract, NewC);
3598 }
3599 }
3600 }
3601 return nullptr;
3602}
3603
3604/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3605/// where X is some kind of instruction.
3607 const APInt *C;
3608
3609 if (match(Cmp.getOperand(1), m_APInt(C))) {
3610 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3611 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3612 return I;
3613
3614 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3615 // For now, we only support constant integers while folding the
3616 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3617 // similar to the cases handled by binary ops above.
3618 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3619 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3620 return I;
3621
3622 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3623 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3624 return I;
3625
3626 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3628 return I;
3629
3630 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3631 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3632 // TODO: This checks one-use, but that is not strictly necessary.
3633 Value *Cmp0 = Cmp.getOperand(0);
3634 Value *X, *Y;
3635 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3636 (match(Cmp0,
3638 m_Value(X), m_Value(Y)))) ||
3639 match(Cmp0,
3641 m_Value(X), m_Value(Y))))))
3642 return new ICmpInst(Cmp.getPredicate(), X, Y);
3643 }
3644
3645 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3647
3648 return nullptr;
3649}
3650
3651/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3652/// icmp eq/ne BO, C.
3654 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3655 // TODO: Some of these folds could work with arbitrary constants, but this
3656 // function is limited to scalar and vector splat constants.
3657 if (!Cmp.isEquality())
3658 return nullptr;
3659
3660 ICmpInst::Predicate Pred = Cmp.getPredicate();
3661 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3662 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3663 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3664
3665 switch (BO->getOpcode()) {
3666 case Instruction::SRem:
3667 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3668 if (C.isZero() && BO->hasOneUse()) {
3669 const APInt *BOC;
3670 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3671 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3672 return new ICmpInst(Pred, NewRem,
3674 }
3675 }
3676 break;
3677 case Instruction::Add: {
3678 // (A + C2) == C --> A == (C - C2)
3679 // (A + C2) != C --> A != (C - C2)
3680 // TODO: Remove the one-use limitation? See discussion in D58633.
3681 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3682 if (BO->hasOneUse())
3683 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3684 } else if (C.isZero()) {
3685 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3686 // efficiently invertible, or if the add has just this one use.
3687 if (Value *NegVal = dyn_castNegVal(BOp1))
3688 return new ICmpInst(Pred, BOp0, NegVal);
3689 if (Value *NegVal = dyn_castNegVal(BOp0))
3690 return new ICmpInst(Pred, NegVal, BOp1);
3691 if (BO->hasOneUse()) {
3692 // (add nuw A, B) != 0 -> (or A, B) != 0
3693 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3694 Value *Or = Builder.CreateOr(BOp0, BOp1);
3695 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3696 }
3697 Value *Neg = Builder.CreateNeg(BOp1);
3698 Neg->takeName(BO);
3699 return new ICmpInst(Pred, BOp0, Neg);
3700 }
3701 }
3702 break;
3703 }
3704 case Instruction::Xor:
3705 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3706 // For the xor case, we can xor two constants together, eliminating
3707 // the explicit xor.
3708 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3709 } else if (C.isZero()) {
3710 // Replace ((xor A, B) != 0) with (A != B)
3711 return new ICmpInst(Pred, BOp0, BOp1);
3712 }
3713 break;
3714 case Instruction::Or: {
3715 const APInt *BOC;
3716 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3717 // Comparing if all bits outside of a constant mask are set?
3718 // Replace (X | C) == -1 with (X & ~C) == ~C.
3719 // This removes the -1 constant.
3721 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3722 return new ICmpInst(Pred, And, NotBOC);
3723 }
3724 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3725 // -> (and cond, (icmp eq Other, 0))
3726 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3727 // -> (or cond, (icmp ne Other, 0))
3728 Value *Cond, *TV, *FV, *Other, *Sel;
3729 if (C.isZero() &&
3730 match(BO,
3733 m_Value(FV))),
3734 m_Value(Other)))) &&
3735 Cond->getType() == Cmp.getType()) {
3736 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3737 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3738 if (Pred == ICmpInst::ICMP_EQ
3739 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3740 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3741 Value *Cmp = Builder.CreateICmp(
3742 Pred, Other, Constant::getNullValue(Other->getType()));
3744 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3745 Cond);
3746 }
3747 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3748 // case we need to invert the select condition so we need to be careful to
3749 // avoid creating extra instructions.
3750 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3751 // -> (or (not cond), (icmp ne Other, 0))
3752 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3753 // -> (and (not cond), (icmp eq Other, 0))
3754 //
3755 // Only do this if the inner select has one use, in which case we are
3756 // replacing `select` with `(not cond)`. Otherwise, we will create more
3757 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3758 // cond was freely invertable, the select arms would have been inverted.
3759 if (Sel->hasOneUse() &&
3760 (Pred == ICmpInst::ICMP_EQ
3761 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3762 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3763 Value *NotCond = Builder.CreateNot(Cond);
3764 Value *Cmp = Builder.CreateICmp(
3765 Pred, Other, Constant::getNullValue(Other->getType()));
3767 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3768 NotCond);
3769 }
3770 }
3771 break;
3772 }
3773 case Instruction::UDiv:
3774 case Instruction::SDiv:
3775 if (BO->isExact()) {
3776 // div exact X, Y eq/ne 0 -> X eq/ne 0
3777 // div exact X, Y eq/ne 1 -> X eq/ne Y
3778 // div exact X, Y eq/ne C ->
3779 // if Y * C never-overflow && OneUse:
3780 // -> Y * C eq/ne X
3781 if (C.isZero())
3782 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3783 else if (C.isOne())
3784 return new ICmpInst(Pred, BOp0, BOp1);
3785 else if (BO->hasOneUse()) {
3787 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3788 Cmp.getOperand(1), BO);
3790 Value *YC =
3791 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3792 return new ICmpInst(Pred, YC, BOp0);
3793 }
3794 }
3795 }
3796 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3797 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3798 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3799 return new ICmpInst(NewPred, BOp1, BOp0);
3800 }
3801 break;
3802 default:
3803 break;
3804 }
3805 return nullptr;
3806}
3807
3809 const APInt &CRhs,
3810 InstCombiner::BuilderTy &Builder,
3811 const SimplifyQuery &Q) {
3812 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3813 "Non-ctpop intrin in ctpop fold");
3814 if (!CtpopLhs->hasOneUse())
3815 return nullptr;
3816
3817 // Power of 2 test:
3818 // isPow2OrZero : ctpop(X) u< 2
3819 // isPow2 : ctpop(X) == 1
3820 // NotPow2OrZero: ctpop(X) u> 1
3821 // NotPow2 : ctpop(X) != 1
3822 // If we know any bit of X can be folded to:
3823 // IsPow2 : X & (~Bit) == 0
3824 // NotPow2 : X & (~Bit) != 0
3825 const ICmpInst::Predicate Pred = I.getPredicate();
3826 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3827 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3828 Value *Op = CtpopLhs->getArgOperand(0);
3829 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CxtI, Q.DT);
3830 // No need to check for count > 1, that should be already constant folded.
3831 if (OpKnown.countMinPopulation() == 1) {
3832 Value *And = Builder.CreateAnd(
3833 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3834 return new ICmpInst(
3835 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3838 And, Constant::getNullValue(Op->getType()));
3839 }
3840 }
3841
3842 return nullptr;
3843}
3844
3845/// Fold an equality icmp with LLVM intrinsic and constant operand.
3847 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3848 Type *Ty = II->getType();
3849 unsigned BitWidth = C.getBitWidth();
3850 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3851
3852 switch (II->getIntrinsicID()) {
3853 case Intrinsic::abs:
3854 // abs(A) == 0 -> A == 0
3855 // abs(A) == INT_MIN -> A == INT_MIN
3856 if (C.isZero() || C.isMinSignedValue())
3857 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3858 break;
3859
3860 case Intrinsic::bswap:
3861 // bswap(A) == C -> A == bswap(C)
3862 return new ICmpInst(Pred, II->getArgOperand(0),
3863 ConstantInt::get(Ty, C.byteSwap()));
3864
3865 case Intrinsic::bitreverse:
3866 // bitreverse(A) == C -> A == bitreverse(C)
3867 return new ICmpInst(Pred, II->getArgOperand(0),
3868 ConstantInt::get(Ty, C.reverseBits()));
3869
3870 case Intrinsic::ctlz:
3871 case Intrinsic::cttz: {
3872 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3873 if (C == BitWidth)
3874 return new ICmpInst(Pred, II->getArgOperand(0),
3876
3877 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3878 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3879 // Limit to one use to ensure we don't increase instruction count.
3880 unsigned Num = C.getLimitedValue(BitWidth);
3881 if (Num != BitWidth && II->hasOneUse()) {
3882 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3883 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3884 : APInt::getHighBitsSet(BitWidth, Num + 1);
3885 APInt Mask2 = IsTrailing
3888 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3889 ConstantInt::get(Ty, Mask2));
3890 }
3891 break;
3892 }
3893
3894 case Intrinsic::ctpop: {
3895 // popcount(A) == 0 -> A == 0 and likewise for !=
3896 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3897 bool IsZero = C.isZero();
3898 if (IsZero || C == BitWidth)
3899 return new ICmpInst(Pred, II->getArgOperand(0),
3900 IsZero ? Constant::getNullValue(Ty)
3902
3903 break;
3904 }
3905
3906 case Intrinsic::fshl:
3907 case Intrinsic::fshr:
3908 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3909 const APInt *RotAmtC;
3910 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3911 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3912 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3913 return new ICmpInst(Pred, II->getArgOperand(0),
3914 II->getIntrinsicID() == Intrinsic::fshl
3915 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3916 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3917 }
3918 break;
3919
3920 case Intrinsic::umax:
3921 case Intrinsic::uadd_sat: {
3922 // uadd.sat(a, b) == 0 -> (a | b) == 0
3923 // umax(a, b) == 0 -> (a | b) == 0
3924 if (C.isZero() && II->hasOneUse()) {
3925 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3926 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3927 }
3928 break;
3929 }
3930
3931 case Intrinsic::ssub_sat:
3932 // ssub.sat(a, b) == 0 -> a == b
3933 //
3934 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
3935 // (because 1 saturates to 0). Just skip the optimization for i1.
3936 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
3937 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3938 break;
3939 case Intrinsic::usub_sat: {
3940 // usub.sat(a, b) == 0 -> a <= b
3941 if (C.isZero()) {
3942 ICmpInst::Predicate NewPred =
3944 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3945 }
3946 break;
3947 }
3948 default:
3949 break;
3950 }
3951
3952 return nullptr;
3953}
3954
3955/// Fold an icmp with LLVM intrinsics
3956static Instruction *
3958 InstCombiner::BuilderTy &Builder) {
3959 assert(Cmp.isEquality());
3960
3961 ICmpInst::Predicate Pred = Cmp.getPredicate();
3962 Value *Op0 = Cmp.getOperand(0);
3963 Value *Op1 = Cmp.getOperand(1);
3964 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3965 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3966 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3967 return nullptr;
3968
3969 switch (IIOp0->getIntrinsicID()) {
3970 case Intrinsic::bswap:
3971 case Intrinsic::bitreverse:
3972 // If both operands are byte-swapped or bit-reversed, just compare the
3973 // original values.
3974 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3975 case Intrinsic::fshl:
3976 case Intrinsic::fshr: {
3977 // If both operands are rotated by same amount, just compare the
3978 // original values.
3979 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3980 break;
3981 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3982 break;
3983 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3984 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3985
3986 // rotate(X, AmtX) == rotate(Y, AmtY)
3987 // -> rotate(X, AmtX - AmtY) == Y
3988 // Do this if either both rotates have one use or if only one has one use
3989 // and AmtX/AmtY are constants.
3990 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3991 if (OneUses == 2 ||
3992 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
3993 match(IIOp1->getOperand(2), m_ImmConstant()))) {
3994 Value *SubAmt =
3995 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3996 Value *CombinedRotate = Builder.CreateIntrinsic(
3997 Op0->getType(), IIOp0->getIntrinsicID(),
3998 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3999 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4000 }
4001 } break;
4002 default:
4003 break;
4004 }
4005
4006 return nullptr;
4007}
4008
4009/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4010/// where X is some kind of instruction and C is AllowPoison.
4011/// TODO: Move more folds which allow poison to this function.
4014 const APInt &C) {
4015 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4016 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4017 switch (II->getIntrinsicID()) {
4018 default:
4019 break;
4020 case Intrinsic::fshl:
4021 case Intrinsic::fshr:
4022 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4023 // (rot X, ?) == 0/-1 --> X == 0/-1
4024 if (C.isZero() || C.isAllOnes())
4025 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4026 }
4027 break;
4028 }
4029 }
4030
4031 return nullptr;
4032}
4033
4034/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4036 BinaryOperator *BO,
4037 const APInt &C) {
4038 switch (BO->getOpcode()) {
4039 case Instruction::Xor:
4040 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4041 return I;
4042 break;
4043 case Instruction::And:
4044 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4045 return I;
4046 break;
4047 case Instruction::Or:
4048 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4049 return I;
4050 break;
4051 case Instruction::Mul:
4052 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4053 return I;
4054 break;
4055 case Instruction::Shl:
4056 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4057 return I;
4058 break;
4059 case Instruction::LShr:
4060 case Instruction::AShr:
4061 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4062 return I;
4063 break;
4064 case Instruction::SRem:
4065 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4066 return I;
4067 break;
4068 case Instruction::UDiv:
4069 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4070 return I;
4071 [[fallthrough]];
4072 case Instruction::SDiv:
4073 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4074 return I;
4075 break;
4076 case Instruction::Sub:
4077 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4078 return I;
4079 break;
4080 case Instruction::Add:
4081 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4082 return I;
4083 break;
4084 default:
4085 break;
4086 }
4087
4088 // TODO: These folds could be refactored to be part of the above calls.
4090 return I;
4091
4092 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4093 // : C4), C5` pattern, by computing a truth table of the four constant
4094 // variants.
4096}
4097
4098static Instruction *
4100 const APInt &C,
4101 InstCombiner::BuilderTy &Builder) {
4102 // This transform may end up producing more than one instruction for the
4103 // intrinsic, so limit it to one user of the intrinsic.
4104 if (!II->hasOneUse())
4105 return nullptr;
4106
4107 // Let Y = [add/sub]_sat(X, C) pred C2
4108 // SatVal = The saturating value for the operation
4109 // WillWrap = Whether or not the operation will underflow / overflow
4110 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4111 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4112 //
4113 // When (SatVal pred C2) is true, then
4114 // Y = WillWrap ? true : ((X binop C) pred C2)
4115 // => Y = WillWrap || ((X binop C) pred C2)
4116 // else
4117 // Y = WillWrap ? false : ((X binop C) pred C2)
4118 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4119 // => Y = !WillWrap && ((X binop C) pred C2)
4120 Value *Op0 = II->getOperand(0);
4121 Value *Op1 = II->getOperand(1);
4122
4123 const APInt *COp1;
4124 // This transform only works when the intrinsic has an integral constant or
4125 // splat vector as the second operand.
4126 if (!match(Op1, m_APInt(COp1)))
4127 return nullptr;
4128
4129 APInt SatVal;
4130 switch (II->getIntrinsicID()) {
4131 default:
4133 "This function only works with usub_sat and uadd_sat for now!");
4134 case Intrinsic::uadd_sat:
4135 SatVal = APInt::getAllOnes(C.getBitWidth());
4136 break;
4137 case Intrinsic::usub_sat:
4138 SatVal = APInt::getZero(C.getBitWidth());
4139 break;
4140 }
4141
4142 // Check (SatVal pred C2)
4143 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4144
4145 // !WillWrap.
4147 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4148
4149 // WillWrap.
4150 if (SatValCheck)
4151 C1 = C1.inverse();
4152
4154 if (II->getBinaryOp() == Instruction::Add)
4155 C2 = C2.sub(*COp1);
4156 else
4157 C2 = C2.add(*COp1);
4158
4159 Instruction::BinaryOps CombiningOp =
4160 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4161
4162 std::optional<ConstantRange> Combination;
4163 if (CombiningOp == Instruction::BinaryOps::Or)
4164 Combination = C1.exactUnionWith(C2);
4165 else /* CombiningOp == Instruction::BinaryOps::And */
4166 Combination = C1.exactIntersectWith(C2);
4167
4168 if (!Combination)
4169 return nullptr;
4170
4171 CmpInst::Predicate EquivPred;
4172 APInt EquivInt;
4173 APInt EquivOffset;
4174
4175 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4176
4177 return new ICmpInst(
4178 EquivPred,
4179 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4180 ConstantInt::get(Op1->getType(), EquivInt));
4181}
4182
4183static Instruction *
4185 const APInt &C,
4186 InstCombiner::BuilderTy &Builder) {
4187 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4188 switch (Pred) {
4189 case ICmpInst::ICMP_EQ:
4190 case ICmpInst::ICMP_NE:
4191 if (C.isZero())
4192 NewPredicate = Pred;
4193 else if (C.isOne())
4194 NewPredicate =
4196 else if (C.isAllOnes())
4197 NewPredicate =
4199 break;
4200
4201 case ICmpInst::ICMP_SGT:
4202 if (C.isAllOnes())
4203 NewPredicate = ICmpInst::ICMP_UGE;
4204 else if (C.isZero())
4205 NewPredicate = ICmpInst::ICMP_UGT;
4206 break;
4207
4208 case ICmpInst::ICMP_SLT:
4209 if (C.isZero())
4210 NewPredicate = ICmpInst::ICMP_ULT;
4211 else if (C.isOne())
4212 NewPredicate = ICmpInst::ICMP_ULE;
4213 break;
4214
4215 case ICmpInst::ICMP_ULT:
4216 if (C.ugt(1))
4217 NewPredicate = ICmpInst::ICMP_UGE;
4218 break;
4219
4220 case ICmpInst::ICMP_UGT:
4221 if (!C.isZero() && !C.isAllOnes())
4222 NewPredicate = ICmpInst::ICMP_ULT;
4223 break;
4224
4225 default:
4226 break;
4227 }
4228
4229 if (!NewPredicate)
4230 return nullptr;
4231
4232 if (I->getIntrinsicID() == Intrinsic::scmp)
4233 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4234 Value *LHS = I->getOperand(0);
4235 Value *RHS = I->getOperand(1);
4236 return new ICmpInst(*NewPredicate, LHS, RHS);
4237}
4238
4239/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4242 const APInt &C) {
4243 ICmpInst::Predicate Pred = Cmp.getPredicate();
4244
4245 // Handle folds that apply for any kind of icmp.
4246 switch (II->getIntrinsicID()) {
4247 default:
4248 break;
4249 case Intrinsic::uadd_sat:
4250 case Intrinsic::usub_sat:
4251 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4252 Pred, cast<SaturatingInst>(II), C, Builder))
4253 return Folded;
4254 break;
4255 case Intrinsic::ctpop: {
4256 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4257 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4258 return R;
4259 } break;
4260 case Intrinsic::scmp:
4261 case Intrinsic::ucmp:
4262 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4263 return Folded;
4264 break;
4265 }
4266
4267 if (Cmp.isEquality())
4268 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4269
4270 Type *Ty = II->getType();
4271 unsigned BitWidth = C.getBitWidth();
4272 switch (II->getIntrinsicID()) {
4273 case Intrinsic::ctpop: {
4274 // (ctpop X > BitWidth - 1) --> X == -1
4275 Value *X = II->getArgOperand(0);
4276 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4277 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4279 // (ctpop X < BitWidth) --> X != -1
4280 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4281 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4283 break;
4284 }
4285 case Intrinsic::ctlz: {
4286 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4287 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4288 unsigned Num = C.getLimitedValue();
4289 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4290 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4291 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4292 }
4293
4294 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4295 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4296 unsigned Num = C.getLimitedValue();
4298 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4299 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4300 }
4301 break;
4302 }
4303 case Intrinsic::cttz: {
4304 // Limit to one use to ensure we don't increase instruction count.
4305 if (!II->hasOneUse())
4306 return nullptr;
4307
4308 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4309 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4310 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4311 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4312 Builder.CreateAnd(II->getArgOperand(0), Mask),
4314 }
4315
4316 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4317 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4318 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4319 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4320 Builder.CreateAnd(II->getArgOperand(0), Mask),
4322 }
4323 break;
4324 }
4325 case Intrinsic::ssub_sat:
4326 // ssub.sat(a, b) spred 0 -> a spred b
4327 //
4328 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4329 // (because 1 saturates to 0). Just skip the optimization for i1.
4330 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4331 if (C.isZero())
4332 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4333 // X s<= 0 is cannonicalized to X s< 1
4334 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4335 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4336 II->getArgOperand(1));
4337 // X s>= 0 is cannonicalized to X s> -1
4338 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4339 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4340 II->getArgOperand(1));
4341 }
4342 break;
4343 case Intrinsic::abs: {
4344 if (!II->hasOneUse())
4345 return nullptr;
4346
4347 Value *X = II->getArgOperand(0);
4348 bool IsIntMinPoison =
4349 cast<ConstantInt>(II->getArgOperand(1))->getValue().isOne();
4350
4351 // If C >= 0:
4352 // abs(X) u> C --> X + C u> 2 * C
4353 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4354 return new ICmpInst(ICmpInst::ICMP_UGT,
4355 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4356 ConstantInt::get(Ty, 2 * C));
4357 }
4358
4359 // If abs(INT_MIN) is poison and C >= 1:
4360 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4361 if (IsIntMinPoison && Pred == CmpInst::ICMP_ULT && C.sge(1)) {
4362 return new ICmpInst(ICmpInst::ICMP_ULE,
4363 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4364 ConstantInt::get(Ty, 2 * (C - 1)));
4365 }
4366
4367 break;
4368 }
4369 default:
4370 break;
4371 }
4372
4373 return nullptr;
4374}
4375
4376/// Handle icmp with constant (but not simple integer constant) RHS.
4378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4379 Constant *RHSC = dyn_cast<Constant>(Op1);
4381 if (!RHSC || !LHSI)
4382 return nullptr;
4383
4384 switch (LHSI->getOpcode()) {
4385 case Instruction::IntToPtr:
4386 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4387 if (isa<ConstantPointerNull>(RHSC)) {
4388 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4389 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4390 APInt NullPtrValue =
4391 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4392 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4393 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4394 }
4395 }
4396 break;
4397
4398 case Instruction::Load:
4399 // Try to optimize things like "A[i] > 4" to index computations.
4400 if (GetElementPtrInst *GEP =
4402 if (Instruction *Res =
4404 return Res;
4405 break;
4406 }
4407
4408 return nullptr;
4409}
4410
4412 Value *RHS, const ICmpInst &I) {
4413 // Try to fold the comparison into the select arms, which will cause the
4414 // select to be converted into a logical and/or.
4415 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4416 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4417 return Res;
4418 if (std::optional<bool> Impl = isImpliedCondition(
4419 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4420 return ConstantInt::get(I.getType(), *Impl);
4421 return nullptr;
4422 };
4423
4424 ConstantInt *CI = nullptr;
4425 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4426 if (Op1)
4427 CI = dyn_cast<ConstantInt>(Op1);
4428
4429 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4430 if (Op2)
4431 CI = dyn_cast<ConstantInt>(Op2);
4432
4433 auto Simplifies = [&](Value *Op, unsigned Idx) {
4434 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4435 const APInt *Dummy;
4436 return Op ||
4437 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4438 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4439 };
4440
4441 // We only want to perform this transformation if it will not lead to
4442 // additional code. This is true if either both sides of the select
4443 // fold to a constant (in which case the icmp is replaced with a select
4444 // which will usually simplify) or this is the only user of the
4445 // select (in which case we are trading a select+icmp for a simpler
4446 // select+icmp) or all uses of the select can be replaced based on
4447 // dominance information ("Global cases").
4448 bool Transform = false;
4449 if (Op1 && Op2)
4450 Transform = true;
4451 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4452 // Local case
4453 if (SI->hasOneUse())
4454 Transform = true;
4455 // Global cases
4456 else if (CI && !CI->isZero())
4457 // When Op1 is constant try replacing select with second operand.
4458 // Otherwise Op2 is constant and try replacing select with first
4459 // operand.
4460 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4461 }
4462 if (Transform) {
4463 if (!Op1)
4464 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4465 if (!Op2)
4466 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4467 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr,
4468 ProfcheckDisableMetadataFixes ? nullptr : SI);
4469 }
4470
4471 return nullptr;
4472}
4473
4474// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4475static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4476 unsigned Depth = 0) {
4477 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4478 return true;
4479 if (V->getType()->getScalarSizeInBits() == 1)
4480 return true;
4482 return false;
4483 Value *X;
4485 if (!I)
4486 return false;
4487 switch (I->getOpcode()) {
4488 case Instruction::ZExt:
4489 // ZExt(Mask) is a Mask.
4490 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4491 case Instruction::SExt:
4492 // SExt(Mask) is a Mask.
4493 // SExt(~Mask) is a ~Mask.
4494 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4495 case Instruction::And:
4496 case Instruction::Or:
4497 // Mask0 | Mask1 is a Mask.
4498 // Mask0 & Mask1 is a Mask.
4499 // ~Mask0 | ~Mask1 is a ~Mask.
4500 // ~Mask0 & ~Mask1 is a ~Mask.
4501 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4502 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4503 case Instruction::Xor:
4504 if (match(V, m_Not(m_Value(X))))
4505 return isMaskOrZero(X, !Not, Q, Depth);
4506
4507 // (X ^ -X) is a ~Mask
4508 if (Not)
4509 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4510 // (X ^ (X - 1)) is a Mask
4511 else
4512 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4513 case Instruction::Select:
4514 // c ? Mask0 : Mask1 is a Mask.
4515 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4516 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4517 case Instruction::Shl:
4518 // (~Mask) << X is a ~Mask.
4519 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4520 case Instruction::LShr:
4521 // Mask >> X is a Mask.
4522 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4523 case Instruction::AShr:
4524 // Mask s>> X is a Mask.
4525 // ~Mask s>> X is a ~Mask.
4526 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4527 case Instruction::Add:
4528 // Pow2 - 1 is a Mask.
4529 if (!Not && match(I->getOperand(1), m_AllOnes()))
4530 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4531 Q.AC, Q.CxtI, Q.DT, Depth);
4532 break;
4533 case Instruction::Sub:
4534 // -Pow2 is a ~Mask.
4535 if (Not && match(I->getOperand(0), m_Zero()))
4536 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4537 Q.AC, Q.CxtI, Q.DT, Depth);
4538 break;
4539 case Instruction::Call: {
4540 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4541 switch (II->getIntrinsicID()) {
4542 // min/max(Mask0, Mask1) is a Mask.
4543 // min/max(~Mask0, ~Mask1) is a ~Mask.
4544 case Intrinsic::umax:
4545 case Intrinsic::smax:
4546 case Intrinsic::umin:
4547 case Intrinsic::smin:
4548 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4549 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4550
4551 // In the context of masks, bitreverse(Mask) == ~Mask
4552 case Intrinsic::bitreverse:
4553 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4554 default:
4555 break;
4556 }
4557 }
4558 break;
4559 }
4560 default:
4561 break;
4562 }
4563 return false;
4564}
4565
4566/// Some comparisons can be simplified.
4567/// In this case, we are looking for comparisons that look like
4568/// a check for a lossy truncation.
4569/// Folds:
4570/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4571/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4572/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4573/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4574/// Where Mask is some pattern that produces all-ones in low bits:
4575/// (-1 >> y)
4576/// ((-1 << y) >> y) <- non-canonical, has extra uses
4577/// ~(-1 << y)
4578/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4579/// The Mask can be a constant, too.
4580/// For some predicates, the operands are commutative.
4581/// For others, x can only be on a specific side.
4583 Value *Op1, const SimplifyQuery &Q,
4584 InstCombiner &IC) {
4585
4586 ICmpInst::Predicate DstPred;
4587 switch (Pred) {
4589 // x & Mask == x
4590 // x & ~Mask == 0
4591 // ~x | Mask == -1
4592 // -> x u<= Mask
4593 // x & ~Mask == ~Mask
4594 // -> ~Mask u<= x
4596 break;
4598 // x & Mask != x
4599 // x & ~Mask != 0
4600 // ~x | Mask != -1
4601 // -> x u> Mask
4602 // x & ~Mask != ~Mask
4603 // -> ~Mask u> x
4605 break;
4607 // x & Mask u< x
4608 // -> x u> Mask
4609 // x & ~Mask u< ~Mask
4610 // -> ~Mask u> x
4612 break;
4614 // x & Mask u>= x
4615 // -> x u<= Mask
4616 // x & ~Mask u>= ~Mask
4617 // -> ~Mask u<= x
4619 break;
4621 // x & Mask s< x [iff Mask s>= 0]
4622 // -> x s> Mask
4623 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4624 // -> ~Mask s> x
4626 break;
4628 // x & Mask s>= x [iff Mask s>= 0]
4629 // -> x s<= Mask
4630 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4631 // -> ~Mask s<= x
4633 break;
4634 default:
4635 // We don't support sgt,sle
4636 // ult/ugt are simplified to true/false respectively.
4637 return nullptr;
4638 }
4639
4640 Value *X, *M;
4641 // Put search code in lambda for early positive returns.
4642 auto IsLowBitMask = [&]() {
4643 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4644 X = Op1;
4645 // Look for: x & Mask pred x
4646 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4647 return !ICmpInst::isSigned(Pred) ||
4648 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4649 }
4650
4651 // Look for: x & ~Mask pred ~Mask
4652 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4653 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4654 }
4655 return false;
4656 }
4657 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4658 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4659
4660 auto Check = [&]() {
4661 // Look for: ~x | Mask == -1
4662 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4663 if (Value *NotX =
4664 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4665 X = NotX;
4666 return true;
4667 }
4668 }
4669 return false;
4670 };
4671 if (Check())
4672 return true;
4673 std::swap(X, M);
4674 return Check();
4675 }
4676 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4677 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4678 auto Check = [&]() {
4679 // Look for: x & ~Mask == 0
4680 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4681 if (Value *NotM =
4682 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4683 M = NotM;
4684 return true;
4685 }
4686 }
4687 return false;
4688 };
4689 if (Check())
4690 return true;
4691 std::swap(X, M);
4692 return Check();
4693 }
4694 return false;
4695 };
4696
4697 if (!IsLowBitMask())
4698 return nullptr;
4699
4700 return IC.Builder.CreateICmp(DstPred, X, M);
4701}
4702
4703/// Some comparisons can be simplified.
4704/// In this case, we are looking for comparisons that look like
4705/// a check for a lossy signed truncation.
4706/// Folds: (MaskedBits is a constant.)
4707/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4708/// Into:
4709/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4710/// Where KeptBits = bitwidth(%x) - MaskedBits
4711static Value *
4713 InstCombiner::BuilderTy &Builder) {
4714 CmpPredicate SrcPred;
4715 Value *X;
4716 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4717 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4718 if (!match(&I, m_c_ICmp(SrcPred,
4720 m_APInt(C1))),
4721 m_Deferred(X))))
4722 return nullptr;
4723
4724 // Potential handling of non-splats: for each element:
4725 // * if both are undef, replace with constant 0.
4726 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4727 // * if both are not undef, and are different, bailout.
4728 // * else, only one is undef, then pick the non-undef one.
4729
4730 // The shift amount must be equal.
4731 if (*C0 != *C1)
4732 return nullptr;
4733 const APInt &MaskedBits = *C0;
4734 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4735
4736 ICmpInst::Predicate DstPred;
4737 switch (SrcPred) {
4739 // ((%x << MaskedBits) a>> MaskedBits) == %x
4740 // =>
4741 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4743 break;
4745 // ((%x << MaskedBits) a>> MaskedBits) != %x
4746 // =>
4747 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4749 break;
4750 // FIXME: are more folds possible?
4751 default:
4752 return nullptr;
4753 }
4754
4755 auto *XType = X->getType();
4756 const unsigned XBitWidth = XType->getScalarSizeInBits();
4757 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4758 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4759
4760 // KeptBits = bitwidth(%x) - MaskedBits
4761 const APInt KeptBits = BitWidth - MaskedBits;
4762 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4763 // ICmpCst = (1 << KeptBits)
4764 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4765 assert(ICmpCst.isPowerOf2());
4766 // AddCst = (1 << (KeptBits-1))
4767 const APInt AddCst = ICmpCst.lshr(1);
4768 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4769
4770 // T0 = add %x, AddCst
4771 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4772 // T1 = T0 DstPred ICmpCst
4773 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4774
4775 return T1;
4776}
4777
4778// Given pattern:
4779// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4780// we should move shifts to the same hand of 'and', i.e. rewrite as
4781// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4782// We are only interested in opposite logical shifts here.
4783// One of the shifts can be truncated.
4784// If we can, we want to end up creating 'lshr' shift.
4785static Value *
4787 InstCombiner::BuilderTy &Builder) {
4788 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4789 !I.getOperand(0)->hasOneUse())
4790 return nullptr;
4791
4792 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4793
4794 // Look for an 'and' of two logical shifts, one of which may be truncated.
4795 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4796 Instruction *XShift, *MaybeTruncation, *YShift;
4797 if (!match(
4798 I.getOperand(0),
4799 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4801 m_AnyLogicalShift, m_Instruction(YShift))),
4802 m_Instruction(MaybeTruncation)))))
4803 return nullptr;
4804
4805 // We potentially looked past 'trunc', but only when matching YShift,
4806 // therefore YShift must have the widest type.
4807 Instruction *WidestShift = YShift;
4808 // Therefore XShift must have the shallowest type.
4809 // Or they both have identical types if there was no truncation.
4810 Instruction *NarrowestShift = XShift;
4811
4812 Type *WidestTy = WidestShift->getType();
4813 Type *NarrowestTy = NarrowestShift->getType();
4814 assert(NarrowestTy == I.getOperand(0)->getType() &&
4815 "We did not look past any shifts while matching XShift though.");
4816 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4817
4818 // If YShift is a 'lshr', swap the shifts around.
4819 if (match(YShift, m_LShr(m_Value(), m_Value())))
4820 std::swap(XShift, YShift);
4821
4822 // The shifts must be in opposite directions.
4823 auto XShiftOpcode = XShift->getOpcode();
4824 if (XShiftOpcode == YShift->getOpcode())
4825 return nullptr; // Do not care about same-direction shifts here.
4826
4827 Value *X, *XShAmt, *Y, *YShAmt;
4828 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4829 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4830
4831 // If one of the values being shifted is a constant, then we will end with
4832 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4833 // however, we will need to ensure that we won't increase instruction count.
4834 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4835 // At least one of the hands of the 'and' should be one-use shift.
4836 if (!match(I.getOperand(0),
4837 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4838 return nullptr;
4839 if (HadTrunc) {
4840 // Due to the 'trunc', we will need to widen X. For that either the old
4841 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4842 if (!MaybeTruncation->hasOneUse() &&
4843 !NarrowestShift->getOperand(1)->hasOneUse())
4844 return nullptr;
4845 }
4846 }
4847
4848 // We have two shift amounts from two different shifts. The types of those
4849 // shift amounts may not match. If that's the case let's bailout now.
4850 if (XShAmt->getType() != YShAmt->getType())
4851 return nullptr;
4852
4853 // As input, we have the following pattern:
4854 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4855 // We want to rewrite that as:
4856 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4857 // While we know that originally (Q+K) would not overflow
4858 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4859 // shift amounts. so it may now overflow in smaller bitwidth.
4860 // To ensure that does not happen, we need to ensure that the total maximal
4861 // shift amount is still representable in that smaller bit width.
4862 unsigned MaximalPossibleTotalShiftAmount =
4863 (WidestTy->getScalarSizeInBits() - 1) +
4864 (NarrowestTy->getScalarSizeInBits() - 1);
4865 APInt MaximalRepresentableShiftAmount =
4867 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4868 return nullptr;
4869
4870 // Can we fold (XShAmt+YShAmt) ?
4871 auto *NewShAmt = dyn_cast_or_null<Constant>(
4872 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4873 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4874 if (!NewShAmt)
4875 return nullptr;
4876 if (NewShAmt->getType() != WidestTy) {
4877 NewShAmt =
4878 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4879 if (!NewShAmt)
4880 return nullptr;
4881 }
4882 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4883
4884 // Is the new shift amount smaller than the bit width?
4885 // FIXME: could also rely on ConstantRange.
4886 if (!match(NewShAmt,
4888 APInt(WidestBitWidth, WidestBitWidth))))
4889 return nullptr;
4890
4891 // An extra legality check is needed if we had trunc-of-lshr.
4892 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4893 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4894 WidestShift]() {
4895 // It isn't obvious whether it's worth it to analyze non-constants here.
4896 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4897 // If *any* of these preconditions matches we can perform the fold.
4898 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4899 ? NewShAmt->getSplatValue()
4900 : NewShAmt;
4901 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4902 if (NewShAmtSplat &&
4903 (NewShAmtSplat->isNullValue() ||
4904 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4905 return true;
4906 // We consider *min* leading zeros so a single outlier
4907 // blocks the transform as opposed to allowing it.
4908 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4910 unsigned MinLeadZero = Known.countMinLeadingZeros();
4911 // If the value being shifted has at most lowest bit set we can fold.
4912 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4913 if (MaxActiveBits <= 1)
4914 return true;
4915 // Precondition: NewShAmt u<= countLeadingZeros(C)
4916 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4917 return true;
4918 }
4919 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4921 unsigned MinLeadZero = Known.countMinLeadingZeros();
4922 // If the value being shifted has at most lowest bit set we can fold.
4923 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4924 if (MaxActiveBits <= 1)
4925 return true;
4926 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4927 if (NewShAmtSplat) {
4928 APInt AdjNewShAmt =
4929 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4930 if (AdjNewShAmt.ule(MinLeadZero))
4931 return true;
4932 }
4933 }
4934 return false; // Can't tell if it's ok.
4935 };
4936 if (!CanFold())
4937 return nullptr;
4938 }
4939
4940 // All good, we can do this fold.
4941 X = Builder.CreateZExt(X, WidestTy);
4942 Y = Builder.CreateZExt(Y, WidestTy);
4943 // The shift is the same that was for X.
4944 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4945 ? Builder.CreateLShr(X, NewShAmt)
4946 : Builder.CreateShl(X, NewShAmt);
4947 Value *T1 = Builder.CreateAnd(T0, Y);
4948 return Builder.CreateICmp(I.getPredicate(), T1,
4949 Constant::getNullValue(WidestTy));
4950}
4951
4952/// Fold
4953/// (-1 u/ x) u< y
4954/// ((x * y) ?/ x) != y
4955/// to
4956/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4957/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4958/// will mean that we are looking for the opposite answer.
4960 CmpPredicate Pred;
4961 Value *X, *Y;
4963 Instruction *Div;
4964 bool NeedNegation;
4965 // Look for: (-1 u/ x) u</u>= y
4966 if (!I.isEquality() &&
4967 match(&I, m_c_ICmp(Pred,
4969 m_Instruction(Div)),
4970 m_Value(Y)))) {
4971 Mul = nullptr;
4972
4973 // Are we checking that overflow does not happen, or does happen?
4974 switch (Pred) {
4976 NeedNegation = false;
4977 break; // OK
4979 NeedNegation = true;
4980 break; // OK
4981 default:
4982 return nullptr; // Wrong predicate.
4983 }
4984 } else // Look for: ((x * y) / x) !=/== y
4985 if (I.isEquality() &&
4986 match(&I, m_c_ICmp(Pred, m_Value(Y),
4989 m_Value(X)),
4991 m_Deferred(X))),
4992 m_Instruction(Div))))) {
4993 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4994 } else
4995 return nullptr;
4996
4998 // If the pattern included (x * y), we'll want to insert new instructions
4999 // right before that original multiplication so that we can replace it.
5000 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5001 if (MulHadOtherUses)
5002 Builder.SetInsertPoint(Mul);
5003
5004 Value *Call = Builder.CreateIntrinsic(
5005 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5006 : Intrinsic::smul_with_overflow,
5007 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5008
5009 // If the multiplication was used elsewhere, to ensure that we don't leave
5010 // "duplicate" instructions, replace uses of that original multiplication
5011 // with the multiplication result from the with.overflow intrinsic.
5012 if (MulHadOtherUses)
5013 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5014
5015 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5016 if (NeedNegation) // This technically increases instruction count.
5017 Res = Builder.CreateNot(Res, "mul.not.ov");
5018
5019 // If we replaced the mul, erase it. Do this after all uses of Builder,
5020 // as the mul is used as insertion point.
5021 if (MulHadOtherUses)
5023
5024 return Res;
5025}
5026
5028 InstCombiner::BuilderTy &Builder) {
5029 CmpPredicate Pred;
5030 Value *X;
5031 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5032
5033 if (ICmpInst::isSigned(Pred))
5034 Pred = ICmpInst::getSwappedPredicate(Pred);
5035 else if (ICmpInst::isUnsigned(Pred))
5036 Pred = ICmpInst::getSignedPredicate(Pred);
5037 // else for equality-comparisons just keep the predicate.
5038
5039 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5040 Constant::getNullValue(X->getType()), I.getName());
5041 }
5042
5043 // A value is not equal to its negation unless that value is 0 or
5044 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5045 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5046 ICmpInst::isEquality(Pred)) {
5047 Type *Ty = X->getType();
5048 uint32_t BitWidth = Ty->getScalarSizeInBits();
5049 Constant *MaxSignedVal =
5050 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5051 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5052 Constant *Zero = Constant::getNullValue(Ty);
5053 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5054 }
5055
5056 return nullptr;
5057}
5058
5060 InstCombinerImpl &IC) {
5061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5062 // Normalize and operand as operand 0.
5063 CmpInst::Predicate Pred = I.getPredicate();
5064 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5065 std::swap(Op0, Op1);
5066 Pred = ICmpInst::getSwappedPredicate(Pred);
5067 }
5068
5069 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5070 return nullptr;
5071
5072 // (icmp (X & Y) u< X --> (X & Y) != X
5073 if (Pred == ICmpInst::ICMP_ULT)
5074 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5075
5076 // (icmp (X & Y) u>= X --> (X & Y) == X
5077 if (Pred == ICmpInst::ICMP_UGE)
5078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5079
5080 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5081 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5082 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5083 // so don't do this fold.
5084 if (!match(Op1, m_ImmConstant()))
5085 if (auto *NotOp1 =
5086 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5087 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5088 Constant::getAllOnesValue(Op1->getType()));
5089 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5090 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5091 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5092 Constant::getNullValue(Op1->getType()));
5093 }
5094
5095 if (!ICmpInst::isSigned(Pred))
5096 return nullptr;
5097
5098 KnownBits KnownY = IC.computeKnownBits(A, &I);
5099 // (X & NegY) spred X --> (X & NegY) upred X
5100 if (KnownY.isNegative())
5101 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5102
5103 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5104 return nullptr;
5105
5106 if (KnownY.isNonNegative())
5107 // (X & PosY) s<= X --> X s>= 0
5108 // (X & PosY) s> X --> X s< 0
5109 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5110 Constant::getNullValue(Op1->getType()));
5111
5113 // (NegX & Y) s<= NegX --> Y s< 0
5114 // (NegX & Y) s> NegX --> Y s>= 0
5116 Constant::getNullValue(A->getType()));
5117
5118 return nullptr;
5119}
5120
5122 InstCombinerImpl &IC) {
5123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5124
5125 // Normalize or operand as operand 0.
5126 CmpInst::Predicate Pred = I.getPredicate();
5127 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5128 std::swap(Op0, Op1);
5129 Pred = ICmpInst::getSwappedPredicate(Pred);
5130 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5131 return nullptr;
5132 }
5133
5134 // icmp (X | Y) u<= X --> (X | Y) == X
5135 if (Pred == ICmpInst::ICMP_ULE)
5136 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5137
5138 // icmp (X | Y) u> X --> (X | Y) != X
5139 if (Pred == ICmpInst::ICMP_UGT)
5140 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5141
5142 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5143 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5144 if (Value *NotOp1 = IC.getFreelyInverted(
5145 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5146 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5147 Constant::getNullValue(Op1->getType()));
5148 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5149 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5150 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5151 Constant::getAllOnesValue(Op1->getType()));
5152 }
5153 return nullptr;
5154}
5155
5157 InstCombinerImpl &IC) {
5158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5159 // Normalize xor operand as operand 0.
5160 CmpInst::Predicate Pred = I.getPredicate();
5161 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5162 std::swap(Op0, Op1);
5163 Pred = ICmpInst::getSwappedPredicate(Pred);
5164 }
5165 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5166 return nullptr;
5167
5168 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5169 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5170 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5171 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5173 if (PredOut != Pred && isKnownNonZero(A, Q))
5174 return new ICmpInst(PredOut, Op0, Op1);
5175
5176 // These transform work when A is negative.
5177 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5178 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5179 if (match(A, m_Negative())) {
5180 CmpInst::Predicate NewPred;
5181 switch (ICmpInst::getStrictPredicate(Pred)) {
5182 default:
5183 return nullptr;
5184 case ICmpInst::ICMP_SLT:
5185 case ICmpInst::ICMP_UGT:
5186 NewPred = ICmpInst::ICMP_SLT;
5187 break;
5188 case ICmpInst::ICMP_SGT:
5189 case ICmpInst::ICMP_ULT:
5190 NewPred = ICmpInst::ICMP_SGE;
5191 break;
5192 }
5193 Constant *Const = Constant::getNullValue(Op0->getType());
5194 return new ICmpInst(NewPred, Op0, Const);
5195 }
5196
5197 return nullptr;
5198}
5199
5200/// Return true if X is a multiple of C.
5201/// TODO: Handle non-power-of-2 factors.
5202static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5203 if (C.isOne())
5204 return true;
5205
5206 if (!C.isPowerOf2())
5207 return false;
5208
5209 return MaskedValueIsZero(X, C - 1, Q);
5210}
5211
5212/// Try to fold icmp (binop), X or icmp X, (binop).
5213/// TODO: A large part of this logic is duplicated in InstSimplify's
5214/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5215/// duplication.
5217 const SimplifyQuery &SQ) {
5218 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5220
5221 // Special logic for binary operators.
5224 if (!BO0 && !BO1)
5225 return nullptr;
5226
5227 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5228 return NewICmp;
5229
5230 const CmpInst::Predicate Pred = I.getPredicate();
5231 Value *X;
5232
5233 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5234 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5235 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5236 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5237 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5238 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5239 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5240 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5241 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5242
5243 {
5244 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5245 Constant *C;
5246 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5247 m_ImmConstant(C)))) &&
5248 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5250 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5251 }
5252 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5253 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5254 m_ImmConstant(C)))) &&
5255 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5257 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5258 }
5259 }
5260
5261 // (icmp eq/ne (X, -P2), INT_MIN)
5262 // -> (icmp slt/sge X, INT_MIN + P2)
5263 if (ICmpInst::isEquality(Pred) && BO0 &&
5264 match(I.getOperand(1), m_SignMask()) &&
5266 // Will Constant fold.
5267 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5268 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5270 BO0->getOperand(0), NewC);
5271 }
5272
5273 {
5274 // Similar to above: an unsigned overflow comparison may use offset + mask:
5275 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5276 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5277 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5278 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5279 BinaryOperator *BO;
5280 const APInt *C;
5281 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5282 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5284 CmpInst::Predicate NewPred =
5286 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5287 return new ICmpInst(NewPred, Op1, Zero);
5288 }
5289
5290 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5291 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5293 CmpInst::Predicate NewPred =
5295 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5296 return new ICmpInst(NewPred, Op0, Zero);
5297 }
5298 }
5299
5300 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5301 bool Op0HasNUW = false, Op1HasNUW = false;
5302 bool Op0HasNSW = false, Op1HasNSW = false;
5303 // Analyze the case when either Op0 or Op1 is an add instruction.
5304 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5305 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5306 bool &HasNSW, bool &HasNUW) -> bool {
5308 HasNUW = BO.hasNoUnsignedWrap();
5309 HasNSW = BO.hasNoSignedWrap();
5310 return ICmpInst::isEquality(Pred) ||
5311 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5312 (CmpInst::isSigned(Pred) && HasNSW);
5313 } else if (BO.getOpcode() == Instruction::Or) {
5314 HasNUW = true;
5315 HasNSW = true;
5316 return true;
5317 } else {
5318 return false;
5319 }
5320 };
5321 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5322
5323 if (BO0) {
5324 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5325 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5326 }
5327 if (BO1) {
5328 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5329 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5330 }
5331
5332 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5333 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5334 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5335 return new ICmpInst(Pred, A == Op1 ? B : A,
5336 Constant::getNullValue(Op1->getType()));
5337
5338 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5339 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5340 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5341 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5342 C == Op0 ? D : C);
5343
5344 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5345 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5346 NoOp1WrapProblem) {
5347 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5348 Value *Y, *Z;
5349 if (A == C) {
5350 // C + B == C + D -> B == D
5351 Y = B;
5352 Z = D;
5353 } else if (A == D) {
5354 // D + B == C + D -> B == C
5355 Y = B;
5356 Z = C;
5357 } else if (B == C) {
5358 // A + C == C + D -> A == D
5359 Y = A;
5360 Z = D;
5361 } else {
5362 assert(B == D);
5363 // A + D == C + D -> A == C
5364 Y = A;
5365 Z = C;
5366 }
5367 return new ICmpInst(Pred, Y, Z);
5368 }
5369
5370 if (ICmpInst::isRelational(Pred)) {
5371 // Return if both X and Y is divisible by Z/-Z.
5372 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5373 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5374 bool IsNegative) -> bool {
5375 const APInt *OffsetC;
5376 if (!match(Z, m_APInt(OffsetC)))
5377 return false;
5378
5379 // Fast path for Z == 1/-1.
5380 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5381 return true;
5382
5383 APInt C = *OffsetC;
5384 if (IsNegative)
5385 C.negate();
5386 // Note: -INT_MIN is also negative.
5387 if (!C.isStrictlyPositive())
5388 return false;
5389
5390 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5391 };
5392
5393 // TODO: The subtraction-related identities shown below also hold, but
5394 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5395 // wouldn't happen even if they were implemented.
5396 //
5397 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5398 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5399 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5400 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5401
5402 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5403 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5404 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5405 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5406 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5407 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5408 if (A && NoOp0WrapProblem &&
5409 ShareCommonDivisor(A, Op1, B,
5410 ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred)))
5412 Op1);
5413
5414 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5415 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5416 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5417 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5418 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5419 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5420 if (C && NoOp1WrapProblem &&
5421 ShareCommonDivisor(Op0, C, D,
5422 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5424 C);
5425 }
5426
5427 // if C1 has greater magnitude than C2:
5428 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5429 // s.t. C3 = C1 - C2
5430 //
5431 // if C2 has greater magnitude than C1:
5432 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5433 // s.t. C3 = C2 - C1
5434 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5435 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5436 const APInt *AP1, *AP2;
5437 // TODO: Support non-uniform vectors.
5438 // TODO: Allow poison passthrough if B or D's element is poison.
5439 if (match(B, m_APIntAllowPoison(AP1)) &&
5440 match(D, m_APIntAllowPoison(AP2)) &&
5441 AP1->isNegative() == AP2->isNegative()) {
5442 APInt AP1Abs = AP1->abs();
5443 APInt AP2Abs = AP2->abs();
5444 if (AP1Abs.uge(AP2Abs)) {
5445 APInt Diff = *AP1 - *AP2;
5446 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5447 Value *NewAdd = Builder.CreateAdd(
5448 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5449 return new ICmpInst(Pred, NewAdd, C);
5450 } else {
5451 APInt Diff = *AP2 - *AP1;
5452 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5453 Value *NewAdd = Builder.CreateAdd(
5454 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5455 return new ICmpInst(Pred, A, NewAdd);
5456 }
5457 }
5458 Constant *Cst1, *Cst2;
5459 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5460 ICmpInst::isEquality(Pred)) {
5461 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5462 Value *NewAdd = Builder.CreateAdd(C, Diff);
5463 return new ICmpInst(Pred, A, NewAdd);
5464 }
5465 }
5466
5467 // Analyze the case when either Op0 or Op1 is a sub instruction.
5468 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5469 A = nullptr;
5470 B = nullptr;
5471 C = nullptr;
5472 D = nullptr;
5473 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5474 A = BO0->getOperand(0);
5475 B = BO0->getOperand(1);
5476 }
5477 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5478 C = BO1->getOperand(0);
5479 D = BO1->getOperand(1);
5480 }
5481
5482 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5483 if (A == Op1 && NoOp0WrapProblem)
5484 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5485 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5486 if (C == Op0 && NoOp1WrapProblem)
5487 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5488
5489 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5490 // (A - B) u>/u<= A --> B u>/u<= A
5491 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5492 return new ICmpInst(Pred, B, A);
5493 // C u</u>= (C - D) --> C u</u>= D
5494 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5495 return new ICmpInst(Pred, C, D);
5496 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5497 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5498 isKnownNonZero(B, Q))
5500 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5501 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5502 isKnownNonZero(D, Q))
5504
5505 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5506 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5507 return new ICmpInst(Pred, A, C);
5508
5509 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5510 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5511 return new ICmpInst(Pred, D, B);
5512
5513 // icmp (0-X) < cst --> x > -cst
5514 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5515 Value *X;
5516 if (match(BO0, m_Neg(m_Value(X))))
5517 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5518 if (RHSC->isNotMinSignedValue())
5519 return new ICmpInst(I.getSwappedPredicate(), X,
5520 ConstantExpr::getNeg(RHSC));
5521 }
5522
5523 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5524 return R;
5525 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5526 return R;
5527
5528 {
5529 // Try to remove shared multiplier from comparison:
5530 // X * Z pred Y * Z
5531 Value *X, *Y, *Z;
5532 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5533 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5534 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5535 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5536 if (ICmpInst::isSigned(Pred)) {
5537 if (Op0HasNSW && Op1HasNSW) {
5538 KnownBits ZKnown = computeKnownBits(Z, &I);
5539 if (ZKnown.isStrictlyPositive())
5540 return new ICmpInst(Pred, X, Y);
5541 if (ZKnown.isNegative())
5542 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5544 SQ.getWithInstruction(&I));
5545 if (LessThan && match(LessThan, m_One()))
5546 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5547 Constant::getNullValue(Z->getType()));
5548 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5549 SQ.getWithInstruction(&I));
5550 if (GreaterThan && match(GreaterThan, m_One()))
5551 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5552 }
5553 } else {
5554 bool NonZero;
5555 if (ICmpInst::isEquality(Pred)) {
5556 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5557 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5558 isKnownNonEqual(X, Y, SQ))
5559 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5560
5561 KnownBits ZKnown = computeKnownBits(Z, &I);
5562 // if Z % 2 != 0
5563 // X * Z eq/ne Y * Z -> X eq/ne Y
5564 if (ZKnown.countMaxTrailingZeros() == 0)
5565 return new ICmpInst(Pred, X, Y);
5566 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5567 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5568 // X * Z eq/ne Y * Z -> X eq/ne Y
5569 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5570 return new ICmpInst(Pred, X, Y);
5571 } else
5572 NonZero = isKnownNonZero(Z, Q);
5573
5574 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5575 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5576 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5577 return new ICmpInst(Pred, X, Y);
5578 }
5579 }
5580 }
5581
5582 BinaryOperator *SRem = nullptr;
5583 // icmp (srem X, Y), Y
5584 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5585 SRem = BO0;
5586 // icmp Y, (srem X, Y)
5587 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5588 Op0 == BO1->getOperand(1))
5589 SRem = BO1;
5590 if (SRem) {
5591 // We don't check hasOneUse to avoid increasing register pressure because
5592 // the value we use is the same value this instruction was already using.
5593 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5594 default:
5595 break;
5596 case ICmpInst::ICMP_EQ:
5597 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5598 case ICmpInst::ICMP_NE:
5599 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5600 case ICmpInst::ICMP_SGT:
5601 case ICmpInst::ICMP_SGE:
5602 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5604 case ICmpInst::ICMP_SLT:
5605 case ICmpInst::ICMP_SLE:
5606 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5608 }
5609 }
5610
5611 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5612 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5613 BO0->getOperand(1) == BO1->getOperand(1)) {
5614 switch (BO0->getOpcode()) {
5615 default:
5616 break;
5617 case Instruction::Add:
5618 case Instruction::Sub:
5619 case Instruction::Xor: {
5620 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5621 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5622
5623 const APInt *C;
5624 if (match(BO0->getOperand(1), m_APInt(C))) {
5625 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5626 if (C->isSignMask()) {
5627 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5628 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5629 }
5630
5631 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5632 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5633 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5634 NewPred = I.getSwappedPredicate(NewPred);
5635 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5636 }
5637 }
5638 break;
5639 }
5640 case Instruction::Mul: {
5641 if (!I.isEquality())
5642 break;
5643
5644 const APInt *C;
5645 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5646 !C->isOne()) {
5647 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5648 // Mask = -1 >> count-trailing-zeros(C).
5649 if (unsigned TZs = C->countr_zero()) {
5650 Constant *Mask = ConstantInt::get(
5651 BO0->getType(),
5652 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5653 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5654 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5655 return new ICmpInst(Pred, And1, And2);
5656 }
5657 }
5658 break;
5659 }
5660 case Instruction::UDiv:
5661 case Instruction::LShr:
5662 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5663 break;
5664 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5665
5666 case Instruction::SDiv:
5667 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5668 !BO0->isExact() || !BO1->isExact())
5669 break;
5670 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5671
5672 case Instruction::AShr:
5673 if (!BO0->isExact() || !BO1->isExact())
5674 break;
5675 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5676
5677 case Instruction::Shl: {
5678 bool NUW = Op0HasNUW && Op1HasNUW;
5679 bool NSW = Op0HasNSW && Op1HasNSW;
5680 if (!NUW && !NSW)
5681 break;
5682 if (!NSW && I.isSigned())
5683 break;
5684 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5685 }
5686 }
5687 }
5688
5689 if (BO0) {
5690 // Transform A & (L - 1) `ult` L --> L != 0
5691 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5692 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5693
5694 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5695 auto *Zero = Constant::getNullValue(BO0->getType());
5696 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5697 }
5698 }
5699
5700 // For unsigned predicates / eq / ne:
5701 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5702 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5703 if (!ICmpInst::isSigned(Pred)) {
5704 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5705 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5706 Constant::getNullValue(Op1->getType()));
5707 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5708 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5709 Constant::getNullValue(Op0->getType()), Op0);
5710 }
5711
5713 return replaceInstUsesWith(I, V);
5714
5715 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5716 return R;
5717
5719 return replaceInstUsesWith(I, V);
5720
5722 return replaceInstUsesWith(I, V);
5723
5724 return nullptr;
5725}
5726
5727/// Fold icmp Pred min|max(X, Y), Z.
5730 Value *Z, CmpPredicate Pred) {
5731 Value *X = MinMax->getLHS();
5732 Value *Y = MinMax->getRHS();
5733 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5734 return nullptr;
5735 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5736 // Revert the transform signed pred -> unsigned pred
5737 // TODO: We can flip the signedness of predicate if both operands of icmp
5738 // are negative.
5739 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5740 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5742 } else
5743 return nullptr;
5744 }
5745 SimplifyQuery Q = SQ.getWithInstruction(&I);
5746 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5747 if (!Val)
5748 return std::nullopt;
5749 if (match(Val, m_One()))
5750 return true;
5751 if (match(Val, m_Zero()))
5752 return false;
5753 return std::nullopt;
5754 };
5755 // Remove samesign here since it is illegal to keep it when we speculatively
5756 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5757 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5758 // -46, -32)`. `X` is allowed to be non-negative here.
5759 Pred = Pred.dropSameSign();
5760 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5761 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5762 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5763 return nullptr;
5764 if (!CmpXZ.has_value()) {
5765 std::swap(X, Y);
5766 std::swap(CmpXZ, CmpYZ);
5767 }
5768
5769 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5770 if (CmpYZ.has_value())
5771 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5772 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5773 };
5774
5775 switch (Pred) {
5776 case ICmpInst::ICMP_EQ:
5777 case ICmpInst::ICMP_NE: {
5778 // If X == Z:
5779 // Expr Result
5780 // min(X, Y) == Z X <= Y
5781 // max(X, Y) == Z X >= Y
5782 // min(X, Y) != Z X > Y
5783 // max(X, Y) != Z X < Y
5784 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5785 ICmpInst::Predicate NewPred =
5786 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5787 if (Pred == ICmpInst::ICMP_NE)
5788 NewPred = ICmpInst::getInversePredicate(NewPred);
5789 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5790 }
5791 // Otherwise (X != Z):
5792 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5793 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5794 if (!MinMaxCmpXZ.has_value()) {
5795 std::swap(X, Y);
5796 std::swap(CmpXZ, CmpYZ);
5797 // Re-check pre-condition X != Z
5798 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5799 break;
5800 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5801 }
5802 if (!MinMaxCmpXZ.has_value())
5803 break;
5804 if (*MinMaxCmpXZ) {
5805 // Expr Fact Result
5806 // min(X, Y) == Z X < Z false
5807 // max(X, Y) == Z X > Z false
5808 // min(X, Y) != Z X < Z true
5809 // max(X, Y) != Z X > Z true
5810 return replaceInstUsesWith(
5811 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5812 } else {
5813 // Expr Fact Result
5814 // min(X, Y) == Z X > Z Y == Z
5815 // max(X, Y) == Z X < Z Y == Z
5816 // min(X, Y) != Z X > Z Y != Z
5817 // max(X, Y) != Z X < Z Y != Z
5818 return FoldIntoCmpYZ();
5819 }
5820 break;
5821 }
5822 case ICmpInst::ICMP_SLT:
5823 case ICmpInst::ICMP_ULT:
5824 case ICmpInst::ICMP_SLE:
5825 case ICmpInst::ICMP_ULE:
5826 case ICmpInst::ICMP_SGT:
5827 case ICmpInst::ICMP_UGT:
5828 case ICmpInst::ICMP_SGE:
5829 case ICmpInst::ICMP_UGE: {
5830 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5831 if (*CmpXZ) {
5832 if (IsSame) {
5833 // Expr Fact Result
5834 // min(X, Y) < Z X < Z true
5835 // min(X, Y) <= Z X <= Z true
5836 // max(X, Y) > Z X > Z true
5837 // max(X, Y) >= Z X >= Z true
5838 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5839 } else {
5840 // Expr Fact Result
5841 // max(X, Y) < Z X < Z Y < Z
5842 // max(X, Y) <= Z X <= Z Y <= Z
5843 // min(X, Y) > Z X > Z Y > Z
5844 // min(X, Y) >= Z X >= Z Y >= Z
5845 return FoldIntoCmpYZ();
5846 }
5847 } else {
5848 if (IsSame) {
5849 // Expr Fact Result
5850 // min(X, Y) < Z X >= Z Y < Z
5851 // min(X, Y) <= Z X > Z Y <= Z
5852 // max(X, Y) > Z X <= Z Y > Z
5853 // max(X, Y) >= Z X < Z Y >= Z
5854 return FoldIntoCmpYZ();
5855 } else {
5856 // Expr Fact Result
5857 // max(X, Y) < Z X >= Z false
5858 // max(X, Y) <= Z X > Z false
5859 // min(X, Y) > Z X <= Z false
5860 // min(X, Y) >= Z X < Z false
5861 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5862 }
5863 }
5864 break;
5865 }
5866 default:
5867 break;
5868 }
5869
5870 return nullptr;
5871}
5872
5873/// Match and fold patterns like:
5874/// icmp eq/ne X, min(max(X, Lo), Hi)
5875/// which represents a range check and can be represented as a ConstantRange.
5876///
5877/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5878/// (X - Lo) u< (Hi + 1 - Lo)
5879/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5880/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5882 MinMaxIntrinsic *Min) {
5883 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5884 return nullptr;
5885
5886 const APInt *Lo = nullptr, *Hi = nullptr;
5887 if (Min->isSigned()) {
5888 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
5889 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
5890 return nullptr;
5891 } else {
5892 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
5893 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
5894 return nullptr;
5895 }
5896
5899 APInt C, Offset;
5900 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5901 CR.getEquivalentICmp(Pred, C, Offset);
5902 else
5903 CR.inverse().getEquivalentICmp(Pred, C, Offset);
5904
5905 if (!Offset.isZero())
5906 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
5907
5908 return replaceInstUsesWith(
5909 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
5910}
5911
5912// Canonicalize checking for a power-of-2-or-zero value:
5914 InstCombiner::BuilderTy &Builder) {
5915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916 const CmpInst::Predicate Pred = I.getPredicate();
5917 Value *A = nullptr;
5918 bool CheckIs;
5919 if (I.isEquality()) {
5920 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5921 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5922 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5923 m_Deferred(A)))) ||
5924 !match(Op1, m_ZeroInt()))
5925 A = nullptr;
5926
5927 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5928 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5929 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5930 A = Op1;
5931 else if (match(Op1,
5933 A = Op0;
5934
5935 CheckIs = Pred == ICmpInst::ICMP_EQ;
5936 } else if (ICmpInst::isUnsigned(Pred)) {
5937 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5938 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5939
5940 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5942 m_Specific(Op1))))) {
5943 A = Op1;
5944 CheckIs = Pred == ICmpInst::ICMP_UGE;
5945 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5947 m_Specific(Op0))))) {
5948 A = Op0;
5949 CheckIs = Pred == ICmpInst::ICMP_ULE;
5950 }
5951 }
5952
5953 if (A) {
5954 Type *Ty = A->getType();
5955 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5956 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5957 ConstantInt::get(Ty, 2))
5958 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5959 ConstantInt::get(Ty, 1));
5960 }
5961
5962 return nullptr;
5963}
5964
5965/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
5966using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
5968 bool AllowRecursion) {
5970 if (!Inst || !Inst->hasOneUse())
5971 return;
5972
5973 switch (Inst->getOpcode()) {
5974 case Instruction::Add:
5975 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
5976 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
5977 break;
5978 case Instruction::Sub:
5979 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
5980 break;
5981 case Instruction::Xor:
5982 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
5983 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
5984 break;
5985 case Instruction::Shl:
5986 if (Inst->hasNoSignedWrap())
5987 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
5988 if (Inst->hasNoUnsignedWrap())
5989 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
5990 break;
5991 case Instruction::Select:
5992 if (AllowRecursion) {
5993 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
5994 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
5995 }
5996 break;
5997 default:
5998 break;
5999 }
6000}
6001
6003
6008
6010 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6011 }
6013 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6014 }
6015 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6017 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6018 }
6019 bool isValid() const { return Kind != OffsetKind::Invalid; }
6021 switch (Kind) {
6023 llvm_unreachable("Invalid offset result");
6024 case OffsetKind::Value:
6025 return V0;
6026 case OffsetKind::Select:
6027 return Builder.CreateSelect(
6028 V0, V1, V2, "", ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
6029 }
6030 llvm_unreachable("Unknown OffsetKind enum");
6031 }
6032};
6033
6034/// Offset both sides of an equality icmp to see if we can save some
6035/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6036/// Note: This operation should not introduce poison.
6038 InstCombiner::BuilderTy &Builder,
6039 const SimplifyQuery &SQ) {
6040 assert(I.isEquality() && "Expected an equality icmp");
6041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6042 if (!Op0->getType()->isIntOrIntVectorTy())
6043 return nullptr;
6044
6045 SmallVector<OffsetOp, 4> OffsetOps;
6046 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6047 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6048
6049 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6050 switch (BinOpc) {
6051 // V = shl nsw X, RHS => X = ashr V, RHS
6052 case Instruction::AShr: {
6053 const APInt *CV, *CRHS;
6054 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6055 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6057 return nullptr;
6058 break;
6059 }
6060 // V = shl nuw X, RHS => X = lshr V, RHS
6061 case Instruction::LShr: {
6062 const APInt *CV, *CRHS;
6063 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6064 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6066 return nullptr;
6067 break;
6068 }
6069 default:
6070 break;
6071 }
6072
6073 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6074 if (!Simplified)
6075 return nullptr;
6076 // Reject constant expressions as they don't simplify things.
6077 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6078 return nullptr;
6079 // Check if the transformation introduces poison.
6080 return impliesPoison(RHS, V) ? Simplified : nullptr;
6081 };
6082
6083 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6084 Value *RHS) -> OffsetResult {
6085 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6086 if (!Sel->hasOneUse())
6087 return OffsetResult::invalid();
6088 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6089 if (!TrueVal)
6090 return OffsetResult::invalid();
6091 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6092 if (!FalseVal)
6093 return OffsetResult::invalid();
6094 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6095 }
6096 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6097 return OffsetResult::value(Simplified);
6098 return OffsetResult::invalid();
6099 };
6100
6101 for (auto [BinOp, RHS] : OffsetOps) {
6102 auto BinOpc = static_cast<unsigned>(BinOp);
6103
6104 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6105 if (!Op0Result.isValid())
6106 continue;
6107 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6108 if (!Op1Result.isValid())
6109 continue;
6110
6111 Value *NewLHS = Op0Result.materialize(Builder);
6112 Value *NewRHS = Op1Result.materialize(Builder);
6113 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6114 }
6115
6116 return nullptr;
6117}
6118
6120 if (!I.isEquality())
6121 return nullptr;
6122
6123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6124 const CmpInst::Predicate Pred = I.getPredicate();
6125 Value *A, *B, *C, *D;
6126 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6127 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6128 Value *OtherVal = A == Op1 ? B : A;
6129 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6130 }
6131
6132 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6133 // A^c1 == C^c2 --> A == C^(c1^c2)
6134 ConstantInt *C1, *C2;
6135 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6136 Op1->hasOneUse()) {
6137 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6138 Value *Xor = Builder.CreateXor(C, NC);
6139 return new ICmpInst(Pred, A, Xor);
6140 }
6141
6142 // A^B == A^D -> B == D
6143 if (A == C)
6144 return new ICmpInst(Pred, B, D);
6145 if (A == D)
6146 return new ICmpInst(Pred, B, C);
6147 if (B == C)
6148 return new ICmpInst(Pred, A, D);
6149 if (B == D)
6150 return new ICmpInst(Pred, A, C);
6151 }
6152 }
6153
6154 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6155 // A == (A^B) -> B == 0
6156 Value *OtherVal = A == Op0 ? B : A;
6157 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6158 }
6159
6160 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6161 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6162 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6163 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6164
6165 if (A == C) {
6166 X = B;
6167 Y = D;
6168 Z = A;
6169 } else if (A == D) {
6170 X = B;
6171 Y = C;
6172 Z = A;
6173 } else if (B == C) {
6174 X = A;
6175 Y = D;
6176 Z = B;
6177 } else if (B == D) {
6178 X = A;
6179 Y = C;
6180 Z = B;
6181 }
6182
6183 if (X) {
6184 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6185 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6186 // instructions.
6187 const APInt *C0, *C1;
6188 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6189 (*C0 ^ *C1).isNegatedPowerOf2();
6190
6191 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6192 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6193 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6194 int UseCnt =
6195 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6196 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6197 if (XorIsNegP2 || UseCnt >= 2) {
6198 // Build (X^Y) & Z
6199 Op1 = Builder.CreateXor(X, Y);
6200 Op1 = Builder.CreateAnd(Op1, Z);
6201 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6202 }
6203 }
6204 }
6205
6206 {
6207 // Similar to above, but specialized for constant because invert is needed:
6208 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6209 Value *X, *Y;
6210 Constant *C;
6211 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6212 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6213 Value *Xor = Builder.CreateXor(X, Y);
6214 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6215 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6216 }
6217 }
6218
6219 if (match(Op1, m_ZExt(m_Value(A))) &&
6220 (Op0->hasOneUse() || Op1->hasOneUse())) {
6221 // (B & (Pow2C-1)) == zext A --> A == trunc B
6222 // (B & (Pow2C-1)) != zext A --> A != trunc B
6223 const APInt *MaskC;
6224 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6225 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6226 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6227 }
6228
6229 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6230 // For lshr and ashr pairs.
6231 const APInt *AP1, *AP2;
6232 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6233 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6234 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6235 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6236 if (*AP1 != *AP2)
6237 return nullptr;
6238 unsigned TypeBits = AP1->getBitWidth();
6239 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6240 if (ShAmt < TypeBits && ShAmt != 0) {
6241 ICmpInst::Predicate NewPred =
6243 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6244 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6245 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6246 }
6247 }
6248
6249 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6250 ConstantInt *Cst1;
6251 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6252 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6253 unsigned TypeBits = Cst1->getBitWidth();
6254 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6255 if (ShAmt < TypeBits && ShAmt != 0) {
6256 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6257 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6258 Value *And =
6259 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6260 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6261 }
6262 }
6263
6264 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6265 // "icmp (and X, mask), cst"
6266 uint64_t ShAmt = 0;
6267 if (Op0->hasOneUse() &&
6268 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6269 match(Op1, m_ConstantInt(Cst1)) &&
6270 // Only do this when A has multiple uses. This is most important to do
6271 // when it exposes other optimizations.
6272 !A->hasOneUse()) {
6273 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6274
6275 if (ShAmt < ASize) {
6276 APInt MaskV =
6278 MaskV <<= ShAmt;
6279
6280 APInt CmpV = Cst1->getValue().zext(ASize);
6281 CmpV <<= ShAmt;
6282
6283 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6284 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6285 }
6286 }
6287
6289 return ICmp;
6290
6291 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6292 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6293 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6294 // few steps of instcombine.
6295 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6296 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6298 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6299 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6301 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6302 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6304 Add, ConstantInt::get(A->getType(), C.shl(1)));
6305 }
6306
6307 // Canonicalize:
6308 // Assume B_Pow2 != 0
6309 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6310 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6311 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6312 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6313 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6315
6316 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6317 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6318 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6319 ConstantInt::getNullValue(Op1->getType()));
6320
6321 // Canonicalize:
6322 // icmp eq/ne X, OneUse(rotate-right(X))
6323 // -> icmp eq/ne X, rotate-left(X)
6324 // We generally try to convert rotate-right -> rotate-left, this just
6325 // canonicalizes another case.
6326 if (match(&I, m_c_ICmp(m_Value(A),
6328 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6329 return new ICmpInst(
6330 Pred, A,
6331 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6332
6333 // Canonicalize:
6334 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6335 Constant *Cst;
6338 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6339
6340 {
6341 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6342 auto m_Matcher =
6345 m_Sub(m_Value(B), m_Deferred(A)));
6346 std::optional<bool> IsZero = std::nullopt;
6347 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6348 m_Deferred(A))))
6349 IsZero = false;
6350 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6351 else if (match(&I,
6352 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6353 IsZero = true;
6354
6355 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6356 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6357 // -> (icmp eq/ne (and X, P2), 0)
6358 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6359 // -> (icmp eq/ne (and X, P2), P2)
6360 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6361 *IsZero ? A
6362 : ConstantInt::getNullValue(A->getType()));
6363 }
6364
6365 if (auto *Res = foldICmpEqualityWithOffset(
6366 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6367 return Res;
6368
6369 return nullptr;
6370}
6371
6373 ICmpInst::Predicate Pred = ICmp.getPredicate();
6374 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6375
6376 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6377 // The trunc masks high bits while the compare may effectively mask low bits.
6378 Value *X;
6379 const APInt *C;
6380 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6381 return nullptr;
6382
6383 // This matches patterns corresponding to tests of the signbit as well as:
6384 // (trunc X) pred C2 --> (X & Mask) == C
6385 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6386 /*AllowNonZeroC=*/true)) {
6387 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6388 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6389 return new ICmpInst(Res->Pred, And, C);
6390 }
6391
6392 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6393 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6394 if (II->getIntrinsicID() == Intrinsic::cttz ||
6395 II->getIntrinsicID() == Intrinsic::ctlz) {
6396 unsigned MaxRet = SrcBits;
6397 // If the "is_zero_poison" argument is set, then we know at least
6398 // one bit is set in the input, so the result is always at least one
6399 // less than the full bitwidth of that input.
6400 if (match(II->getArgOperand(1), m_One()))
6401 MaxRet--;
6402
6403 // Make sure the destination is wide enough to hold the largest output of
6404 // the intrinsic.
6405 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6406 if (Instruction *I =
6407 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6408 return I;
6409 }
6410 }
6411
6412 return nullptr;
6413}
6414
6416 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6417 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6418 Value *X;
6419 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6420 return nullptr;
6421
6422 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6423 bool IsSignedCmp = ICmp.isSigned();
6424
6425 // icmp Pred (ext X), (ext Y)
6426 Value *Y;
6427 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6428 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6429 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6430
6431 if (IsZext0 != IsZext1) {
6432 // If X and Y and both i1
6433 // (icmp eq/ne (zext X) (sext Y))
6434 // eq -> (icmp eq (or X, Y), 0)
6435 // ne -> (icmp ne (or X, Y), 0)
6436 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6437 Y->getType()->isIntOrIntVectorTy(1))
6438 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6439 Constant::getNullValue(X->getType()));
6440
6441 // If we have mismatched casts and zext has the nneg flag, we can
6442 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6443
6444 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6445 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6446
6447 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6448 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6449
6450 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6451 IsSignedExt = true;
6452 else
6453 return nullptr;
6454 }
6455
6456 // Not an extension from the same type?
6457 Type *XTy = X->getType(), *YTy = Y->getType();
6458 if (XTy != YTy) {
6459 // One of the casts must have one use because we are creating a new cast.
6460 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6461 return nullptr;
6462 // Extend the narrower operand to the type of the wider operand.
6463 CastInst::CastOps CastOpcode =
6464 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6465 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6466 X = Builder.CreateCast(CastOpcode, X, YTy);
6467 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6468 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6469 else
6470 return nullptr;
6471 }
6472
6473 // (zext X) == (zext Y) --> X == Y
6474 // (sext X) == (sext Y) --> X == Y
6475 if (ICmp.isEquality())
6476 return new ICmpInst(ICmp.getPredicate(), X, Y);
6477
6478 // A signed comparison of sign extended values simplifies into a
6479 // signed comparison.
6480 if (IsSignedCmp && IsSignedExt)
6481 return new ICmpInst(ICmp.getPredicate(), X, Y);
6482
6483 // The other three cases all fold into an unsigned comparison.
6484 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6485 }
6486
6487 // Below here, we are only folding a compare with constant.
6488 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6489 if (!C)
6490 return nullptr;
6491
6492 // If a lossless truncate is possible...
6493 Type *SrcTy = CastOp0->getSrcTy();
6494 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6495 if (Res) {
6496 if (ICmp.isEquality())
6497 return new ICmpInst(ICmp.getPredicate(), X, Res);
6498
6499 // A signed comparison of sign extended values simplifies into a
6500 // signed comparison.
6501 if (IsSignedExt && IsSignedCmp)
6502 return new ICmpInst(ICmp.getPredicate(), X, Res);
6503
6504 // The other three cases all fold into an unsigned comparison.
6505 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6506 }
6507
6508 // The re-extended constant changed, partly changed (in the case of a vector),
6509 // or could not be determined to be equal (in the case of a constant
6510 // expression), so the constant cannot be represented in the shorter type.
6511 // All the cases that fold to true or false will have already been handled
6512 // by simplifyICmpInst, so only deal with the tricky case.
6513 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6514 return nullptr;
6515
6516 // Is source op positive?
6517 // icmp ult (sext X), C --> icmp sgt X, -1
6518 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6520
6521 // Is source op negative?
6522 // icmp ugt (sext X), C --> icmp slt X, 0
6523 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6525}
6526
6527/// Handle icmp (cast x), (cast or constant).
6529 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6530 // icmp compares only pointer's value.
6531 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6532 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6533 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6534 if (SimplifiedOp0 || SimplifiedOp1)
6535 return new ICmpInst(ICmp.getPredicate(),
6536 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6537 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6538
6539 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6540 Value *Op1 = ICmp.getOperand(1);
6541 if (!CastOp0)
6542 return nullptr;
6543 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6544 return nullptr;
6545
6546 Value *Op0Src = CastOp0->getOperand(0);
6547 Type *SrcTy = CastOp0->getSrcTy();
6548 Type *DestTy = CastOp0->getDestTy();
6549
6550 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6551 // integer type is the same size as the pointer type.
6552 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6553 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6554 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6555 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6556 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6557 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6558 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6559 };
6560 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6561 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6562 Value *NewOp1 = nullptr;
6563 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6564 NewOp1 = PtrToIntOp1->getOperand(0);
6565 HasPtrToInt = true;
6566 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6567 NewOp1 = PtrToAddrOp1->getOperand(0);
6568 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6569 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6570 }
6571
6572 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6573 // check PtrWidth.
6574 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6575 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6576 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6577 }
6578
6579 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6580 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6581 CompatibleSizes(DestTy, SrcTy)) {
6582 Value *NewOp1 = nullptr;
6583 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6584 Value *IntSrc = IntToPtrOp1->getOperand(0);
6585 if (IntSrc->getType() == Op0Src->getType())
6586 NewOp1 = IntToPtrOp1->getOperand(0);
6587 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6588 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6589 }
6590
6591 if (NewOp1)
6592 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6593 }
6594
6595 if (Instruction *R = foldICmpWithTrunc(ICmp))
6596 return R;
6597
6598 return foldICmpWithZextOrSext(ICmp);
6599}
6600
6602 bool IsSigned) {
6603 switch (BinaryOp) {
6604 default:
6605 llvm_unreachable("Unsupported binary op");
6606 case Instruction::Add:
6607 case Instruction::Sub:
6608 return match(RHS, m_Zero());
6609 case Instruction::Mul:
6610 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6611 match(RHS, m_One());
6612 }
6613}
6614
6617 bool IsSigned, Value *LHS, Value *RHS,
6618 Instruction *CxtI) const {
6619 switch (BinaryOp) {
6620 default:
6621 llvm_unreachable("Unsupported binary op");
6622 case Instruction::Add:
6623 if (IsSigned)
6624 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6625 else
6626 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6627 case Instruction::Sub:
6628 if (IsSigned)
6629 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6630 else
6631 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6632 case Instruction::Mul:
6633 if (IsSigned)
6634 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6635 else
6636 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6637 }
6638}
6639
6640bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6641 bool IsSigned, Value *LHS,
6642 Value *RHS, Instruction &OrigI,
6643 Value *&Result,
6644 Constant *&Overflow) {
6645 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6646 std::swap(LHS, RHS);
6647
6648 // If the overflow check was an add followed by a compare, the insertion point
6649 // may be pointing to the compare. We want to insert the new instructions
6650 // before the add in case there are uses of the add between the add and the
6651 // compare.
6652 Builder.SetInsertPoint(&OrigI);
6653
6654 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6655 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6656 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6657
6658 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6659 Result = LHS;
6660 Overflow = ConstantInt::getFalse(OverflowTy);
6661 return true;
6662 }
6663
6664 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6666 return false;
6669 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6670 Result->takeName(&OrigI);
6671 Overflow = ConstantInt::getTrue(OverflowTy);
6672 return true;
6674 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6675 Result->takeName(&OrigI);
6676 Overflow = ConstantInt::getFalse(OverflowTy);
6677 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6678 if (IsSigned)
6679 Inst->setHasNoSignedWrap();
6680 else
6681 Inst->setHasNoUnsignedWrap();
6682 }
6683 return true;
6684 }
6685
6686 llvm_unreachable("Unexpected overflow result");
6687}
6688
6689/// Recognize and process idiom involving test for multiplication
6690/// overflow.
6691///
6692/// The caller has matched a pattern of the form:
6693/// I = cmp u (mul(zext A, zext B), V
6694/// The function checks if this is a test for overflow and if so replaces
6695/// multiplication with call to 'mul.with.overflow' intrinsic.
6696///
6697/// \param I Compare instruction.
6698/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6699/// the compare instruction. Must be of integer type.
6700/// \param OtherVal The other argument of compare instruction.
6701/// \returns Instruction which must replace the compare instruction, NULL if no
6702/// replacement required.
6704 const APInt *OtherVal,
6705 InstCombinerImpl &IC) {
6706 // Don't bother doing this transformation for pointers, don't do it for
6707 // vectors.
6708 if (!isa<IntegerType>(MulVal->getType()))
6709 return nullptr;
6710
6711 auto *MulInstr = dyn_cast<Instruction>(MulVal);
6712 if (!MulInstr)
6713 return nullptr;
6714 assert(MulInstr->getOpcode() == Instruction::Mul);
6715
6716 auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
6717 *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
6718 assert(LHS->getOpcode() == Instruction::ZExt);
6719 assert(RHS->getOpcode() == Instruction::ZExt);
6720 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6721
6722 // Calculate type and width of the result produced by mul.with.overflow.
6723 Type *TyA = A->getType(), *TyB = B->getType();
6724 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6725 WidthB = TyB->getPrimitiveSizeInBits();
6726 unsigned MulWidth;
6727 Type *MulType;
6728 if (WidthB > WidthA) {
6729 MulWidth = WidthB;
6730 MulType = TyB;
6731 } else {
6732 MulWidth = WidthA;
6733 MulType = TyA;
6734 }
6735
6736 // In order to replace the original mul with a narrower mul.with.overflow,
6737 // all uses must ignore upper bits of the product. The number of used low
6738 // bits must be not greater than the width of mul.with.overflow.
6739 if (MulVal->hasNUsesOrMore(2))
6740 for (User *U : MulVal->users()) {
6741 if (U == &I)
6742 continue;
6743 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6744 // Check if truncation ignores bits above MulWidth.
6745 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6746 if (TruncWidth > MulWidth)
6747 return nullptr;
6748 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6749 // Check if AND ignores bits above MulWidth.
6750 if (BO->getOpcode() != Instruction::And)
6751 return nullptr;
6752 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6753 const APInt &CVal = CI->getValue();
6754 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6755 return nullptr;
6756 } else {
6757 // In this case we could have the operand of the binary operation
6758 // being defined in another block, and performing the replacement
6759 // could break the dominance relation.
6760 return nullptr;
6761 }
6762 } else {
6763 // Other uses prohibit this transformation.
6764 return nullptr;
6765 }
6766 }
6767
6768 // Recognize patterns
6769 switch (I.getPredicate()) {
6770 case ICmpInst::ICMP_UGT: {
6771 // Recognize pattern:
6772 // mulval = mul(zext A, zext B)
6773 // cmp ugt mulval, max
6774 APInt MaxVal = APInt::getMaxValue(MulWidth);
6775 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6776 if (MaxVal.eq(*OtherVal))
6777 break; // Recognized
6778 return nullptr;
6779 }
6780
6781 case ICmpInst::ICMP_ULT: {
6782 // Recognize pattern:
6783 // mulval = mul(zext A, zext B)
6784 // cmp ule mulval, max + 1
6785 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
6786 if (MaxVal.eq(*OtherVal))
6787 break; // Recognized
6788 return nullptr;
6789 }
6790
6791 default:
6792 return nullptr;
6793 }
6794
6795 InstCombiner::BuilderTy &Builder = IC.Builder;
6796 Builder.SetInsertPoint(MulInstr);
6797
6798 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6799 Value *MulA = A, *MulB = B;
6800 if (WidthA < MulWidth)
6801 MulA = Builder.CreateZExt(A, MulType);
6802 if (WidthB < MulWidth)
6803 MulB = Builder.CreateZExt(B, MulType);
6804 Value *Call =
6805 Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, MulType,
6806 {MulA, MulB}, /*FMFSource=*/nullptr, "umul");
6807 IC.addToWorklist(MulInstr);
6808
6809 // If there are uses of mul result other than the comparison, we know that
6810 // they are truncation or binary AND. Change them to use result of
6811 // mul.with.overflow and adjust properly mask/size.
6812 if (MulVal->hasNUsesOrMore(2)) {
6813 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
6814 for (User *U : make_early_inc_range(MulVal->users())) {
6815 if (U == &I)
6816 continue;
6817 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6818 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6819 IC.replaceInstUsesWith(*TI, Mul);
6820 else
6821 TI->setOperand(0, Mul);
6822 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6823 assert(BO->getOpcode() == Instruction::And);
6824 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6825 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6826 APInt ShortMask = CI->getValue().trunc(MulWidth);
6827 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
6828 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6829 IC.replaceInstUsesWith(*BO, Zext);
6830 } else {
6831 llvm_unreachable("Unexpected Binary operation");
6832 }
6834 }
6835 }
6836
6837 // The original icmp gets replaced with the overflow value, maybe inverted
6838 // depending on predicate.
6839 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6840 Value *Res = Builder.CreateExtractValue(Call, 1);
6841 return BinaryOperator::CreateNot(Res);
6842 }
6843
6844 return ExtractValueInst::Create(Call, 1);
6845}
6846
6847/// When performing a comparison against a constant, it is possible that not all
6848/// the bits in the LHS are demanded. This helper method computes the mask that
6849/// IS demanded.
6851 const APInt *RHS;
6852 if (!match(I.getOperand(1), m_APInt(RHS)))
6854
6855 // If this is a normal comparison, it demands all bits. If it is a sign bit
6856 // comparison, it only demands the sign bit.
6857 bool UnusedBit;
6858 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6860
6861 switch (I.getPredicate()) {
6862 // For a UGT comparison, we don't care about any bits that
6863 // correspond to the trailing ones of the comparand. The value of these
6864 // bits doesn't impact the outcome of the comparison, because any value
6865 // greater than the RHS must differ in a bit higher than these due to carry.
6866 case ICmpInst::ICMP_UGT:
6867 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6868
6869 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6870 // Any value less than the RHS must differ in a higher bit because of carries.
6871 case ICmpInst::ICMP_ULT:
6872 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6873
6874 default:
6876 }
6877}
6878
6879/// Check that one use is in the same block as the definition and all
6880/// other uses are in blocks dominated by a given block.
6881///
6882/// \param DI Definition
6883/// \param UI Use
6884/// \param DB Block that must dominate all uses of \p DI outside
6885/// the parent block
6886/// \return true when \p UI is the only use of \p DI in the parent block
6887/// and all other uses of \p DI are in blocks dominated by \p DB.
6888///
6890 const Instruction *UI,
6891 const BasicBlock *DB) const {
6892 assert(DI && UI && "Instruction not defined\n");
6893 // Ignore incomplete definitions.
6894 if (!DI->getParent())
6895 return false;
6896 // DI and UI must be in the same block.
6897 if (DI->getParent() != UI->getParent())
6898 return false;
6899 // Protect from self-referencing blocks.
6900 if (DI->getParent() == DB)
6901 return false;
6902 for (const User *U : DI->users()) {
6903 auto *Usr = cast<Instruction>(U);
6904 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6905 return false;
6906 }
6907 return true;
6908}
6909
6910/// Return true when the instruction sequence within a block is select-cmp-br.
6912 const BasicBlock *BB = SI->getParent();
6913 if (!BB)
6914 return false;
6916 if (!BI)
6917 return false;
6918 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
6919 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
6920 return false;
6921 return true;
6922}
6923
6924/// True when a select result is replaced by one of its operands
6925/// in select-icmp sequence. This will eventually result in the elimination
6926/// of the select.
6927///
6928/// \param SI Select instruction
6929/// \param Icmp Compare instruction
6930/// \param SIOpd Operand that replaces the select
6931///
6932/// Notes:
6933/// - The replacement is global and requires dominator information
6934/// - The caller is responsible for the actual replacement
6935///
6936/// Example:
6937///
6938/// entry:
6939/// %4 = select i1 %3, %C* %0, %C* null
6940/// %5 = icmp eq %C* %4, null
6941/// br i1 %5, label %9, label %7
6942/// ...
6943/// ; <label>:7 ; preds = %entry
6944/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6945/// ...
6946///
6947/// can be transformed to
6948///
6949/// %5 = icmp eq %C* %0, null
6950/// %6 = select i1 %3, i1 %5, i1 true
6951/// br i1 %6, label %9, label %7
6952/// ...
6953/// ; <label>:7 ; preds = %entry
6954/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
6955///
6956/// Similar when the first operand of the select is a constant or/and
6957/// the compare is for not equal rather than equal.
6958///
6959/// NOTE: The function is only called when the select and compare constants
6960/// are equal, the optimization can work only for EQ predicates. This is not a
6961/// major restriction since a NE compare should be 'normalized' to an equal
6962/// compare, which usually happens in the combiner and test case
6963/// select-cmp-br.ll checks for it.
6965 const ICmpInst *Icmp,
6966 const unsigned SIOpd) {
6967 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6969 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
6970 // The check for the single predecessor is not the best that can be
6971 // done. But it protects efficiently against cases like when SI's
6972 // home block has two successors, Succ and Succ1, and Succ1 predecessor
6973 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6974 // replaced can be reached on either path. So the uniqueness check
6975 // guarantees that the path all uses of SI (outside SI's parent) are on
6976 // is disjoint from all other paths out of SI. But that information
6977 // is more expensive to compute, and the trade-off here is in favor
6978 // of compile-time. It should also be noticed that we check for a single
6979 // predecessor and not only uniqueness. This to handle the situation when
6980 // Succ and Succ1 points to the same basic block.
6981 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
6982 NumSel++;
6983 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
6984 return true;
6985 }
6986 }
6987 return false;
6988}
6989
6990/// Try to fold the comparison based on range information we can get by checking
6991/// whether bits are known to be zero or one in the inputs.
6993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6994 Type *Ty = Op0->getType();
6995 ICmpInst::Predicate Pred = I.getPredicate();
6996
6997 // Get scalar or pointer size.
6998 unsigned BitWidth = Ty->isIntOrIntVectorTy()
6999 ? Ty->getScalarSizeInBits()
7000 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7001
7002 if (!BitWidth)
7003 return nullptr;
7004
7005 KnownBits Op0Known(BitWidth);
7006 KnownBits Op1Known(BitWidth);
7007
7008 {
7009 // Don't use dominating conditions when folding icmp using known bits. This
7010 // may convert signed into unsigned predicates in ways that other passes
7011 // (especially IndVarSimplify) may not be able to reliably undo.
7012 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7014 Op0Known, Q))
7015 return &I;
7016
7017 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7018 return &I;
7019 }
7020
7021 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7022 return new ICmpInst(
7023 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7024 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7025 return new ICmpInst(
7026 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7027
7028 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7029 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7030
7031 // Given the known and unknown bits, compute a range that the LHS could be
7032 // in. Compute the Min, Max and RHS values based on the known bits. For the
7033 // EQ and NE we use unsigned values.
7034 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7035 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7036 if (I.isSigned()) {
7037 Op0Min = Op0Known.getSignedMinValue();
7038 Op0Max = Op0Known.getSignedMaxValue();
7039 Op1Min = Op1Known.getSignedMinValue();
7040 Op1Max = Op1Known.getSignedMaxValue();
7041 } else {
7042 Op0Min = Op0Known.getMinValue();
7043 Op0Max = Op0Known.getMaxValue();
7044 Op1Min = Op1Known.getMinValue();
7045 Op1Max = Op1Known.getMaxValue();
7046 }
7047
7048 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7049 // min/max canonical compare with some other compare. That could lead to
7050 // conflict with select canonicalization and infinite looping.
7051 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7052 auto isMinMaxCmp = [&](Instruction &Cmp) {
7053 if (!Cmp.hasOneUse())
7054 return false;
7055 Value *A, *B;
7056 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7058 return false;
7059 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7060 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7061 };
7062 if (!isMinMaxCmp(I)) {
7063 switch (Pred) {
7064 default:
7065 break;
7066 case ICmpInst::ICMP_ULT: {
7067 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7068 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7069 const APInt *CmpC;
7070 if (match(Op1, m_APInt(CmpC))) {
7071 // A <u C -> A == C-1 if min(A)+1 == C
7072 if (*CmpC == Op0Min + 1)
7073 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7074 ConstantInt::get(Op1->getType(), *CmpC - 1));
7075 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7076 // exceeds the log2 of C.
7077 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7079 Constant::getNullValue(Op1->getType()));
7080 }
7081 break;
7082 }
7083 case ICmpInst::ICMP_UGT: {
7084 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7085 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7086 const APInt *CmpC;
7087 if (match(Op1, m_APInt(CmpC))) {
7088 // A >u C -> A == C+1 if max(a)-1 == C
7089 if (*CmpC == Op0Max - 1)
7090 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7091 ConstantInt::get(Op1->getType(), *CmpC + 1));
7092 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7093 // exceeds the log2 of C.
7094 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7095 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7096 Constant::getNullValue(Op1->getType()));
7097 }
7098 break;
7099 }
7100 case ICmpInst::ICMP_SLT: {
7101 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7102 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7103 const APInt *CmpC;
7104 if (match(Op1, m_APInt(CmpC))) {
7105 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7106 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7107 ConstantInt::get(Op1->getType(), *CmpC - 1));
7108 }
7109 break;
7110 }
7111 case ICmpInst::ICMP_SGT: {
7112 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7113 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7114 const APInt *CmpC;
7115 if (match(Op1, m_APInt(CmpC))) {
7116 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7117 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7118 ConstantInt::get(Op1->getType(), *CmpC + 1));
7119 }
7120 break;
7121 }
7122 }
7123 }
7124
7125 // Based on the range information we know about the LHS, see if we can
7126 // simplify this comparison. For example, (x&4) < 8 is always true.
7127 switch (Pred) {
7128 default:
7129 break;
7130 case ICmpInst::ICMP_EQ:
7131 case ICmpInst::ICMP_NE: {
7132 // If all bits are known zero except for one, then we know at most one bit
7133 // is set. If the comparison is against zero, then this is a check to see if
7134 // *that* bit is set.
7135 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7136 if (Op1Known.isZero()) {
7137 // If the LHS is an AND with the same constant, look through it.
7138 Value *LHS = nullptr;
7139 const APInt *LHSC;
7140 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7141 *LHSC != Op0KnownZeroInverted)
7142 LHS = Op0;
7143
7144 Value *X;
7145 const APInt *C1;
7146 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7147 Type *XTy = X->getType();
7148 unsigned Log2C1 = C1->countr_zero();
7149 APInt C2 = Op0KnownZeroInverted;
7150 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7151 if (C2Pow2.isPowerOf2()) {
7152 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7153 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7154 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7155 unsigned Log2C2 = C2Pow2.countr_zero();
7156 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7157 auto NewPred =
7159 return new ICmpInst(NewPred, X, CmpC);
7160 }
7161 }
7162 }
7163
7164 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7165 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7166 (Op0Known & Op1Known) == Op0Known)
7167 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7168 ConstantInt::getNullValue(Op1->getType()));
7169 break;
7170 }
7171 case ICmpInst::ICMP_SGE:
7172 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7173 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7174 break;
7175 case ICmpInst::ICMP_SLE:
7176 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7177 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7178 break;
7179 case ICmpInst::ICMP_UGE:
7180 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7181 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7182 break;
7183 case ICmpInst::ICMP_ULE:
7184 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7185 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7186 break;
7187 }
7188
7189 // Turn a signed comparison into an unsigned one if both operands are known to
7190 // have the same sign. Set samesign if possible (except for equality
7191 // predicates).
7192 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7193 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7194 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7195 I.setPredicate(I.getUnsignedPredicate());
7196 I.setSameSign();
7197 return &I;
7198 }
7199
7200 return nullptr;
7201}
7202
7203/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7204/// then try to reduce patterns based on that limit.
7206 Value *X, *Y;
7207 CmpPredicate Pred;
7208
7209 // X must be 0 and bool must be true for "ULT":
7210 // X <u (zext i1 Y) --> (X == 0) & Y
7211 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7212 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7213 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7214
7215 // X must be 0 or bool must be true for "ULE":
7216 // X <=u (sext i1 Y) --> (X == 0) | Y
7217 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7218 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7219 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7220
7221 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7222 CmpPredicate Pred1, Pred2;
7223 const APInt *C;
7224 Instruction *ExtI;
7225 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7228 m_APInt(C)))))) &&
7229 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7230 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7231 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7232 auto CreateRangeCheck = [&] {
7233 Value *CmpV1 =
7234 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7235 Value *CmpV2 = Builder.CreateICmp(
7236 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7238 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7239 CmpV1, CmpV2);
7240 };
7241 if (C->isZero()) {
7242 if (Pred2 == ICmpInst::ICMP_EQ) {
7243 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7244 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7245 return replaceInstUsesWith(
7246 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7247 } else if (!IsSExt || HasOneUse) {
7248 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7249 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7250 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7251 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7252 return CreateRangeCheck();
7253 }
7254 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7255 if (Pred2 == ICmpInst::ICMP_NE) {
7256 // icmp eq X, (zext (icmp ne X, 1)) --> false
7257 // icmp ne X, (zext (icmp ne X, 1)) --> true
7258 // icmp eq X, (sext (icmp ne X, -1)) --> false
7259 // icmp ne X, (sext (icmp ne X, -1)) --> true
7260 return replaceInstUsesWith(
7261 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7262 } else if (!IsSExt || HasOneUse) {
7263 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7264 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7265 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7266 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7267 return CreateRangeCheck();
7268 }
7269 } else {
7270 // when C != 0 && C != 1:
7271 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7272 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7273 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7274 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7275 // when C != 0 && C != -1:
7276 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7277 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7278 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7279 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7280 return ICmpInst::Create(
7281 Instruction::ICmp, Pred1, X,
7282 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7283 ? (IsSExt ? -1 : 1)
7284 : 0));
7285 }
7286 }
7287
7288 return nullptr;
7289}
7290
7291/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7292/// it into the appropriate icmp lt or icmp gt instruction. This transform
7293/// allows them to be folded in visitICmpInst.
7295 ICmpInst::Predicate Pred = I.getPredicate();
7296 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7298 return nullptr;
7299
7300 Value *Op0 = I.getOperand(0);
7301 Value *Op1 = I.getOperand(1);
7302 auto *Op1C = dyn_cast<Constant>(Op1);
7303 if (!Op1C)
7304 return nullptr;
7305
7306 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7307 if (!FlippedStrictness)
7308 return nullptr;
7309
7310 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7311}
7312
7313/// If we have a comparison with a non-canonical predicate, if we can update
7314/// all the users, invert the predicate and adjust all the users.
7316 // Is the predicate already canonical?
7317 CmpInst::Predicate Pred = I.getPredicate();
7319 return nullptr;
7320
7321 // Can all users be adjusted to predicate inversion?
7322 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7323 return nullptr;
7324
7325 // Ok, we can canonicalize comparison!
7326 // Let's first invert the comparison's predicate.
7327 I.setPredicate(CmpInst::getInversePredicate(Pred));
7328 I.setName(I.getName() + ".not");
7329
7330 // And, adapt users.
7332
7333 return &I;
7334}
7335
7336/// Integer compare with boolean values can always be turned into bitwise ops.
7338 InstCombiner::BuilderTy &Builder) {
7339 Value *A = I.getOperand(0), *B = I.getOperand(1);
7340 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7341
7342 // A boolean compared to true/false can be simplified to Op0/true/false in
7343 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7344 // Cases not handled by InstSimplify are always 'not' of Op0.
7345 if (match(B, m_Zero())) {
7346 switch (I.getPredicate()) {
7347 case CmpInst::ICMP_EQ: // A == 0 -> !A
7348 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7349 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7351 default:
7352 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7353 }
7354 } else if (match(B, m_One())) {
7355 switch (I.getPredicate()) {
7356 case CmpInst::ICMP_NE: // A != 1 -> !A
7357 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7358 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7360 default:
7361 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7362 }
7363 }
7364
7365 switch (I.getPredicate()) {
7366 default:
7367 llvm_unreachable("Invalid icmp instruction!");
7368 case ICmpInst::ICMP_EQ:
7369 // icmp eq i1 A, B -> ~(A ^ B)
7370 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7371
7372 case ICmpInst::ICMP_NE:
7373 // icmp ne i1 A, B -> A ^ B
7374 return BinaryOperator::CreateXor(A, B);
7375
7376 case ICmpInst::ICMP_UGT:
7377 // icmp ugt -> icmp ult
7378 std::swap(A, B);
7379 [[fallthrough]];
7380 case ICmpInst::ICMP_ULT:
7381 // icmp ult i1 A, B -> ~A & B
7382 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7383
7384 case ICmpInst::ICMP_SGT:
7385 // icmp sgt -> icmp slt
7386 std::swap(A, B);
7387 [[fallthrough]];
7388 case ICmpInst::ICMP_SLT:
7389 // icmp slt i1 A, B -> A & ~B
7390 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7391
7392 case ICmpInst::ICMP_UGE:
7393 // icmp uge -> icmp ule
7394 std::swap(A, B);
7395 [[fallthrough]];
7396 case ICmpInst::ICMP_ULE:
7397 // icmp ule i1 A, B -> ~A | B
7398 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7399
7400 case ICmpInst::ICMP_SGE:
7401 // icmp sge -> icmp sle
7402 std::swap(A, B);
7403 [[fallthrough]];
7404 case ICmpInst::ICMP_SLE:
7405 // icmp sle i1 A, B -> A | ~B
7406 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7407 }
7408}
7409
7410// Transform pattern like:
7411// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7412// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7413// Into:
7414// (X l>> Y) != 0
7415// (X l>> Y) == 0
7417 InstCombiner::BuilderTy &Builder) {
7418 CmpPredicate Pred, NewPred;
7419 Value *X, *Y;
7420 if (match(&Cmp,
7421 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7422 switch (Pred) {
7423 case ICmpInst::ICMP_ULE:
7424 NewPred = ICmpInst::ICMP_NE;
7425 break;
7426 case ICmpInst::ICMP_UGT:
7427 NewPred = ICmpInst::ICMP_EQ;
7428 break;
7429 default:
7430 return nullptr;
7431 }
7432 } else if (match(&Cmp, m_c_ICmp(Pred,
7435 m_Add(m_Shl(m_One(), m_Value(Y)),
7436 m_AllOnes()))),
7437 m_Value(X)))) {
7438 // The variant with 'add' is not canonical, (the variant with 'not' is)
7439 // we only get it because it has extra uses, and can't be canonicalized,
7440
7441 switch (Pred) {
7442 case ICmpInst::ICMP_ULT:
7443 NewPred = ICmpInst::ICMP_NE;
7444 break;
7445 case ICmpInst::ICMP_UGE:
7446 NewPred = ICmpInst::ICMP_EQ;
7447 break;
7448 default:
7449 return nullptr;
7450 }
7451 } else
7452 return nullptr;
7453
7454 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7455 Constant *Zero = Constant::getNullValue(NewX->getType());
7456 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7457}
7458
7460 InstCombiner::BuilderTy &Builder) {
7461 const CmpInst::Predicate Pred = Cmp.getPredicate();
7462 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7463 Value *V1, *V2;
7464
7465 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7466 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7467 if (auto *I = dyn_cast<Instruction>(V))
7468 I->copyIRFlags(&Cmp);
7469 Module *M = Cmp.getModule();
7471 M, Intrinsic::vector_reverse, V->getType());
7472 return CallInst::Create(F, V);
7473 };
7474
7475 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7476 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7477 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7478 (LHS->hasOneUse() || RHS->hasOneUse()))
7479 return createCmpReverse(Pred, V1, V2);
7480
7481 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7482 if (LHS->hasOneUse() && isSplatValue(RHS))
7483 return createCmpReverse(Pred, V1, RHS);
7484 }
7485 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7486 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7487 return createCmpReverse(Pred, LHS, V2);
7488
7489 ArrayRef<int> M;
7490 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7491 return nullptr;
7492
7493 // If both arguments of the cmp are shuffles that use the same mask and
7494 // shuffle within a single vector, move the shuffle after the cmp:
7495 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7496 Type *V1Ty = V1->getType();
7497 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7498 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7499 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7500 return new ShuffleVectorInst(NewCmp, M);
7501 }
7502
7503 // Try to canonicalize compare with splatted operand and splat constant.
7504 // TODO: We could generalize this for more than splats. See/use the code in
7505 // InstCombiner::foldVectorBinop().
7506 Constant *C;
7507 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7508 return nullptr;
7509
7510 // Length-changing splats are ok, so adjust the constants as needed:
7511 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7512 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7513 int MaskSplatIndex;
7514 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7515 // We allow poison in matching, but this transform removes it for safety.
7516 // Demanded elements analysis should be able to recover some/all of that.
7517 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7518 ScalarC);
7519 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7520 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7521 return new ShuffleVectorInst(NewCmp, NewM);
7522 }
7523
7524 return nullptr;
7525}
7526
7527// extract(uadd.with.overflow(A, B), 0) ult A
7528// -> extract(uadd.with.overflow(A, B), 1)
7530 CmpInst::Predicate Pred = I.getPredicate();
7531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7532
7533 Value *UAddOv;
7534 Value *A, *B;
7535 auto UAddOvResultPat = m_ExtractValue<0>(
7537 if (match(Op0, UAddOvResultPat) &&
7538 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7539 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7540 (match(A, m_One()) || match(B, m_One()))) ||
7541 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7542 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7543 // extract(uadd.with.overflow(A, B), 0) < A
7544 // extract(uadd.with.overflow(A, 1), 0) == 0
7545 // extract(uadd.with.overflow(A, -1), 0) != -1
7546 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7547 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7548 (Op0 == A || Op0 == B))
7549 // A > extract(uadd.with.overflow(A, B), 0)
7550 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7551 else
7552 return nullptr;
7553
7554 return ExtractValueInst::Create(UAddOv, 1);
7555}
7556
7558 if (!I.getOperand(0)->getType()->isPointerTy() ||
7560 I.getParent()->getParent(),
7561 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7562 return nullptr;
7563 }
7564 Instruction *Op;
7565 if (match(I.getOperand(0), m_Instruction(Op)) &&
7566 match(I.getOperand(1), m_Zero()) &&
7567 Op->isLaunderOrStripInvariantGroup()) {
7568 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7569 Op->getOperand(0), I.getOperand(1));
7570 }
7571 return nullptr;
7572}
7573
7575 IRBuilderBase &Builder) {
7576 if (!ICmpInst::isEquality(I.getPredicate()))
7577 return nullptr;
7578
7579 // The caller puts constants after non-constants.
7580 Value *Op = I.getOperand(0);
7581 Value *Const = I.getOperand(1);
7582
7583 // For Cond an equality condition, fold
7584 //
7585 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7586 // icmp (eq|ne) Op, (Zero|AllOnes)
7587 //
7588 // with a bitcast.
7589 Value *Vec;
7590 if ((match(Const, m_ZeroInt()) &&
7592 m_Value(Vec))))) ||
7593 (match(Const, m_AllOnes()) &&
7595 m_Value(Vec)))))) {
7596 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7597 if (!VecTy)
7598 return nullptr;
7599 Type *VecEltTy = VecTy->getElementType();
7600 unsigned ScalarBW =
7601 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7602 if (!DL.fitsInLegalInteger(ScalarBW))
7603 return nullptr;
7604 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7605 Value *NewConst = match(Const, m_ZeroInt())
7606 ? ConstantInt::get(ScalarTy, 0)
7607 : ConstantInt::getAllOnesValue(ScalarTy);
7608 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7609 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7610 }
7611 return nullptr;
7612}
7613
7614/// This function folds patterns produced by lowering of reduce idioms, such as
7615/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7616/// attempts to generate fewer number of scalar comparisons instead of vector
7617/// comparisons when possible.
7619 InstCombiner::BuilderTy &Builder,
7620 const DataLayout &DL) {
7621 if (I.getType()->isVectorTy())
7622 return nullptr;
7623 CmpPredicate OuterPred, InnerPred;
7624 Value *LHS, *RHS;
7625
7626 // Match lowering of @llvm.vector.reduce.and. Turn
7627 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7628 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7629 /// %res = icmp <pred> i8 %scalar_ne, 0
7630 ///
7631 /// into
7632 ///
7633 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7634 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7635 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7636 ///
7637 /// for <pred> in {ne, eq}.
7638 if (!match(&I, m_ICmp(OuterPred,
7640 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7641 m_Zero())))
7642 return nullptr;
7643 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7644 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7645 return nullptr;
7646 unsigned NumBits =
7647 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7648 // TODO: Relax this to "not wider than max legal integer type"?
7649 if (!DL.isLegalInteger(NumBits))
7650 return nullptr;
7651
7652 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7653 auto *ScalarTy = Builder.getIntNTy(NumBits);
7654 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7655 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7656 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7657 I.getName());
7658 }
7659
7660 return nullptr;
7661}
7662
7663// This helper will be called with icmp operands in both orders.
7665 Value *Op0, Value *Op1,
7666 ICmpInst &CxtI) {
7667 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7668 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7669 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7670 return NI;
7671
7672 if (auto *SI = dyn_cast<SelectInst>(Op0))
7673 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7674 return NI;
7675
7676 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7677 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7678 return Res;
7679
7680 if (Instruction *Res = foldICmpWithClamp(CxtI, Op1, MinMax))
7681 return Res;
7682 }
7683
7684 {
7685 Value *X;
7686 const APInt *C;
7687 // icmp X+Cst, X
7688 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7689 return foldICmpAddOpConst(X, *C, Pred);
7690 }
7691
7692 // abs(X) >= X --> true
7693 // abs(X) u<= X --> true
7694 // abs(X) < X --> false
7695 // abs(X) u> X --> false
7696 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7697 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7698 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7699 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7700 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7701 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7702 {
7703 Value *X;
7704 Constant *C;
7706 match(Op1, m_Specific(X))) {
7707 Value *NullValue = Constant::getNullValue(X->getType());
7708 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7709 const APInt SMin =
7710 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7711 bool IsIntMinPosion = C->isAllOnesValue();
7712 switch (Pred) {
7713 case CmpInst::ICMP_ULE:
7714 case CmpInst::ICMP_SGE:
7715 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7716 case CmpInst::ICMP_UGT:
7717 case CmpInst::ICMP_SLT:
7719 case CmpInst::ICMP_UGE:
7720 case CmpInst::ICMP_SLE:
7721 case CmpInst::ICMP_EQ: {
7722 return replaceInstUsesWith(
7723 CxtI, IsIntMinPosion
7724 ? Builder.CreateICmpSGT(X, AllOnesValue)
7725 : Builder.CreateICmpULT(
7726 X, ConstantInt::get(X->getType(), SMin + 1)));
7727 }
7728 case CmpInst::ICMP_ULT:
7729 case CmpInst::ICMP_SGT:
7730 case CmpInst::ICMP_NE: {
7731 return replaceInstUsesWith(
7732 CxtI, IsIntMinPosion
7733 ? Builder.CreateICmpSLT(X, NullValue)
7734 : Builder.CreateICmpUGT(
7735 X, ConstantInt::get(X->getType(), SMin)));
7736 }
7737 default:
7738 llvm_unreachable("Invalid predicate!");
7739 }
7740 }
7741 }
7742
7743 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7744 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7745 return replaceInstUsesWith(CxtI, V);
7746
7747 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7748 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7749 {
7750 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7751 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7753 }
7754
7755 if (!ICmpInst::isUnsigned(Pred) &&
7756 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7757 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7759 }
7760 }
7761
7762 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7763 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7764 {
7765 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7766 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7768 }
7769
7770 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7771 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7772 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7774 }
7775 }
7776
7777 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7778 // -> icmp X, (add nsw/nuw Y, K >> L)
7779 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7780 Value *X;
7781 uint64_t ShAmt;
7782 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7783 !CxtI.isSigned()) {
7784 if (ShAmt >= X->getType()->getScalarSizeInBits())
7785 return nullptr;
7786 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7787 ShiftSemantics::Unsigned, &CxtI)) {
7788 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7790 return new ICmpInst(Pred, X, NewOp1);
7791 }
7792 }
7793
7794 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7795 !CxtI.isUnsigned()) {
7796 if (ShAmt >= X->getType()->getScalarSizeInBits())
7797 return nullptr;
7798 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7799 ShiftSemantics::Signed, &CxtI)) {
7800 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7802 return new ICmpInst(Pred, X, NewOp1);
7803 }
7804 }
7805 return nullptr;
7806}
7807
7809 bool Changed = false;
7810 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7812 unsigned Op0Cplxity = getComplexity(Op0);
7813 unsigned Op1Cplxity = getComplexity(Op1);
7814
7815 /// Orders the operands of the compare so that they are listed from most
7816 /// complex to least complex. This puts constants before unary operators,
7817 /// before binary operators.
7818 if (Op0Cplxity < Op1Cplxity) {
7819 I.swapOperands();
7820 std::swap(Op0, Op1);
7821 Changed = true;
7822 }
7823
7824 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7825 return replaceInstUsesWith(I, V);
7826
7827 // Comparing -val or val with non-zero is the same as just comparing val
7828 // ie, abs(val) != 0 -> val != 0
7829 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7830 Value *Cond, *SelectTrue, *SelectFalse;
7831 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7832 m_Value(SelectFalse)))) {
7833 if (Value *V = dyn_castNegVal(SelectTrue)) {
7834 if (V == SelectFalse)
7835 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7836 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7837 if (V == SelectTrue)
7838 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7839 }
7840 }
7841 }
7842
7844 return Res;
7845
7846 if (Op0->getType()->isIntOrIntVectorTy(1))
7848 return Res;
7849
7851 return Res;
7852
7854 return Res;
7855
7857 return Res;
7858
7860 return Res;
7861
7863 return Res;
7864
7866 return Res;
7867
7869 return Res;
7870
7871 // Test if the ICmpInst instruction is used exclusively by a select as
7872 // part of a minimum or maximum operation. If so, refrain from doing
7873 // any other folding. This helps out other analyses which understand
7874 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7875 // and CodeGen. And in this case, at least one of the comparison
7876 // operands has at least one user besides the compare (the select),
7877 // which would often largely negate the benefit of folding anyway.
7878 //
7879 // Do the same for the other patterns recognized by matchSelectPattern.
7880 if (I.hasOneUse())
7881 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7882 Value *A, *B;
7884 if (SPR.Flavor != SPF_UNKNOWN)
7885 return nullptr;
7886 }
7887
7888 // Do this after checking for min/max to prevent infinite looping.
7889 if (Instruction *Res = foldICmpWithZero(I))
7890 return Res;
7891
7892 Value *X;
7893 const APInt *C;
7894 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
7895 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
7896 match(Op1, m_Not(m_Specific(X)))) {
7897 if (C->isNonNegative())
7898 return new ICmpInst(ICmpInst::ICMP_SLT, X,
7899 Constant::getNullValue(X->getType()));
7900 return new ICmpInst(ICmpInst::ICMP_UGT, X,
7901 ConstantInt::get(X->getType(), ~*C));
7902 }
7903
7904 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
7905 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
7906 match(Op1, m_Not(m_Specific(X)))) {
7907 if (C->isNonNegative())
7908 return new ICmpInst(ICmpInst::ICMP_SGT, X,
7909 Constant::getAllOnesValue(X->getType()));
7910 return new ICmpInst(ICmpInst::ICMP_ULT, X,
7911 ConstantInt::get(X->getType(), ~*C));
7912 }
7913
7914 // FIXME: We only do this after checking for min/max to prevent infinite
7915 // looping caused by a reverse canonicalization of these patterns for min/max.
7916 // FIXME: The organization of folds is a mess. These would naturally go into
7917 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7918 // down here after the min/max restriction.
7919 ICmpInst::Predicate Pred = I.getPredicate();
7920 if (match(Op1, m_APInt(C))) {
7921 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
7922 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7923 Constant *Zero = Constant::getNullValue(Op0->getType());
7924 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7925 }
7926
7927 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
7928 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7930 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7931 }
7932 }
7933
7934 // The folds in here may rely on wrapping flags and special constants, so
7935 // they can break up min/max idioms in some cases but not seemingly similar
7936 // patterns.
7937 // FIXME: It may be possible to enhance select folding to make this
7938 // unnecessary. It may also be moot if we canonicalize to min/max
7939 // intrinsics.
7940 if (Instruction *Res = foldICmpBinOp(I, Q))
7941 return Res;
7942
7944 return Res;
7945
7946 // Try to match comparison as a sign bit test. Intentionally do this after
7947 // foldICmpInstWithConstant() to potentially let other folds to happen first.
7948 if (Instruction *New = foldSignBitTest(I))
7949 return New;
7950
7951 if (auto *PN = dyn_cast<PHINode>(Op0))
7952 if (Instruction *NV = foldOpIntoPhi(I, PN))
7953 return NV;
7954 if (auto *PN = dyn_cast<PHINode>(Op1))
7955 if (Instruction *NV = foldOpIntoPhi(I, PN))
7956 return NV;
7957
7959 return Res;
7960
7961 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
7962 return Res;
7963 if (Instruction *Res =
7964 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
7965 return Res;
7966
7967 if (I.isCommutative()) {
7968 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
7969 replaceOperand(I, 0, Pair->first);
7970 replaceOperand(I, 1, Pair->second);
7971 return &I;
7972 }
7973 }
7974
7975 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
7976 // when all select arms are constants, via truth table.
7978 return R;
7979
7980 // In case of a comparison with two select instructions having the same
7981 // condition, check whether one of the resulting branches can be simplified.
7982 // If so, just compare the other branch and select the appropriate result.
7983 // For example:
7984 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
7985 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
7986 // %cmp2 = icmp slt i32 %tmp2, %tmp1
7987 // The icmp will result false for the false value of selects and the result
7988 // will depend upon the comparison of true values of selects if %cmp is
7989 // true. Thus, transform this into:
7990 // %cmp = icmp slt i32 %y, %z
7991 // %sel = select i1 %cond, i1 %cmp, i1 false
7992 // This handles similar cases to transform.
7993 {
7994 Value *Cond, *A, *B, *C, *D;
7995 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
7997 (Op0->hasOneUse() || Op1->hasOneUse())) {
7998 // Check whether comparison of TrueValues can be simplified
7999 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8000 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8001 return SelectInst::Create(
8002 Cond, Res, NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8004 }
8005 // Check whether comparison of FalseValues can be simplified
8006 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8007 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8008 return SelectInst::Create(
8009 Cond, NewICMP, Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8011 }
8012 }
8013 }
8014
8015 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8016 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8017 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8018 {
8019 Value *A, *B;
8020 CmpPredicate CmpPred;
8021 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8023 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8024 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8025 bool I0NUW = I0->hasNoUnsignedWrap();
8026 bool I1NUW = I1->hasNoUnsignedWrap();
8027 bool I0NSW = I0->hasNoSignedWrap();
8028 bool I1NSW = I1->hasNoSignedWrap();
8029 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8030 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8031 (ICmpInst::isEquality(Pred) &&
8032 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8033 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8034 ConstantInt::get(Op0->getType(), 0));
8035 }
8036 }
8037 }
8038
8039 // Try to optimize equality comparisons against alloca-based pointers.
8040 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8041 assert(Op1->getType()->isPointerTy() &&
8042 "Comparing pointer with non-pointer?");
8043 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8044 if (foldAllocaCmp(Alloca))
8045 return nullptr;
8046 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8047 if (foldAllocaCmp(Alloca))
8048 return nullptr;
8049 }
8050
8051 if (Instruction *Res = foldICmpBitCast(I))
8052 return Res;
8053
8054 // TODO: Hoist this above the min/max bailout.
8056 return R;
8057
8058 {
8059 Value *X, *Y;
8060 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8061 // and (X & ~Y) != 0 --> (X & Y) == 0
8062 // if A is a power of 2.
8063 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8064 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8065 I.isEquality())
8066 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8067 Op1);
8068
8069 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8070 if (Op0->getType()->isIntOrIntVectorTy()) {
8071 bool ConsumesOp0, ConsumesOp1;
8072 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8073 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8074 (ConsumesOp0 || ConsumesOp1)) {
8075 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8076 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8077 assert(InvOp0 && InvOp1 &&
8078 "Mismatch between isFreeToInvert and getFreelyInverted");
8079 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8080 }
8081 }
8082
8083 Instruction *AddI = nullptr;
8085 m_Instruction(AddI))) &&
8086 isa<IntegerType>(X->getType())) {
8087 Value *Result;
8088 Constant *Overflow;
8089 // m_UAddWithOverflow can match patterns that do not include an explicit
8090 // "add" instruction, so check the opcode of the matched op.
8091 if (AddI->getOpcode() == Instruction::Add &&
8092 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8093 Result, Overflow)) {
8094 replaceInstUsesWith(*AddI, Result);
8095 eraseInstFromFunction(*AddI);
8096 return replaceInstUsesWith(I, Overflow);
8097 }
8098 }
8099
8100 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8101 if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
8102 match(Op1, m_APInt(C))) {
8103 if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
8104 return R;
8105 }
8106
8107 // Signbit test folds
8108 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8109 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8110 Instruction *ExtI;
8111 if ((I.isUnsigned() || I.isEquality()) &&
8112 match(Op1,
8114 Y->getType()->getScalarSizeInBits() == 1 &&
8115 (Op0->hasOneUse() || Op1->hasOneUse())) {
8116 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8117 Instruction *ShiftI;
8118 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8120 OpWidth - 1))))) {
8121 unsigned ExtOpc = ExtI->getOpcode();
8122 unsigned ShiftOpc = ShiftI->getOpcode();
8123 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8124 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8125 Value *SLTZero =
8126 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8127 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8128 return replaceInstUsesWith(I, Cmp);
8129 }
8130 }
8131 }
8132 }
8133
8134 if (Instruction *Res = foldICmpEquality(I))
8135 return Res;
8136
8138 return Res;
8139
8140 if (Instruction *Res = foldICmpOfUAddOv(I))
8141 return Res;
8142
8144 return Res;
8145
8146 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8147 // an i1 which indicates whether or not we successfully did the swap.
8148 //
8149 // Replace comparisons between the old value and the expected value with the
8150 // indicator that 'cmpxchg' returns.
8151 //
8152 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8153 // spuriously fail. In those cases, the old value may equal the expected
8154 // value but it is possible for the swap to not occur.
8155 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8156 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8157 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8158 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8159 !ACXI->isWeak())
8160 return ExtractValueInst::Create(ACXI, 1);
8161
8163 return Res;
8164
8165 if (I.getType()->isVectorTy())
8166 if (Instruction *Res = foldVectorCmp(I, Builder))
8167 return Res;
8168
8170 return Res;
8171
8173 return Res;
8174
8175 {
8176 Value *A;
8177 const APInt *C1, *C2;
8178 ICmpInst::Predicate Pred = I.getPredicate();
8179 if (ICmpInst::isEquality(Pred)) {
8180 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8181 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8182 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8183 match(Op1, m_APInt(C2))) {
8184 Type *InputTy = A->getType();
8185 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8186 // c2 must be non-negative at the bitwidth of a.
8187 if (C2->getActiveBits() < InputBitWidth) {
8188 APInt TruncC1 = C1->trunc(InputBitWidth);
8189 // Check if there are 1s in C1 high bits of size InputBitWidth.
8190 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8191 TruncC1.setBit(InputBitWidth - 1);
8192 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8193 return new ICmpInst(
8194 Pred, AndInst,
8195 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8196 }
8197 }
8198 }
8199 }
8200
8201 return Changed ? &I : nullptr;
8202}
8203
8204/// Fold fcmp ([us]itofp x, cst) if possible.
8206 Instruction *LHSI,
8207 Constant *RHSC) {
8208 const APFloat *RHS;
8209 if (!match(RHSC, m_APFloat(RHS)))
8210 return nullptr;
8211
8212 // Get the width of the mantissa. We don't want to hack on conversions that
8213 // might lose information from the integer, e.g. "i64 -> float"
8214 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8215 if (MantissaWidth == -1)
8216 return nullptr; // Unknown.
8217
8218 Type *IntTy = LHSI->getOperand(0)->getType();
8219 unsigned IntWidth = IntTy->getScalarSizeInBits();
8220 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8221
8222 if (I.isEquality()) {
8223 FCmpInst::Predicate P = I.getPredicate();
8224 bool IsExact = false;
8225 APSInt RHSCvt(IntWidth, LHSUnsigned);
8226 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8227
8228 // If the floating point constant isn't an integer value, we know if we will
8229 // ever compare equal / not equal to it.
8230 if (!IsExact) {
8231 // TODO: Can never be -0.0 and other non-representable values
8232 APFloat RHSRoundInt(*RHS);
8234 if (*RHS != RHSRoundInt) {
8236 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8237
8239 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8240 }
8241 }
8242
8243 // TODO: If the constant is exactly representable, is it always OK to do
8244 // equality compares as integer?
8245 }
8246
8247 // Check to see that the input is converted from an integer type that is small
8248 // enough that preserves all bits. TODO: check here for "known" sign bits.
8249 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8250
8251 // Following test does NOT adjust IntWidth downwards for signed inputs,
8252 // because the most negative value still requires all the mantissa bits
8253 // to distinguish it from one less than that value.
8254 if ((int)IntWidth > MantissaWidth) {
8255 // Conversion would lose accuracy. Check if loss can impact comparison.
8256 int Exp = ilogb(*RHS);
8257 if (Exp == APFloat::IEK_Inf) {
8258 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8259 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8260 // Conversion could create infinity.
8261 return nullptr;
8262 } else {
8263 // Note that if RHS is zero or NaN, then Exp is negative
8264 // and first condition is trivially false.
8265 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8266 // Conversion could affect comparison.
8267 return nullptr;
8268 }
8269 }
8270
8271 // Otherwise, we can potentially simplify the comparison. We know that it
8272 // will always come through as an integer value and we know the constant is
8273 // not a NAN (it would have been previously simplified).
8274 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8275
8277 switch (I.getPredicate()) {
8278 default:
8279 llvm_unreachable("Unexpected predicate!");
8280 case FCmpInst::FCMP_UEQ:
8281 case FCmpInst::FCMP_OEQ:
8282 Pred = ICmpInst::ICMP_EQ;
8283 break;
8284 case FCmpInst::FCMP_UGT:
8285 case FCmpInst::FCMP_OGT:
8286 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8287 break;
8288 case FCmpInst::FCMP_UGE:
8289 case FCmpInst::FCMP_OGE:
8290 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8291 break;
8292 case FCmpInst::FCMP_ULT:
8293 case FCmpInst::FCMP_OLT:
8294 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8295 break;
8296 case FCmpInst::FCMP_ULE:
8297 case FCmpInst::FCMP_OLE:
8298 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8299 break;
8300 case FCmpInst::FCMP_UNE:
8301 case FCmpInst::FCMP_ONE:
8302 Pred = ICmpInst::ICMP_NE;
8303 break;
8304 case FCmpInst::FCMP_ORD:
8305 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8306 case FCmpInst::FCMP_UNO:
8307 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8308 }
8309
8310 // Now we know that the APFloat is a normal number, zero or inf.
8311
8312 // See if the FP constant is too large for the integer. For example,
8313 // comparing an i8 to 300.0.
8314 if (!LHSUnsigned) {
8315 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8316 // and large values.
8317 APFloat SMax(RHS->getSemantics());
8318 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8320 if (SMax < *RHS) { // smax < 13123.0
8321 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8322 Pred == ICmpInst::ICMP_SLE)
8323 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8324 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8325 }
8326 } else {
8327 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8328 // +INF and large values.
8329 APFloat UMax(RHS->getSemantics());
8330 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8332 if (UMax < *RHS) { // umax < 13123.0
8333 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8334 Pred == ICmpInst::ICMP_ULE)
8335 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8336 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8337 }
8338 }
8339
8340 if (!LHSUnsigned) {
8341 // See if the RHS value is < SignedMin.
8342 APFloat SMin(RHS->getSemantics());
8343 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8345 if (SMin > *RHS) { // smin > 12312.0
8346 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8347 Pred == ICmpInst::ICMP_SGE)
8348 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8349 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8350 }
8351 } else {
8352 // See if the RHS value is < UnsignedMin.
8353 APFloat UMin(RHS->getSemantics());
8354 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8356 if (UMin > *RHS) { // umin > 12312.0
8357 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8358 Pred == ICmpInst::ICMP_UGE)
8359 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8360 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8361 }
8362 }
8363
8364 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8365 // [0, UMAX], but it may still be fractional. Check whether this is the case
8366 // using the IsExact flag.
8367 // Don't do this for zero, because -0.0 is not fractional.
8368 APSInt RHSInt(IntWidth, LHSUnsigned);
8369 bool IsExact;
8370 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8371 if (!RHS->isZero()) {
8372 if (!IsExact) {
8373 // If we had a comparison against a fractional value, we have to adjust
8374 // the compare predicate and sometimes the value. RHSC is rounded towards
8375 // zero at this point.
8376 switch (Pred) {
8377 default:
8378 llvm_unreachable("Unexpected integer comparison!");
8379 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8380 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8381 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8382 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8383 case ICmpInst::ICMP_ULE:
8384 // (float)int <= 4.4 --> int <= 4
8385 // (float)int <= -4.4 --> false
8386 if (RHS->isNegative())
8387 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8388 break;
8389 case ICmpInst::ICMP_SLE:
8390 // (float)int <= 4.4 --> int <= 4
8391 // (float)int <= -4.4 --> int < -4
8392 if (RHS->isNegative())
8393 Pred = ICmpInst::ICMP_SLT;
8394 break;
8395 case ICmpInst::ICMP_ULT:
8396 // (float)int < -4.4 --> false
8397 // (float)int < 4.4 --> int <= 4
8398 if (RHS->isNegative())
8399 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8400 Pred = ICmpInst::ICMP_ULE;
8401 break;
8402 case ICmpInst::ICMP_SLT:
8403 // (float)int < -4.4 --> int < -4
8404 // (float)int < 4.4 --> int <= 4
8405 if (!RHS->isNegative())
8406 Pred = ICmpInst::ICMP_SLE;
8407 break;
8408 case ICmpInst::ICMP_UGT:
8409 // (float)int > 4.4 --> int > 4
8410 // (float)int > -4.4 --> true
8411 if (RHS->isNegative())
8412 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8413 break;
8414 case ICmpInst::ICMP_SGT:
8415 // (float)int > 4.4 --> int > 4
8416 // (float)int > -4.4 --> int >= -4
8417 if (RHS->isNegative())
8418 Pred = ICmpInst::ICMP_SGE;
8419 break;
8420 case ICmpInst::ICMP_UGE:
8421 // (float)int >= -4.4 --> true
8422 // (float)int >= 4.4 --> int > 4
8423 if (RHS->isNegative())
8424 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8425 Pred = ICmpInst::ICMP_UGT;
8426 break;
8427 case ICmpInst::ICMP_SGE:
8428 // (float)int >= -4.4 --> int >= -4
8429 // (float)int >= 4.4 --> int > 4
8430 if (!RHS->isNegative())
8431 Pred = ICmpInst::ICMP_SGT;
8432 break;
8433 }
8434 }
8435 }
8436
8437 // Lower this FP comparison into an appropriate integer version of the
8438 // comparison.
8439 return new ICmpInst(Pred, LHSI->getOperand(0),
8440 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8441}
8442
8443/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8444/// where all true/false values are constants that allow the compare to be
8445/// constant-folded for every combination of C1 and C2.
8446/// We compute a 4-entry truth table and use createLogicFromTable to
8447/// synthesize a boolean expression of C1 and C2.
8449 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8450 Value *C1, *C2;
8451 Constant *TV1, *FV1, *TV2, *FV2;
8452
8453 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8454 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8455 return nullptr;
8456
8457 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8458 return nullptr;
8459
8460 unsigned Pred = I.getPredicate();
8461 const DataLayout &DL = I.getDataLayout();
8462
8463 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8464 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8465 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8466 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8467
8468 if (!Res00 || !Res01 || !Res10 || !Res11)
8469 return nullptr;
8470
8471 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8472 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8473 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8474 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8475 return nullptr;
8476
8477 std::bitset<4> Table;
8478 if (!Res00->isNullValue())
8479 Table.set(0);
8480 if (!Res01->isNullValue())
8481 Table.set(1);
8482 if (!Res10->isNullValue())
8483 Table.set(2);
8484 if (!Res11->isNullValue())
8485 Table.set(3);
8486
8487 Value *Res = createLogicFromTable(Table, C1, C2, Builder,
8488 Op0->hasOneUse() && Op1->hasOneUse());
8489 if (!Res)
8490 return nullptr;
8491 return replaceInstUsesWith(I, Res);
8492}
8493
8494/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8496 Constant *RHSC) {
8497 // When C is not 0.0 and infinities are not allowed:
8498 // (C / X) < 0.0 is a sign-bit test of X
8499 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8500 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8501 //
8502 // Proof:
8503 // Multiply (C / X) < 0.0 by X * X / C.
8504 // - X is non zero, if it is the flag 'ninf' is violated.
8505 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8506 // the predicate. C is also non zero by definition.
8507 //
8508 // Thus X * X / C is non zero and the transformation is valid. [qed]
8509
8510 FCmpInst::Predicate Pred = I.getPredicate();
8511
8512 // Check that predicates are valid.
8513 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8514 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8515 return nullptr;
8516
8517 // Check that RHS operand is zero.
8518 if (!match(RHSC, m_AnyZeroFP()))
8519 return nullptr;
8520
8521 // Check fastmath flags ('ninf').
8522 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8523 return nullptr;
8524
8525 // Check the properties of the dividend. It must not be zero to avoid a
8526 // division by zero (see Proof).
8527 const APFloat *C;
8528 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8529 return nullptr;
8530
8531 if (C->isZero())
8532 return nullptr;
8533
8534 // Get swapped predicate if necessary.
8535 if (C->isNegative())
8536 Pred = I.getSwappedPredicate();
8537
8538 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8539}
8540
8541// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8542// Patterns include:
8543// fptrunc(x) < C --> x < ext(C)
8544// fptrunc(x) <= C --> x <= ext(C)
8545// fptrunc(x) > C --> x > ext(C)
8546// fptrunc(x) >= C --> x >= ext(C)
8547// fptrunc(x) ord/uno C --> x ord/uno 0
8548// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8549// due to precision loss.
8551 const Constant &C) {
8552 FCmpInst::Predicate Pred = I.getPredicate();
8553 Type *DestType = FPTrunc.getOperand(0)->getType();
8554
8555 const APFloat *CValue;
8556 // TODO: support vec
8557 if (!match(&C, m_APFloat(CValue)))
8558 return nullptr;
8559
8560 // Handle ord/uno
8561 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8562 assert(!CValue->isNaN() &&
8563 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8564 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8565 ConstantFP::getZero(DestType), "", &I);
8566 }
8567
8568 // Handle <, >, <=, >=
8569 bool RoundDown = false;
8570
8571 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8572 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8573 RoundDown = true;
8574 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8575 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8576 RoundDown = false;
8577 else
8578 return nullptr;
8579
8580 if (CValue->isNaN() || CValue->isInfinity())
8581 return nullptr;
8582
8583 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8584 bool LosesInfo;
8585 APFloat Dest = Src;
8586 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8587 return Dest;
8588 };
8589
8590 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8591 APFloat NextValue = Value;
8592 NextValue.next(RoundDown);
8593 return NextValue;
8594 };
8595
8596 APFloat NextCValue = NextValue(*CValue, RoundDown);
8597
8598 const fltSemantics &DestFltSema =
8599 DestType->getScalarType()->getFltSemantics();
8600
8601 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8602 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8603
8604 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8605 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8606 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8607 // value of 'CValue'.
8608 if (NextCValue.isInfinity()) {
8609 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8610 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8611
8612 ExtNextCValue = ExtCValue + Bias;
8613 }
8614
8615 APFloat ExtMidValue =
8616 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8617
8618 const fltSemantics &SrcFltSema =
8619 C.getType()->getScalarType()->getFltSemantics();
8620
8621 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8622 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8623 if (MidValue != *CValue)
8624 ExtMidValue.next(!RoundDown);
8625
8626 // Check whether 'ExtMidValue' is a valid result since the assumption on
8627 // imaged 'NextCValue' might not hold for new float types.
8628 // ppc_fp128 can't pass here when converting from max float because of
8629 // APFloat implementation.
8630 if (NextCValue.isInfinity()) {
8631 // ExtMidValue --- narrowed ---> Finite
8632 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8633 return nullptr;
8634
8635 // NextExtMidValue --- narrowed ---> Infinity
8636 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8637 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8638 return nullptr;
8639 }
8640
8641 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8642 ConstantFP::get(DestType, ExtMidValue), "", &I);
8643}
8644
8645/// Optimize fabs(X) compared with zero.
8647 Value *X;
8648 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8649 return nullptr;
8650
8651 const APFloat *C;
8652 if (!match(I.getOperand(1), m_APFloat(C)))
8653 return nullptr;
8654
8655 if (!C->isPosZero()) {
8656 if (!C->isSmallestNormalized())
8657 return nullptr;
8658
8659 const Function *F = I.getFunction();
8660 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8661 if (Mode.Input == DenormalMode::PreserveSign ||
8663
8664 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8665 Constant *Zero = ConstantFP::getZero(X->getType());
8666 return new FCmpInst(P, X, Zero, "", I);
8667 };
8668
8669 switch (I.getPredicate()) {
8670 case FCmpInst::FCMP_OLT:
8671 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8672 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8673 case FCmpInst::FCMP_UGE:
8674 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8675 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8676 case FCmpInst::FCMP_OGE:
8677 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8678 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8679 case FCmpInst::FCMP_ULT:
8680 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8681 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8682 default:
8683 break;
8684 }
8685 }
8686
8687 return nullptr;
8688 }
8689
8690 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8691 I->setPredicate(P);
8692 return IC.replaceOperand(*I, 0, X);
8693 };
8694
8695 switch (I.getPredicate()) {
8696 case FCmpInst::FCMP_UGE:
8697 case FCmpInst::FCMP_OLT:
8698 // fabs(X) >= 0.0 --> true
8699 // fabs(X) < 0.0 --> false
8700 llvm_unreachable("fcmp should have simplified");
8701
8702 case FCmpInst::FCMP_OGT:
8703 // fabs(X) > 0.0 --> X != 0.0
8704 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8705
8706 case FCmpInst::FCMP_UGT:
8707 // fabs(X) u> 0.0 --> X u!= 0.0
8708 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8709
8710 case FCmpInst::FCMP_OLE:
8711 // fabs(X) <= 0.0 --> X == 0.0
8712 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8713
8714 case FCmpInst::FCMP_ULE:
8715 // fabs(X) u<= 0.0 --> X u== 0.0
8716 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8717
8718 case FCmpInst::FCMP_OGE:
8719 // fabs(X) >= 0.0 --> !isnan(X)
8720 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8721 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8722
8723 case FCmpInst::FCMP_ULT:
8724 // fabs(X) u< 0.0 --> isnan(X)
8725 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8726 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8727
8728 case FCmpInst::FCMP_OEQ:
8729 case FCmpInst::FCMP_UEQ:
8730 case FCmpInst::FCMP_ONE:
8731 case FCmpInst::FCMP_UNE:
8732 case FCmpInst::FCMP_ORD:
8733 case FCmpInst::FCMP_UNO:
8734 // Look through the fabs() because it doesn't change anything but the sign.
8735 // fabs(X) == 0.0 --> X == 0.0,
8736 // fabs(X) != 0.0 --> X != 0.0
8737 // isnan(fabs(X)) --> isnan(X)
8738 // !isnan(fabs(X) --> !isnan(X)
8739 return replacePredAndOp0(&I, I.getPredicate(), X);
8740
8741 default:
8742 return nullptr;
8743 }
8744}
8745
8746/// Optimize sqrt(X) compared with zero.
8748 Value *X;
8749 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8750 return nullptr;
8751
8752 if (!match(I.getOperand(1), m_PosZeroFP()))
8753 return nullptr;
8754
8755 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8756 I.setPredicate(P);
8757 return IC.replaceOperand(I, 0, X);
8758 };
8759
8760 // Clear ninf flag if sqrt doesn't have it.
8761 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8762 I.setHasNoInfs(false);
8763
8764 switch (I.getPredicate()) {
8765 case FCmpInst::FCMP_OLT:
8766 case FCmpInst::FCMP_UGE:
8767 // sqrt(X) < 0.0 --> false
8768 // sqrt(X) u>= 0.0 --> true
8769 llvm_unreachable("fcmp should have simplified");
8770 case FCmpInst::FCMP_ULT:
8771 case FCmpInst::FCMP_ULE:
8772 case FCmpInst::FCMP_OGT:
8773 case FCmpInst::FCMP_OGE:
8774 case FCmpInst::FCMP_OEQ:
8775 case FCmpInst::FCMP_UNE:
8776 // sqrt(X) u< 0.0 --> X u< 0.0
8777 // sqrt(X) u<= 0.0 --> X u<= 0.0
8778 // sqrt(X) > 0.0 --> X > 0.0
8779 // sqrt(X) >= 0.0 --> X >= 0.0
8780 // sqrt(X) == 0.0 --> X == 0.0
8781 // sqrt(X) u!= 0.0 --> X u!= 0.0
8782 return IC.replaceOperand(I, 0, X);
8783
8784 case FCmpInst::FCMP_OLE:
8785 // sqrt(X) <= 0.0 --> X == 0.0
8786 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8787 case FCmpInst::FCMP_UGT:
8788 // sqrt(X) u> 0.0 --> X u!= 0.0
8789 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8790 case FCmpInst::FCMP_UEQ:
8791 // sqrt(X) u== 0.0 --> X u<= 0.0
8792 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8793 case FCmpInst::FCMP_ONE:
8794 // sqrt(X) != 0.0 --> X > 0.0
8795 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8796 case FCmpInst::FCMP_ORD:
8797 // !isnan(sqrt(X)) --> X >= 0.0
8798 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8799 case FCmpInst::FCMP_UNO:
8800 // isnan(sqrt(X)) --> X u< 0.0
8801 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8802 default:
8803 llvm_unreachable("Unexpected predicate!");
8804 }
8805}
8806
8808 CmpInst::Predicate Pred = I.getPredicate();
8809 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8810
8811 // Canonicalize fneg as Op1.
8812 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
8813 std::swap(Op0, Op1);
8814 Pred = I.getSwappedPredicate();
8815 }
8816
8817 if (!match(Op1, m_FNeg(m_Specific(Op0))))
8818 return nullptr;
8819
8820 // Replace the negated operand with 0.0:
8821 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8822 Constant *Zero = ConstantFP::getZero(Op0->getType());
8823 return new FCmpInst(Pred, Op0, Zero, "", &I);
8824}
8825
8827 Constant *RHSC, InstCombinerImpl &CI) {
8828 const CmpInst::Predicate Pred = I.getPredicate();
8829 Value *X = LHSI->getOperand(0);
8830 Value *Y = LHSI->getOperand(1);
8831 switch (Pred) {
8832 default:
8833 break;
8834 case FCmpInst::FCMP_UGT:
8835 case FCmpInst::FCMP_ULT:
8836 case FCmpInst::FCMP_UNE:
8837 case FCmpInst::FCMP_OEQ:
8838 case FCmpInst::FCMP_OGE:
8839 case FCmpInst::FCMP_OLE:
8840 // The optimization is not valid if X and Y are infinities of the same
8841 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8842 // flag then we can assume we do not have that case. Otherwise we might be
8843 // able to prove that either X or Y is not infinity.
8844 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8848 break;
8849
8850 [[fallthrough]];
8851 case FCmpInst::FCMP_OGT:
8852 case FCmpInst::FCMP_OLT:
8853 case FCmpInst::FCMP_ONE:
8854 case FCmpInst::FCMP_UEQ:
8855 case FCmpInst::FCMP_UGE:
8856 case FCmpInst::FCMP_ULE:
8857 // fcmp pred (x - y), 0 --> fcmp pred x, y
8858 if (match(RHSC, m_AnyZeroFP()) &&
8859 I.getFunction()->getDenormalMode(
8860 LHSI->getType()->getScalarType()->getFltSemantics()) ==
8862 CI.replaceOperand(I, 0, X);
8863 CI.replaceOperand(I, 1, Y);
8864 I.setHasNoInfs(LHSI->hasNoInfs());
8865 if (LHSI->hasNoNaNs())
8866 I.setHasNoNaNs(true);
8867 return &I;
8868 }
8869 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
8870 // where C and Y can't be arbitrary floating-point values.
8871 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
8872 // to `1.0f`, so the source compare is false while the rewritten compare is
8873 // true.
8874 // We need to make sure (C - Y) never rounds back to C
8875 const APFloat *C;
8876 Value *IntSrc;
8877 if (match(RHSC, m_APFloat(C)) &&
8878 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
8879 C->isNormal()) {
8880 // Requirements on C and Y:
8881 // 1. C is finite, nonzero, normal.
8882 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
8883 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
8884 // must be integer-valued with an absolute value of at least 1;
8885 // as long as the step size near C does not exceed 1,
8886 // C - Y cannot be rounded back to C when Y != 0.
8887 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
8888 // 0, 0` for ordered and unordered predicates as long as C is finite and
8889 // nonzero.
8890 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8891 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
8892 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
8893 I.setPredicate(I.getSwappedPredicate());
8894 CI.replaceOperand(I, 0, Y);
8895 CI.replaceOperand(I, 1, ZeroC);
8896 return &I;
8897 }
8898 }
8899 break;
8900 }
8901
8902 return nullptr;
8903}
8904
8905/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
8906/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
8907/// float when the uitofp casts are exact and C is in the valid range.
8908///
8909/// Since exact uitofp means distinct integers map to distinct floats, the only
8910/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
8911/// There are no values in the open interval (0, 1), so:
8912/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
8913// fabs(..) >= C where C >= 1.0 -> a != b
8914///
8915/// The same logic applies to sitofp.
8917 Value *FAbsArg;
8918 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
8919 return nullptr;
8920
8921 const APFloat *C;
8922 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
8923 return nullptr;
8924
8925 FCmpInst::Predicate Pred = I.getPredicate();
8926 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
8927 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
8928 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
8929 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
8930 if (!IsStrictLt && !IsStrictGt && !IsGe)
8931 return nullptr;
8932
8933 APFloat One = APFloat::getOne(C->getSemantics());
8934 APFloat::cmpResult Cmp = C->compare(One);
8935
8936 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
8937 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
8938 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
8939 return nullptr;
8940 if (IsGe && Cmp == APFloat::cmpGreaterThan)
8941 return nullptr;
8942 if (IsLe && Cmp != APFloat::cmpGreaterThan)
8943 return nullptr;
8944 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
8945 return nullptr;
8946
8947 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
8948 Value *A, *B;
8949 bool IsSigned;
8950 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
8951 IsSigned = false;
8952 } else if (match(FAbsArg,
8954 IsSigned = true;
8955 } else {
8956 return nullptr;
8957 }
8958
8959 // A and B must have the same integer type
8960 if (A->getType() != B->getType())
8961 return nullptr;
8962
8963 Type *FPTy = FAbsArg->getType();
8964 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
8965 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
8966 return nullptr;
8967 ICmpInst::Predicate ResultPred =
8968 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8969 return new ICmpInst(ResultPred, A, B);
8970}
8971
8973 InstCombinerImpl &IC) {
8974 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
8975 Type *OpType = LHS->getType();
8976 CmpInst::Predicate Pred = I.getPredicate();
8977
8980
8981 if (!FloorX && !CeilX) {
8984 std::swap(LHS, RHS);
8985 Pred = I.getSwappedPredicate();
8986 }
8987 }
8988
8989 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
8990 // fcmp pred floor(x), x => fcmp pred trunc(x), x
8991 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
8992 // where pred is oeq, one, ord, ueq, une, uno.
8993 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
8994 return new FCmpInst(Pred, TruncX, RHS, "", &I);
8995 }
8996
8997 switch (Pred) {
8998 case FCmpInst::FCMP_OLE:
8999 // fcmp ole floor(x), x => fcmp ord x, 0
9000 if (FloorX)
9002 "", &I);
9003 break;
9004 case FCmpInst::FCMP_OGT:
9005 // fcmp ogt floor(x), x => false
9006 if (FloorX)
9007 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9008 break;
9009 case FCmpInst::FCMP_OGE:
9010 // fcmp oge ceil(x), x => fcmp ord x, 0
9011 if (CeilX)
9013 "", &I);
9014 break;
9015 case FCmpInst::FCMP_OLT:
9016 // fcmp olt ceil(x), x => false
9017 if (CeilX)
9018 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9019 break;
9020 case FCmpInst::FCMP_ULE:
9021 // fcmp ule floor(x), x => true
9022 if (FloorX)
9023 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9024 break;
9025 case FCmpInst::FCMP_UGT:
9026 // fcmp ugt floor(x), x => fcmp uno x, 0
9027 if (FloorX)
9029 "", &I);
9030 break;
9031 case FCmpInst::FCMP_UGE:
9032 // fcmp uge ceil(x), x => true
9033 if (CeilX)
9034 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9035 break;
9036 case FCmpInst::FCMP_ULT:
9037 // fcmp ult ceil(x), x => fcmp uno x, 0
9038 if (CeilX)
9040 "", &I);
9041 break;
9042 default:
9043 break;
9044 }
9045
9046 return nullptr;
9047}
9048
9049/// Returns true if a select that implements a min/max is redundant and
9050/// select result can be replaced with its non-constant operand, e.g.,
9051/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9052/// where C is the FP constant equal to the minimum integer value
9053/// representable by A.
9055 Value *B) {
9056 const APFloat *APF;
9057 if (!match(B, m_APFloat(APF)))
9058 return false;
9059
9060 auto *I = dyn_cast<Instruction>(A);
9061 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9062 I->getOpcode() == Instruction::UIToFP))
9063 return false;
9064
9065 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9066 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9067 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9068 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9069 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9070 APSInt ConvertedInt(BitWidth, IsUnsigned);
9071 bool IsExact;
9073 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9074 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9075}
9076
9078 bool Changed = false;
9079
9080 /// Orders the operands of the compare so that they are listed from most
9081 /// complex to least complex. This puts constants before unary operators,
9082 /// before binary operators.
9083 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9084 I.swapOperands();
9085 Changed = true;
9086 }
9087
9088 const CmpInst::Predicate Pred = I.getPredicate();
9089 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9090 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9091 SQ.getWithInstruction(&I)))
9092 return replaceInstUsesWith(I, V);
9093
9094 // Simplify 'fcmp pred X, X'
9095 Type *OpType = Op0->getType();
9096 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9097 if (Op0 == Op1) {
9098 switch (Pred) {
9099 default:
9100 break;
9101 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9102 case FCmpInst::FCMP_ULT: // True if unordered or less than
9103 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9104 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9105 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9106 I.setPredicate(FCmpInst::FCMP_UNO);
9107 I.setOperand(1, Constant::getNullValue(OpType));
9108 return &I;
9109
9110 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9111 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9112 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9113 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9114 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9115 I.setPredicate(FCmpInst::FCMP_ORD);
9116 I.setOperand(1, Constant::getNullValue(OpType));
9117 return &I;
9118 }
9119 }
9120
9121 if (I.isCommutative()) {
9122 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9123 replaceOperand(I, 0, Pair->first);
9124 replaceOperand(I, 1, Pair->second);
9125 return &I;
9126 }
9127 }
9128
9129 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9130 // then canonicalize the operand to 0.0.
9131 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9132 if (!match(Op0, m_PosZeroFP()) &&
9133 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9134 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9135
9136 if (!match(Op1, m_PosZeroFP()) &&
9137 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9138 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9139 }
9140
9141 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9142 Value *X, *Y;
9143 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9144 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9145
9147 return R;
9148
9149 // Test if the FCmpInst instruction is used exclusively by a select as
9150 // part of a minimum or maximum operation. If so, refrain from doing
9151 // any other folding. This helps out other analyses which understand
9152 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9153 // and CodeGen. And in this case, at least one of the comparison
9154 // operands has at least one user besides the compare (the select),
9155 // which would often largely negate the benefit of folding anyway.
9156 if (I.hasOneUse())
9157 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9158 Value *A, *B;
9160 bool IsRedundantMinMaxClamp =
9161 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9163 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9164 return nullptr;
9165 }
9166
9167 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9168 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9169 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9170 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9171
9172 // Canonicalize:
9173 // fcmp olt X, +inf -> fcmp one X, +inf
9174 // fcmp ole X, +inf -> fcmp ord X, 0
9175 // fcmp ogt X, +inf -> false
9176 // fcmp oge X, +inf -> fcmp oeq X, +inf
9177 // fcmp ult X, +inf -> fcmp une X, +inf
9178 // fcmp ule X, +inf -> true
9179 // fcmp ugt X, +inf -> fcmp uno X, 0
9180 // fcmp uge X, +inf -> fcmp ueq X, +inf
9181 // fcmp olt X, -inf -> false
9182 // fcmp ole X, -inf -> fcmp oeq X, -inf
9183 // fcmp ogt X, -inf -> fcmp one X, -inf
9184 // fcmp oge X, -inf -> fcmp ord X, 0
9185 // fcmp ult X, -inf -> fcmp uno X, 0
9186 // fcmp ule X, -inf -> fcmp ueq X, -inf
9187 // fcmp ugt X, -inf -> fcmp une X, -inf
9188 // fcmp uge X, -inf -> true
9189 const APFloat *C;
9190 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9191 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9192 default:
9193 break;
9194 case FCmpInst::FCMP_ORD:
9195 case FCmpInst::FCMP_UNO:
9198 case FCmpInst::FCMP_OGT:
9199 case FCmpInst::FCMP_ULE:
9200 llvm_unreachable("Should be simplified by InstSimplify");
9201 case FCmpInst::FCMP_OLT:
9202 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9203 case FCmpInst::FCMP_OLE:
9204 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9205 "", &I);
9206 case FCmpInst::FCMP_OGE:
9207 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9208 case FCmpInst::FCMP_ULT:
9209 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9210 case FCmpInst::FCMP_UGT:
9211 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9212 "", &I);
9213 case FCmpInst::FCMP_UGE:
9214 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9215 }
9216 }
9217
9218 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9219 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9220 if (match(Op1, m_PosZeroFP()) &&
9222 X->getType()->isIntOrIntVectorTy() &&
9223 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9224 .inputsMayBeZero()) {
9226 if (Pred == FCmpInst::FCMP_OEQ)
9227 IntPred = ICmpInst::ICMP_EQ;
9228 else if (Pred == FCmpInst::FCMP_UNE)
9229 IntPred = ICmpInst::ICMP_NE;
9230
9231 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9232 Type *IntTy = X->getType();
9233 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9234 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9235 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9236 }
9237 }
9238
9239 // Handle fcmp with instruction LHS and constant RHS.
9240 Instruction *LHSI;
9241 Constant *RHSC;
9242 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9243 switch (LHSI->getOpcode()) {
9244 case Instruction::Select:
9245 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9246 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9248 return replaceOperand(I, 0, X);
9250 return NV;
9251 break;
9252 case Instruction::FSub:
9253 if (LHSI->hasOneUse())
9254 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9255 return NV;
9256 break;
9257 case Instruction::PHI:
9258 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9259 return NV;
9260 break;
9261 case Instruction::SIToFP:
9262 case Instruction::UIToFP:
9263 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9264 return NV;
9265 break;
9266 case Instruction::FDiv:
9267 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9268 return NV;
9269 break;
9270 case Instruction::Load:
9271 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9272 if (Instruction *Res =
9274 return Res;
9275 break;
9276 case Instruction::FPTrunc:
9277 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9278 return NV;
9279 break;
9280 }
9281 }
9282
9283 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9284 return R;
9285
9286 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9287 return R;
9288
9289 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9290 return R;
9291
9292 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9293 return R;
9294
9296 return R;
9297
9298 if (match(Op0, m_FNeg(m_Value(X)))) {
9299 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9300 Constant *C;
9301 if (match(Op1, m_Constant(C)))
9302 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9303 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9304 }
9305
9306 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9307 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9308 return new FCmpInst(Pred, X, Op1, "", &I);
9309
9310 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9311 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9312 return new FCmpInst(Pred, Op0, Y, "", &I);
9313
9314 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9315 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9316 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9317 X->getType() == Y->getType())
9318 return new FCmpInst(Pred, X, Y, "", &I);
9319
9320 if (match(Op0, m_FPExt(m_Value(X)))) {
9321 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9322 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9323 return new FCmpInst(Pred, X, Y, "", &I);
9324
9325 const APFloat *C;
9326 if (match(Op1, m_APFloat(C))) {
9327 const fltSemantics &FPSem =
9328 X->getType()->getScalarType()->getFltSemantics();
9329 bool Lossy;
9330 APFloat TruncC = *C;
9332
9333 if (Lossy) {
9334 // X can't possibly equal the higher-precision constant, so reduce any
9335 // equality comparison.
9336 // TODO: Other predicates can be handled via getFCmpCode().
9337 switch (Pred) {
9338 case FCmpInst::FCMP_OEQ:
9339 // X is ordered and equal to an impossible constant --> false
9340 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9341 case FCmpInst::FCMP_ONE:
9342 // X is ordered and not equal to an impossible constant --> ordered
9343 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9344 ConstantFP::getZero(X->getType()));
9345 case FCmpInst::FCMP_UEQ:
9346 // X is unordered or equal to an impossible constant --> unordered
9347 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9348 ConstantFP::getZero(X->getType()));
9349 case FCmpInst::FCMP_UNE:
9350 // X is unordered or not equal to an impossible constant --> true
9351 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9352 default:
9353 break;
9354 }
9355 }
9356
9357 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9358 // Avoid lossy conversions and denormals.
9359 // Zero is a special case that's OK to convert.
9360 APFloat Fabs = TruncC;
9361 Fabs.clearSign();
9362 if (!Lossy &&
9363 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9364 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9365 return new FCmpInst(Pred, X, NewC, "", &I);
9366 }
9367 }
9368 }
9369
9370 // Convert a sign-bit test of an FP value into a cast and integer compare.
9371 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9372 // TODO: Handle non-zero compare constants.
9373 // TODO: Handle other predicates.
9375 m_Value(X)))) &&
9376 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9377 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9378 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9379 IntType = VectorType::get(IntType, VecTy->getElementCount());
9380
9381 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9382 if (Pred == FCmpInst::FCMP_OLT) {
9383 Value *IntX = Builder.CreateBitCast(X, IntType);
9384 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9385 ConstantInt::getNullValue(IntType));
9386 }
9387 }
9388
9389 {
9390 Value *CanonLHS = nullptr;
9392 // (canonicalize(x) == x) => (x == x)
9393 if (CanonLHS == Op1)
9394 return new FCmpInst(Pred, Op1, Op1, "", &I);
9395
9396 Value *CanonRHS = nullptr;
9398 // (x == canonicalize(x)) => (x == x)
9399 if (CanonRHS == Op0)
9400 return new FCmpInst(Pred, Op0, Op0, "", &I);
9401
9402 // (canonicalize(x) == canonicalize(y)) => (x == y)
9403 if (CanonLHS && CanonRHS)
9404 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9405 }
9406
9407 if (I.getType()->isVectorTy())
9408 if (Instruction *Res = foldVectorCmp(I, Builder))
9409 return Res;
9410
9411 return Changed ? &I : nullptr;
9412}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
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 * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * processUMulZExtIdiom(ICmpInst &I, Value *MulVal, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for multiplication overflow.
static Instruction * foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize sqrt(X) compared with zero.
static Instruction * foldFCmpFNegCommonOp(FCmpInst &I)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
static Instruction * foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
Fold an icmp with LLVM intrinsics.
static Instruction * foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpPow2Test(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW, const DataLayout &DL, SetVector< Value * > &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
static Instruction * foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc, const Constant &C)
static Instruction * foldICmpXNegX(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombinerImpl &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
static Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, const DataLayout &DL, InstCombiner &IC)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
static Instruction * foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs, const APInt &CRhs, InstCombiner::BuilderTy &Builder, const SimplifyQuery &Q)
static Instruction * foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC)
Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b where 'pred' is olt, ult, ogt,...
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned)
static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q)
Return true if X is a multiple of C.
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
static Instruction * foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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
BinaryOperator * Mul
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:343
static constexpr roundingMode rmTowardZero
Definition APFloat.h:357
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:353
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5929
void clearSign()
Definition APFloat.h:1394
bool isNaN() const
Definition APFloat.h:1573
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1184
bool isZero() const
Definition APFloat.h:1571
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1254
APInt bitcastToAPInt() const
Definition APFloat.h:1467
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1234
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1428
opStatus next(bool nextDown)
Definition APFloat.h:1350
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5858
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1344
bool isInfinity() const
Definition APFloat.h:1572
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1793
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
unsigned ceilLogBase2() const
Definition APInt.h:1789
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1210
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1983
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:467
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1963
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1088
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1670
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1970
void negate()
Negate this APInt in place.
Definition APInt.h:1493
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1477
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1640
unsigned logBase2() const
Definition APInt.h:1786
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:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:406
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1976
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1681
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This instruction compares its operands according to the predicate given to the constructor.
static bool isCommutative(Predicate Pred)
static bool isEquality(Predicate Pred)
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition Operator.h:390
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:82
Value * getPointerOperand()
Definition Operator.h:417
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Definition Operator.h:464
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1570
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2485
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:492
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
Instruction * foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr, const APInt &C)
Fold icmp ({al}shr X, Y), C.
Instruction * foldICmpWithZextOrSext(ICmpInst &ICmp)
Instruction * foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select, ConstantInt *C)
Instruction * foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Instruction * foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
Instruction * foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, const APInt &C)
Fold icmp (or X, Y), C.
Instruction * foldICmpTruncWithTruncOrExt(ICmpInst &Cmp, const SimplifyQuery &Q)
Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
Instruction * foldSignBitTest(ICmpInst &I)
Fold equality-comparison between zero and any (maybe truncated) right-shift by one-less-than-bitwidth...
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi, bool isSigned, bool Inside)
Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise (V < Lo || V >= Hi).
Instruction * foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ)
Try to fold icmp (binop), X or icmp X, (binop).
Instruction * foldCmpLoadFromIndexedGlobal(LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst=nullptr)
This is called when we see this pattern: cmp pred (load (gep GV, ...)), cmpcst where GV is a global v...
Instruction * foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub, const APInt &C)
Fold icmp (sub X, Y), C.
Instruction * foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min)
Match and fold patterns like: icmp eq/ne X, min(max(X, Lo), Hi) which represents a range check and ca...
Instruction * foldICmpInstWithConstantNotInt(ICmpInst &Cmp)
Handle icmp with constant (but not simple integer constant) RHS.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Instruction * foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (shl AP2, A), AP1)" -> (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an equality icmp with LLVM intrinsic and constant operand.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Value * foldMultiplicationOverflowCheck(ICmpInst &Cmp)
Fold (-1 u/ x) u< y ((x * y) ?
Instruction * foldICmpWithConstant(ICmpInst &Cmp)
Fold icmp Pred X, C.
CmpInst * canonicalizeICmpPredicate(CmpInst &I)
If we have a comparison with a non-canonical predicate, if we can update all the users,...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * foldICmpWithZero(ICmpInst &Cmp)
Instruction * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CxtI)
Instruction * foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp equality instruction with binary operator LHS and constant RHS: icmp eq/ne BO,...
Instruction * foldICmpUsingBoolRange(ICmpInst &I)
If one operand of an icmp is effectively a bool (value range of {0,1}), then try to reduce patterns b...
Instruction * foldICmpWithTrunc(ICmpInst &Cmp)
Instruction * foldCmpSelectOfConstants(CmpInst &I)
Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2) where all true/false values are cons...
Instruction * foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS, ConstantInt *&Less, ConstantInt *&Equal, ConstantInt *&Greater)
Match a select chain which produces one of three values based on whether the LHS is less than,...
Instruction * visitFCmpInst(FCmpInst &I)
Instruction * foldICmpUsingKnownBits(ICmpInst &Cmp)
Try to fold the comparison based on range information we can get by checking whether bits are known t...
Instruction * foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div, const APInt &C)
Fold icmp ({su}div X, Y), C.
Instruction * foldIRemByPowerOfTwoToBitTest(ICmpInst &I)
If we have: icmp eq/ne (urem/srem x, y), 0 iff y is a power-of-two, we can replace this with a bit te...
Instruction * foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold fcmp ([us]itofp x, cst) if possible.
Instruction * foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Fold icmp (udiv X, Y), C.
Instruction * foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred)
Fold "icmp pred (X+C), X".
Instruction * foldICmpWithCastOp(ICmpInst &ICmp)
Handle icmp (cast x), (cast or constant).
Instruction * foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc, const APInt &C)
Fold icmp (trunc X), C.
Instruction * foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add, const APInt &C)
Fold icmp (add X, Y), C.
Instruction * foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul, const APInt &C)
Fold icmp (mul X, Y), C.
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
Fold icmp (xor X, Y), C.
Instruction * foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS, const ICmpInst &I)
Instruction * foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp, const APInt &C)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp)
Fold icmp eq (num + mask) & ~mask, num to icmp eq (and num, mask), 0 Where mask is a low bit mask.
Instruction * foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1, const APInt &C2)
Fold icmp (and (sh X, Y), C2), C1.
Instruction * foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Instruction * foldICmpInstWithConstant(ICmpInst &Cmp)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
For power-of-2 C: ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1) ((X s>> ShiftC) ^ X) u> (C - 1) -...
Instruction * foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl, const APInt &C)
Fold icmp (shl X, Y), C.
Instruction * foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And, const APInt &C)
Fold icmp (and X, Y), C.
Instruction * foldICmpEquality(ICmpInst &Cmp)
Instruction * foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax, Value *Z, CmpPredicate Pred)
Fold icmp Pred min|max(X, Y), Z.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
bool foldAllocaCmp(AllocaInst *Alloca)
Instruction * visitICmpInst(ICmpInst &I)
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CxtI) const
Instruction * foldICmpWithDominatingICmp(ICmpInst &Cmp)
Canonicalize icmp instructions based on dominating conditions.
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
Instruction * foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> (icmp eq/ne A, Log2(AP2/AP1)) -> (icmp eq/ne A,...
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
Instruction * foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1)
Fold icmp (and X, C2), C1.
Instruction * foldICmpBitCast(ICmpInst &Cmp)
Instruction * foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, Instruction &I)
Fold comparisons between a GEP instruction and something else.
The core instruction combiner logic.
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
SimplifyQuery SQ
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI, bool IsNSW=false) const
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CxtI=nullptr) const
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
const DataLayout & DL
DomConditionCache DC
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents min/max intrinsics.
Value * getLHS() const
Value * getRHS() const
static bool isMin(Intrinsic::ID ID)
Whether the intrinsic is a smin or umin.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:237
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:155
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2798
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:2816
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.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
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_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< is_negated_power2_or_zero > m_NegatedPower2OrZero()
Match a integer or vector negated power-of-2.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
cst_pred_ty< is_lowbit_mask_or_zero > m_LowBitMaskOrZero()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
cstfp_pred_ty< is_finitenonzero > m_FiniteNonZero()
Match a finite non-zero FP constant.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ BinaryOp
One of the operands is a binary op.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1684
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:910
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:1693
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:395
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2166
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
@ Continue
Definition DWP.h:26
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define NC
Definition regutils.h:42
Value * materialize(InstCombiner::BuilderTy &Builder) const
static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV, Instruction *MDFrom)
static OffsetResult value(Value *V)
static OffsetResult invalid()
This callback is used in conjunction with PointerMayBeCaptured.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
static constexpr DenormalMode getIEEE()
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
Definition KnownBits.h:152
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:215
GEPNoWrapFlags Flags
Definition Loads.h:220
Matching combinators.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Capture information for a specific Use.