xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (revision 647cbc5de815c5651677bf8582797f716ec7b48d)
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/APSInt.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/CaptureTracking.h"
19 #include "llvm/Analysis/CmpInstAnalysis.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/Utils/Local.h"
23 #include "llvm/Analysis/VectorUtils.h"
24 #include "llvm/IR/ConstantRange.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Support/KnownBits.h"
29 #include "llvm/Transforms/InstCombine/InstCombiner.h"
30 #include <bitset>
31 
32 using namespace llvm;
33 using namespace PatternMatch;
34 
35 #define DEBUG_TYPE "instcombine"
36 
37 // How many times is a select replaced by one of its operands?
38 STATISTIC(NumSel, "Number of select opts");
39 
40 
41 /// Compute Result = In1+In2, returning true if the result overflowed for this
42 /// type.
43 static bool addWithOverflow(APInt &Result, const APInt &In1,
44                             const APInt &In2, bool IsSigned = false) {
45   bool Overflow;
46   if (IsSigned)
47     Result = In1.sadd_ov(In2, Overflow);
48   else
49     Result = In1.uadd_ov(In2, Overflow);
50 
51   return Overflow;
52 }
53 
54 /// Compute Result = In1-In2, returning true if the result overflowed for this
55 /// type.
56 static bool subWithOverflow(APInt &Result, const APInt &In1,
57                             const APInt &In2, bool IsSigned = false) {
58   bool Overflow;
59   if (IsSigned)
60     Result = In1.ssub_ov(In2, Overflow);
61   else
62     Result = In1.usub_ov(In2, Overflow);
63 
64   return Overflow;
65 }
66 
67 /// Given an icmp instruction, return true if any use of this comparison is a
68 /// branch on sign bit comparison.
69 static bool hasBranchUse(ICmpInst &I) {
70   for (auto *U : I.users())
71     if (isa<BranchInst>(U))
72       return true;
73   return false;
74 }
75 
76 /// Returns true if the exploded icmp can be expressed as a signed comparison
77 /// to zero and updates the predicate accordingly.
78 /// The signedness of the comparison is preserved.
79 /// TODO: Refactor with decomposeBitTestICmp()?
80 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
81   if (!ICmpInst::isSigned(Pred))
82     return false;
83 
84   if (C.isZero())
85     return ICmpInst::isRelational(Pred);
86 
87   if (C.isOne()) {
88     if (Pred == ICmpInst::ICMP_SLT) {
89       Pred = ICmpInst::ICMP_SLE;
90       return true;
91     }
92   } else if (C.isAllOnes()) {
93     if (Pred == ICmpInst::ICMP_SGT) {
94       Pred = ICmpInst::ICMP_SGE;
95       return true;
96     }
97   }
98 
99   return false;
100 }
101 
102 /// This is called when we see this pattern:
103 ///   cmp pred (load (gep GV, ...)), cmpcst
104 /// where GV is a global variable with a constant initializer. Try to simplify
105 /// this into some simple computation that does not need the load. For example
106 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
107 ///
108 /// If AndCst is non-null, then the loaded value is masked with that constant
109 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
110 Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
111     LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
112     ConstantInt *AndCst) {
113   if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
114       GV->getValueType() != GEP->getSourceElementType() || !GV->isConstant() ||
115       !GV->hasDefinitiveInitializer())
116     return nullptr;
117 
118   Constant *Init = GV->getInitializer();
119   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
120     return nullptr;
121 
122   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
123   // Don't blow up on huge arrays.
124   if (ArrayElementCount > MaxArraySizeForCombine)
125     return nullptr;
126 
127   // There are many forms of this optimization we can handle, for now, just do
128   // the simple index into a single-dimensional array.
129   //
130   // Require: GEP GV, 0, i {{, constant indices}}
131   if (GEP->getNumOperands() < 3 || !isa<ConstantInt>(GEP->getOperand(1)) ||
132       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
133       isa<Constant>(GEP->getOperand(2)))
134     return nullptr;
135 
136   // Check that indices after the variable are constants and in-range for the
137   // type they index.  Collect the indices.  This is typically for arrays of
138   // structs.
139   SmallVector<unsigned, 4> LaterIndices;
140 
141   Type *EltTy = Init->getType()->getArrayElementType();
142   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
143     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
144     if (!Idx)
145       return nullptr; // Variable index.
146 
147     uint64_t IdxVal = Idx->getZExtValue();
148     if ((unsigned)IdxVal != IdxVal)
149       return nullptr; // Too large array index.
150 
151     if (StructType *STy = dyn_cast<StructType>(EltTy))
152       EltTy = STy->getElementType(IdxVal);
153     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
154       if (IdxVal >= ATy->getNumElements())
155         return nullptr;
156       EltTy = ATy->getElementType();
157     } else {
158       return nullptr; // Unknown type.
159     }
160 
161     LaterIndices.push_back(IdxVal);
162   }
163 
164   enum { Overdefined = -3, Undefined = -2 };
165 
166   // Variables for our state machines.
167 
168   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
169   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
170   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
171   // undefined, otherwise set to the first true element.  SecondTrueElement is
172   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
173   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
174 
175   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
176   // form "i != 47 & i != 87".  Same state transitions as for true elements.
177   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
178 
179   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
180   /// define a state machine that triggers for ranges of values that the index
181   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
182   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
183   /// index in the range (inclusive).  We use -2 for undefined here because we
184   /// use relative comparisons and don't want 0-1 to match -1.
185   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
186 
187   // MagicBitvector - This is a magic bitvector where we set a bit if the
188   // comparison is true for element 'i'.  If there are 64 elements or less in
189   // the array, this will fully represent all the comparison results.
190   uint64_t MagicBitvector = 0;
191 
192   // Scan the array and see if one of our patterns matches.
193   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
194   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
195     Constant *Elt = Init->getAggregateElement(i);
196     if (!Elt)
197       return nullptr;
198 
199     // If this is indexing an array of structures, get the structure element.
200     if (!LaterIndices.empty()) {
201       Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
202       if (!Elt)
203         return nullptr;
204     }
205 
206     // If the element is masked, handle it.
207     if (AndCst) {
208       Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
209       if (!Elt)
210         return nullptr;
211     }
212 
213     // Find out if the comparison would be true or false for the i'th element.
214     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
215                                                   CompareRHS, DL, &TLI);
216     // If the result is undef for this element, ignore it.
217     if (isa<UndefValue>(C)) {
218       // Extend range state machines to cover this element in case there is an
219       // undef in the middle of the range.
220       if (TrueRangeEnd == (int)i - 1)
221         TrueRangeEnd = i;
222       if (FalseRangeEnd == (int)i - 1)
223         FalseRangeEnd = i;
224       continue;
225     }
226 
227     // If we can't compute the result for any of the elements, we have to give
228     // up evaluating the entire conditional.
229     if (!isa<ConstantInt>(C))
230       return nullptr;
231 
232     // Otherwise, we know if the comparison is true or false for this element,
233     // update our state machines.
234     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
235 
236     // State machine for single/double/range index comparison.
237     if (IsTrueForElt) {
238       // Update the TrueElement state machine.
239       if (FirstTrueElement == Undefined)
240         FirstTrueElement = TrueRangeEnd = i; // First true element.
241       else {
242         // Update double-compare state machine.
243         if (SecondTrueElement == Undefined)
244           SecondTrueElement = i;
245         else
246           SecondTrueElement = Overdefined;
247 
248         // Update range state machine.
249         if (TrueRangeEnd == (int)i - 1)
250           TrueRangeEnd = i;
251         else
252           TrueRangeEnd = Overdefined;
253       }
254     } else {
255       // Update the FalseElement state machine.
256       if (FirstFalseElement == Undefined)
257         FirstFalseElement = FalseRangeEnd = i; // First false element.
258       else {
259         // Update double-compare state machine.
260         if (SecondFalseElement == Undefined)
261           SecondFalseElement = i;
262         else
263           SecondFalseElement = Overdefined;
264 
265         // Update range state machine.
266         if (FalseRangeEnd == (int)i - 1)
267           FalseRangeEnd = i;
268         else
269           FalseRangeEnd = Overdefined;
270       }
271     }
272 
273     // If this element is in range, update our magic bitvector.
274     if (i < 64 && IsTrueForElt)
275       MagicBitvector |= 1ULL << i;
276 
277     // If all of our states become overdefined, bail out early.  Since the
278     // predicate is expensive, only check it every 8 elements.  This is only
279     // really useful for really huge arrays.
280     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
281         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
282         FalseRangeEnd == Overdefined)
283       return nullptr;
284   }
285 
286   // Now that we've scanned the entire array, emit our new comparison(s).  We
287   // order the state machines in complexity of the generated code.
288   Value *Idx = GEP->getOperand(2);
289 
290   // If the index is larger than the pointer offset size of the target, truncate
291   // the index down like the GEP would do implicitly.  We don't have to do this
292   // for an inbounds GEP because the index can't be out of range.
293   if (!GEP->isInBounds()) {
294     Type *PtrIdxTy = DL.getIndexType(GEP->getType());
295     unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();
296     if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
297       Idx = Builder.CreateTrunc(Idx, PtrIdxTy);
298   }
299 
300   // If inbounds keyword is not present, Idx * ElementSize can overflow.
301   // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
302   // Then, there are two possible values for Idx to match offset 0:
303   // 0x00..00, 0x80..00.
304   // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
305   // comparison is false if Idx was 0x80..00.
306   // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
307   unsigned ElementSize =
308       DL.getTypeAllocSize(Init->getType()->getArrayElementType());
309   auto MaskIdx = [&](Value *Idx) {
310     if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
311       Value *Mask = ConstantInt::get(Idx->getType(), -1);
312       Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
313       Idx = Builder.CreateAnd(Idx, Mask);
314     }
315     return Idx;
316   };
317 
318   // If the comparison is only true for one or two elements, emit direct
319   // comparisons.
320   if (SecondTrueElement != Overdefined) {
321     Idx = MaskIdx(Idx);
322     // None true -> false.
323     if (FirstTrueElement == Undefined)
324       return replaceInstUsesWith(ICI, Builder.getFalse());
325 
326     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
327 
328     // True for one element -> 'i == 47'.
329     if (SecondTrueElement == Undefined)
330       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
331 
332     // True for two elements -> 'i == 47 | i == 72'.
333     Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
334     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
335     Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
336     return BinaryOperator::CreateOr(C1, C2);
337   }
338 
339   // If the comparison is only false for one or two elements, emit direct
340   // comparisons.
341   if (SecondFalseElement != Overdefined) {
342     Idx = MaskIdx(Idx);
343     // None false -> true.
344     if (FirstFalseElement == Undefined)
345       return replaceInstUsesWith(ICI, Builder.getTrue());
346 
347     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
348 
349     // False for one element -> 'i != 47'.
350     if (SecondFalseElement == Undefined)
351       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
352 
353     // False for two elements -> 'i != 47 & i != 72'.
354     Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
355     Value *SecondFalseIdx =
356         ConstantInt::get(Idx->getType(), SecondFalseElement);
357     Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
358     return BinaryOperator::CreateAnd(C1, C2);
359   }
360 
361   // If the comparison can be replaced with a range comparison for the elements
362   // where it is true, emit the range check.
363   if (TrueRangeEnd != Overdefined) {
364     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
365     Idx = MaskIdx(Idx);
366 
367     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
368     if (FirstTrueElement) {
369       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
370       Idx = Builder.CreateAdd(Idx, Offs);
371     }
372 
373     Value *End =
374         ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
375     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
376   }
377 
378   // False range check.
379   if (FalseRangeEnd != Overdefined) {
380     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
381     Idx = MaskIdx(Idx);
382     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
383     if (FirstFalseElement) {
384       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
385       Idx = Builder.CreateAdd(Idx, Offs);
386     }
387 
388     Value *End =
389         ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
390     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
391   }
392 
393   // If a magic bitvector captures the entire comparison state
394   // of this load, replace it with computation that does:
395   //   ((magic_cst >> i) & 1) != 0
396   {
397     Type *Ty = nullptr;
398 
399     // Look for an appropriate type:
400     // - The type of Idx if the magic fits
401     // - The smallest fitting legal type
402     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
403       Ty = Idx->getType();
404     else
405       Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
406 
407     if (Ty) {
408       Idx = MaskIdx(Idx);
409       Value *V = Builder.CreateIntCast(Idx, Ty, false);
410       V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
411       V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
412       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
413     }
414   }
415 
416   return nullptr;
417 }
418 
419 /// Returns true if we can rewrite Start as a GEP with pointer Base
420 /// and some integer offset. The nodes that need to be re-written
421 /// for this transformation will be added to Explored.
422 static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
423                                   const DataLayout &DL,
424                                   SetVector<Value *> &Explored) {
425   SmallVector<Value *, 16> WorkList(1, Start);
426   Explored.insert(Base);
427 
428   // The following traversal gives us an order which can be used
429   // when doing the final transformation. Since in the final
430   // transformation we create the PHI replacement instructions first,
431   // we don't have to get them in any particular order.
432   //
433   // However, for other instructions we will have to traverse the
434   // operands of an instruction first, which means that we have to
435   // do a post-order traversal.
436   while (!WorkList.empty()) {
437     SetVector<PHINode *> PHIs;
438 
439     while (!WorkList.empty()) {
440       if (Explored.size() >= 100)
441         return false;
442 
443       Value *V = WorkList.back();
444 
445       if (Explored.contains(V)) {
446         WorkList.pop_back();
447         continue;
448       }
449 
450       if (!isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
451         // We've found some value that we can't explore which is different from
452         // the base. Therefore we can't do this transformation.
453         return false;
454 
455       if (auto *GEP = dyn_cast<GEPOperator>(V)) {
456         // Only allow inbounds GEPs with at most one variable offset.
457         auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
458         if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
459           return false;
460 
461         if (!Explored.contains(GEP->getOperand(0)))
462           WorkList.push_back(GEP->getOperand(0));
463       }
464 
465       if (WorkList.back() == V) {
466         WorkList.pop_back();
467         // We've finished visiting this node, mark it as such.
468         Explored.insert(V);
469       }
470 
471       if (auto *PN = dyn_cast<PHINode>(V)) {
472         // We cannot transform PHIs on unsplittable basic blocks.
473         if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
474           return false;
475         Explored.insert(PN);
476         PHIs.insert(PN);
477       }
478     }
479 
480     // Explore the PHI nodes further.
481     for (auto *PN : PHIs)
482       for (Value *Op : PN->incoming_values())
483         if (!Explored.contains(Op))
484           WorkList.push_back(Op);
485   }
486 
487   // Make sure that we can do this. Since we can't insert GEPs in a basic
488   // block before a PHI node, we can't easily do this transformation if
489   // we have PHI node users of transformed instructions.
490   for (Value *Val : Explored) {
491     for (Value *Use : Val->uses()) {
492 
493       auto *PHI = dyn_cast<PHINode>(Use);
494       auto *Inst = dyn_cast<Instruction>(Val);
495 
496       if (Inst == Base || Inst == PHI || !Inst || !PHI ||
497           !Explored.contains(PHI))
498         continue;
499 
500       if (PHI->getParent() == Inst->getParent())
501         return false;
502     }
503   }
504   return true;
505 }
506 
507 // Sets the appropriate insert point on Builder where we can add
508 // a replacement Instruction for V (if that is possible).
509 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
510                               bool Before = true) {
511   if (auto *PHI = dyn_cast<PHINode>(V)) {
512     BasicBlock *Parent = PHI->getParent();
513     Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
514     return;
515   }
516   if (auto *I = dyn_cast<Instruction>(V)) {
517     if (!Before)
518       I = &*std::next(I->getIterator());
519     Builder.SetInsertPoint(I);
520     return;
521   }
522   if (auto *A = dyn_cast<Argument>(V)) {
523     // Set the insertion point in the entry block.
524     BasicBlock &Entry = A->getParent()->getEntryBlock();
525     Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
526     return;
527   }
528   // Otherwise, this is a constant and we don't need to set a new
529   // insertion point.
530   assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
531 }
532 
533 /// Returns a re-written value of Start as an indexed GEP using Base as a
534 /// pointer.
535 static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
536                                  const DataLayout &DL,
537                                  SetVector<Value *> &Explored,
538                                  InstCombiner &IC) {
539   // Perform all the substitutions. This is a bit tricky because we can
540   // have cycles in our use-def chains.
541   // 1. Create the PHI nodes without any incoming values.
542   // 2. Create all the other values.
543   // 3. Add the edges for the PHI nodes.
544   // 4. Emit GEPs to get the original pointers.
545   // 5. Remove the original instructions.
546   Type *IndexType = IntegerType::get(
547       Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
548 
549   DenseMap<Value *, Value *> NewInsts;
550   NewInsts[Base] = ConstantInt::getNullValue(IndexType);
551 
552   // Create the new PHI nodes, without adding any incoming values.
553   for (Value *Val : Explored) {
554     if (Val == Base)
555       continue;
556     // Create empty phi nodes. This avoids cyclic dependencies when creating
557     // the remaining instructions.
558     if (auto *PHI = dyn_cast<PHINode>(Val))
559       NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
560                                       PHI->getName() + ".idx", PHI);
561   }
562   IRBuilder<> Builder(Base->getContext());
563 
564   // Create all the other instructions.
565   for (Value *Val : Explored) {
566     if (NewInsts.contains(Val))
567       continue;
568 
569     if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
570       setInsertionPoint(Builder, GEP);
571       Value *Op = NewInsts[GEP->getOperand(0)];
572       Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
573       if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
574         NewInsts[GEP] = OffsetV;
575       else
576         NewInsts[GEP] = Builder.CreateNSWAdd(
577             Op, OffsetV, GEP->getOperand(0)->getName() + ".add");
578       continue;
579     }
580     if (isa<PHINode>(Val))
581       continue;
582 
583     llvm_unreachable("Unexpected instruction type");
584   }
585 
586   // Add the incoming values to the PHI nodes.
587   for (Value *Val : Explored) {
588     if (Val == Base)
589       continue;
590     // All the instructions have been created, we can now add edges to the
591     // phi nodes.
592     if (auto *PHI = dyn_cast<PHINode>(Val)) {
593       PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
594       for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
595         Value *NewIncoming = PHI->getIncomingValue(I);
596 
597         if (NewInsts.contains(NewIncoming))
598           NewIncoming = NewInsts[NewIncoming];
599 
600         NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
601       }
602     }
603   }
604 
605   for (Value *Val : Explored) {
606     if (Val == Base)
607       continue;
608 
609     setInsertionPoint(Builder, Val, false);
610     // Create GEP for external users.
611     Value *NewVal = Builder.CreateInBoundsGEP(
612         Builder.getInt8Ty(), Base, NewInsts[Val], Val->getName() + ".ptr");
613     IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
614     // Add old instruction to worklist for DCE. We don't directly remove it
615     // here because the original compare is one of the users.
616     IC.addToWorklist(cast<Instruction>(Val));
617   }
618 
619   return NewInsts[Start];
620 }
621 
622 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
623 /// We can look through PHIs, GEPs and casts in order to determine a common base
624 /// between GEPLHS and RHS.
625 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
626                                               ICmpInst::Predicate Cond,
627                                               const DataLayout &DL,
628                                               InstCombiner &IC) {
629   // FIXME: Support vector of pointers.
630   if (GEPLHS->getType()->isVectorTy())
631     return nullptr;
632 
633   if (!GEPLHS->hasAllConstantIndices())
634     return nullptr;
635 
636   APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
637   Value *PtrBase =
638       GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
639                                                 /*AllowNonInbounds*/ false);
640 
641   // Bail if we looked through addrspacecast.
642   if (PtrBase->getType() != GEPLHS->getType())
643     return nullptr;
644 
645   // The set of nodes that will take part in this transformation.
646   SetVector<Value *> Nodes;
647 
648   if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
649     return nullptr;
650 
651   // We know we can re-write this as
652   //  ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
653   // Since we've only looked through inbouds GEPs we know that we
654   // can't have overflow on either side. We can therefore re-write
655   // this as:
656   //   OFFSET1 cmp OFFSET2
657   Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes, IC);
658 
659   // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
660   // GEP having PtrBase as the pointer base, and has returned in NewRHS the
661   // offset. Since Index is the offset of LHS to the base pointer, we will now
662   // compare the offsets instead of comparing the pointers.
663   return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
664                       IC.Builder.getInt(Offset), NewRHS);
665 }
666 
667 /// Fold comparisons between a GEP instruction and something else. At this point
668 /// we know that the GEP is on the LHS of the comparison.
669 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
670                                            ICmpInst::Predicate Cond,
671                                            Instruction &I) {
672   // Don't transform signed compares of GEPs into index compares. Even if the
673   // GEP is inbounds, the final add of the base pointer can have signed overflow
674   // and would change the result of the icmp.
675   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
676   // the maximum signed value for the pointer type.
677   if (ICmpInst::isSigned(Cond))
678     return nullptr;
679 
680   // Look through bitcasts and addrspacecasts. We do not however want to remove
681   // 0 GEPs.
682   if (!isa<GetElementPtrInst>(RHS))
683     RHS = RHS->stripPointerCasts();
684 
685   Value *PtrBase = GEPLHS->getOperand(0);
686   if (PtrBase == RHS && (GEPLHS->isInBounds() || ICmpInst::isEquality(Cond))) {
687     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
688     Value *Offset = EmitGEPOffset(GEPLHS);
689     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
690                         Constant::getNullValue(Offset->getType()));
691   }
692 
693   if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
694       isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
695       !NullPointerIsDefined(I.getFunction(),
696                             RHS->getType()->getPointerAddressSpace())) {
697     // For most address spaces, an allocation can't be placed at null, but null
698     // itself is treated as a 0 size allocation in the in bounds rules.  Thus,
699     // the only valid inbounds address derived from null, is null itself.
700     // Thus, we have four cases to consider:
701     // 1) Base == nullptr, Offset == 0 -> inbounds, null
702     // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
703     // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
704     // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
705     //
706     // (Note if we're indexing a type of size 0, that simply collapses into one
707     //  of the buckets above.)
708     //
709     // In general, we're allowed to make values less poison (i.e. remove
710     //   sources of full UB), so in this case, we just select between the two
711     //   non-poison cases (1 and 4 above).
712     //
713     // For vectors, we apply the same reasoning on a per-lane basis.
714     auto *Base = GEPLHS->getPointerOperand();
715     if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
716       auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
717       Base = Builder.CreateVectorSplat(EC, Base);
718     }
719     return new ICmpInst(Cond, Base,
720                         ConstantExpr::getPointerBitCastOrAddrSpaceCast(
721                             cast<Constant>(RHS), Base->getType()));
722   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
723     // If the base pointers are different, but the indices are the same, just
724     // compare the base pointer.
725     if (PtrBase != GEPRHS->getOperand(0)) {
726       bool IndicesTheSame =
727           GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
728           GEPLHS->getPointerOperand()->getType() ==
729               GEPRHS->getPointerOperand()->getType() &&
730           GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
731       if (IndicesTheSame)
732         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
733           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
734             IndicesTheSame = false;
735             break;
736           }
737 
738       // If all indices are the same, just compare the base pointers.
739       Type *BaseType = GEPLHS->getOperand(0)->getType();
740       if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
741         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
742 
743       // If we're comparing GEPs with two base pointers that only differ in type
744       // and both GEPs have only constant indices or just one use, then fold
745       // the compare with the adjusted indices.
746       // FIXME: Support vector of pointers.
747       if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
748           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
749           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
750           PtrBase->stripPointerCasts() ==
751               GEPRHS->getOperand(0)->stripPointerCasts() &&
752           !GEPLHS->getType()->isVectorTy()) {
753         Value *LOffset = EmitGEPOffset(GEPLHS);
754         Value *ROffset = EmitGEPOffset(GEPRHS);
755 
756         // If we looked through an addrspacecast between different sized address
757         // spaces, the LHS and RHS pointers are different sized
758         // integers. Truncate to the smaller one.
759         Type *LHSIndexTy = LOffset->getType();
760         Type *RHSIndexTy = ROffset->getType();
761         if (LHSIndexTy != RHSIndexTy) {
762           if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
763               RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
764             ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
765           } else
766             LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
767         }
768 
769         Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
770                                         LOffset, ROffset);
771         return replaceInstUsesWith(I, Cmp);
772       }
773 
774       // Otherwise, the base pointers are different and the indices are
775       // different. Try convert this to an indexed compare by looking through
776       // PHIs/casts.
777       return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
778     }
779 
780     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
781     if (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++) break;
801           DiffOperand = i;
802         }
803 
804       if (NumDifferences == 0)   // SAME GEP?
805         return replaceInstUsesWith(I, // No comparison is needed here.
806           ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
807 
808       else if (NumDifferences == 1 && GEPsInBounds) {
809         Value *LHSV = GEPLHS->getOperand(DiffOperand);
810         Value *RHSV = GEPRHS->getOperand(DiffOperand);
811         // Make sure we do a signed comparison here.
812         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
813       }
814     }
815 
816     // Only lower this if the icmp is the only user of the GEP or if we expect
817     // the result to fold to a constant!
818     if ((GEPsInBounds || CmpInst::isEquality(Cond)) &&
819         (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
820         (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse())) {
821       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
822       Value *L = EmitGEPOffset(GEPLHS);
823       Value *R = EmitGEPOffset(GEPRHS);
824       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
825     }
826   }
827 
828   // Try convert this to an indexed compare by looking through PHIs/casts as a
829   // last resort.
830   return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
831 }
832 
833 bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
834   // It would be tempting to fold away comparisons between allocas and any
835   // pointer not based on that alloca (e.g. an argument). However, even
836   // though such pointers cannot alias, they can still compare equal.
837   //
838   // But LLVM doesn't specify where allocas get their memory, so if the alloca
839   // doesn't escape we can argue that it's impossible to guess its value, and we
840   // can therefore act as if any such guesses are wrong.
841   //
842   // However, we need to ensure that this folding is consistent: We can't fold
843   // one comparison to false, and then leave a different comparison against the
844   // same value alone (as it might evaluate to true at runtime, leading to a
845   // contradiction). As such, this code ensures that all comparisons are folded
846   // at the same time, and there are no other escapes.
847 
848   struct CmpCaptureTracker : public CaptureTracker {
849     AllocaInst *Alloca;
850     bool Captured = false;
851     /// The value of the map is a bit mask of which icmp operands the alloca is
852     /// used in.
853     SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
854 
855     CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
856 
857     void tooManyUses() override { Captured = true; }
858 
859     bool captured(const Use *U) override {
860       auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
861       // We need to check that U is based *only* on the alloca, and doesn't
862       // have other contributions from a select/phi operand.
863       // TODO: We could check whether getUnderlyingObjects() reduces to one
864       // object, which would allow looking through phi nodes.
865       if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
866         // Collect equality icmps of the alloca, and don't treat them as
867         // captures.
868         auto Res = ICmps.insert({ICmp, 0});
869         Res.first->second |= 1u << U->getOperandNo();
870         return false;
871       }
872 
873       Captured = true;
874       return true;
875     }
876   };
877 
878   CmpCaptureTracker Tracker(Alloca);
879   PointerMayBeCaptured(Alloca, &Tracker);
880   if (Tracker.Captured)
881     return false;
882 
883   bool Changed = false;
884   for (auto [ICmp, Operands] : Tracker.ICmps) {
885     switch (Operands) {
886     case 1:
887     case 2: {
888       // The alloca is only used in one icmp operand. Assume that the
889       // equality is false.
890       auto *Res = ConstantInt::get(
891           ICmp->getType(), ICmp->getPredicate() == ICmpInst::ICMP_NE);
892       replaceInstUsesWith(*ICmp, Res);
893       eraseInstFromFunction(*ICmp);
894       Changed = true;
895       break;
896     }
897     case 3:
898       // Both icmp operands are based on the alloca, so this is comparing
899       // pointer offsets, without leaking any information about the address
900       // of the alloca. Ignore such comparisons.
901       break;
902     default:
903       llvm_unreachable("Cannot happen");
904     }
905   }
906 
907   return Changed;
908 }
909 
910 /// Fold "icmp pred (X+C), X".
911 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
912                                                   ICmpInst::Predicate Pred) {
913   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
914   // so the values can never be equal.  Similarly for all other "or equals"
915   // operators.
916   assert(!!C && "C should not be zero!");
917 
918   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
919   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
920   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
921   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
922     Constant *R = ConstantInt::get(X->getType(),
923                                    APInt::getMaxValue(C.getBitWidth()) - C);
924     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
925   }
926 
927   // (X+1) >u X        --> X <u (0-1)        --> X != 255
928   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
929   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
930   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
931     return new ICmpInst(ICmpInst::ICMP_ULT, X,
932                         ConstantInt::get(X->getType(), -C));
933 
934   APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
935 
936   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
937   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
938   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
939   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
940   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
941   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
942   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
943     return new ICmpInst(ICmpInst::ICMP_SGT, X,
944                         ConstantInt::get(X->getType(), SMax - C));
945 
946   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
947   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
948   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
949   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
950   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
951   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
952 
953   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
954   return new ICmpInst(ICmpInst::ICMP_SLT, X,
955                       ConstantInt::get(X->getType(), SMax - (C - 1)));
956 }
957 
958 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
959 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
960 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
961 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
962                                                      const APInt &AP1,
963                                                      const APInt &AP2) {
964   assert(I.isEquality() && "Cannot fold icmp gt/lt");
965 
966   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
967     if (I.getPredicate() == I.ICMP_NE)
968       Pred = CmpInst::getInversePredicate(Pred);
969     return new ICmpInst(Pred, LHS, RHS);
970   };
971 
972   // Don't bother doing any work for cases which InstSimplify handles.
973   if (AP2.isZero())
974     return nullptr;
975 
976   bool IsAShr = isa<AShrOperator>(I.getOperand(0));
977   if (IsAShr) {
978     if (AP2.isAllOnes())
979       return nullptr;
980     if (AP2.isNegative() != AP1.isNegative())
981       return nullptr;
982     if (AP2.sgt(AP1))
983       return nullptr;
984   }
985 
986   if (!AP1)
987     // 'A' must be large enough to shift out the highest set bit.
988     return getICmp(I.ICMP_UGT, A,
989                    ConstantInt::get(A->getType(), AP2.logBase2()));
990 
991   if (AP1 == AP2)
992     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
993 
994   int Shift;
995   if (IsAShr && AP1.isNegative())
996     Shift = AP1.countl_one() - AP2.countl_one();
997   else
998     Shift = AP1.countl_zero() - AP2.countl_zero();
999 
1000   if (Shift > 0) {
1001     if (IsAShr && AP1 == AP2.ashr(Shift)) {
1002       // There are multiple solutions if we are comparing against -1 and the LHS
1003       // of the ashr is not a power of two.
1004       if (AP1.isAllOnes() && !AP2.isPowerOf2())
1005         return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1006       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1007     } else if (AP1 == AP2.lshr(Shift)) {
1008       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1009     }
1010   }
1011 
1012   // Shifting const2 will never be equal to const1.
1013   // FIXME: This should always be handled by InstSimplify?
1014   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1015   return replaceInstUsesWith(I, TorF);
1016 }
1017 
1018 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1019 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1020 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1021                                                      const APInt &AP1,
1022                                                      const APInt &AP2) {
1023   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1024 
1025   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1026     if (I.getPredicate() == I.ICMP_NE)
1027       Pred = CmpInst::getInversePredicate(Pred);
1028     return new ICmpInst(Pred, LHS, RHS);
1029   };
1030 
1031   // Don't bother doing any work for cases which InstSimplify handles.
1032   if (AP2.isZero())
1033     return nullptr;
1034 
1035   unsigned AP2TrailingZeros = AP2.countr_zero();
1036 
1037   if (!AP1 && AP2TrailingZeros != 0)
1038     return getICmp(
1039         I.ICMP_UGE, A,
1040         ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1041 
1042   if (AP1 == AP2)
1043     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1044 
1045   // Get the distance between the lowest bits that are set.
1046   int Shift = AP1.countr_zero() - AP2TrailingZeros;
1047 
1048   if (Shift > 0 && AP2.shl(Shift) == AP1)
1049     return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1050 
1051   // Shifting const2 will never be equal to const1.
1052   // FIXME: This should always be handled by InstSimplify?
1053   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1054   return replaceInstUsesWith(I, TorF);
1055 }
1056 
1057 /// The caller has matched a pattern of the form:
1058 ///   I = icmp ugt (add (add A, B), CI2), CI1
1059 /// If this is of the form:
1060 ///   sum = a + b
1061 ///   if (sum+128 >u 255)
1062 /// Then replace it with llvm.sadd.with.overflow.i8.
1063 ///
1064 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1065                                           ConstantInt *CI2, ConstantInt *CI1,
1066                                           InstCombinerImpl &IC) {
1067   // The transformation we're trying to do here is to transform this into an
1068   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1069   // with a narrower add, and discard the add-with-constant that is part of the
1070   // range check (if we can't eliminate it, this isn't profitable).
1071 
1072   // In order to eliminate the add-with-constant, the compare can be its only
1073   // use.
1074   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1075   if (!AddWithCst->hasOneUse())
1076     return nullptr;
1077 
1078   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1079   if (!CI2->getValue().isPowerOf2())
1080     return nullptr;
1081   unsigned NewWidth = CI2->getValue().countr_zero();
1082   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1083     return nullptr;
1084 
1085   // The width of the new add formed is 1 more than the bias.
1086   ++NewWidth;
1087 
1088   // Check to see that CI1 is an all-ones value with NewWidth bits.
1089   if (CI1->getBitWidth() == NewWidth ||
1090       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1091     return nullptr;
1092 
1093   // This is only really a signed overflow check if the inputs have been
1094   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1095   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1096   if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1097       IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1098     return nullptr;
1099 
1100   // In order to replace the original add with a narrower
1101   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1102   // and truncates that discard the high bits of the add.  Verify that this is
1103   // the case.
1104   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1105   for (User *U : OrigAdd->users()) {
1106     if (U == AddWithCst)
1107       continue;
1108 
1109     // Only accept truncates for now.  We would really like a nice recursive
1110     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1111     // chain to see which bits of a value are actually demanded.  If the
1112     // original add had another add which was then immediately truncated, we
1113     // could still do the transformation.
1114     TruncInst *TI = dyn_cast<TruncInst>(U);
1115     if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1116       return nullptr;
1117   }
1118 
1119   // If the pattern matches, truncate the inputs to the narrower type and
1120   // use the sadd_with_overflow intrinsic to efficiently compute both the
1121   // result and the overflow bit.
1122   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1123   Function *F = Intrinsic::getDeclaration(
1124       I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1125 
1126   InstCombiner::BuilderTy &Builder = IC.Builder;
1127 
1128   // Put the new code above the original add, in case there are any uses of the
1129   // add between the add and the compare.
1130   Builder.SetInsertPoint(OrigAdd);
1131 
1132   Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1133   Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1134   CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1135   Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1136   Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1137 
1138   // The inner add was the result of the narrow add, zero extended to the
1139   // wider type.  Replace it with the result computed by the intrinsic.
1140   IC.replaceInstUsesWith(*OrigAdd, ZExt);
1141   IC.eraseInstFromFunction(*OrigAdd);
1142 
1143   // The original icmp gets replaced with the overflow value.
1144   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1145 }
1146 
1147 /// If we have:
1148 ///   icmp eq/ne (urem/srem %x, %y), 0
1149 /// iff %y is a power-of-two, we can replace this with a bit test:
1150 ///   icmp eq/ne (and %x, (add %y, -1)), 0
1151 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1152   // This fold is only valid for equality predicates.
1153   if (!I.isEquality())
1154     return nullptr;
1155   ICmpInst::Predicate Pred;
1156   Value *X, *Y, *Zero;
1157   if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1158                         m_CombineAnd(m_Zero(), m_Value(Zero)))))
1159     return nullptr;
1160   if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1161     return nullptr;
1162   // This may increase instruction count, we don't enforce that Y is a constant.
1163   Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1164   Value *Masked = Builder.CreateAnd(X, Mask);
1165   return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1166 }
1167 
1168 /// Fold equality-comparison between zero and any (maybe truncated) right-shift
1169 /// by one-less-than-bitwidth into a sign test on the original value.
1170 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1171   Instruction *Val;
1172   ICmpInst::Predicate Pred;
1173   if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1174     return nullptr;
1175 
1176   Value *X;
1177   Type *XTy;
1178 
1179   Constant *C;
1180   if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1181     XTy = X->getType();
1182     unsigned XBitWidth = XTy->getScalarSizeInBits();
1183     if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1184                                      APInt(XBitWidth, XBitWidth - 1))))
1185       return nullptr;
1186   } else if (isa<BinaryOperator>(Val) &&
1187              (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1188                   cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1189                   /*AnalyzeForSignBitExtraction=*/true))) {
1190     XTy = X->getType();
1191   } else
1192     return nullptr;
1193 
1194   return ICmpInst::Create(Instruction::ICmp,
1195                           Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1196                                                     : ICmpInst::ICMP_SLT,
1197                           X, ConstantInt::getNullValue(XTy));
1198 }
1199 
1200 // Handle  icmp pred X, 0
1201 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1202   CmpInst::Predicate Pred = Cmp.getPredicate();
1203   if (!match(Cmp.getOperand(1), m_Zero()))
1204     return nullptr;
1205 
1206   // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1207   if (Pred == ICmpInst::ICMP_SGT) {
1208     Value *A, *B;
1209     if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1210       if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1211         return new ICmpInst(Pred, B, Cmp.getOperand(1));
1212       if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1213         return new ICmpInst(Pred, A, Cmp.getOperand(1));
1214     }
1215   }
1216 
1217   if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1218     return New;
1219 
1220   // Given:
1221   //   icmp eq/ne (urem %x, %y), 0
1222   // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1223   //   icmp eq/ne %x, 0
1224   Value *X, *Y;
1225   if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1226       ICmpInst::isEquality(Pred)) {
1227     KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1228     KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1229     if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1230       return new ICmpInst(Pred, X, Cmp.getOperand(1));
1231   }
1232 
1233   // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1234   // odd/non-zero/there is no overflow.
1235   if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1236       ICmpInst::isEquality(Pred)) {
1237 
1238     KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1239     // if X % 2 != 0
1240     //    (icmp eq/ne Y)
1241     if (XKnown.countMaxTrailingZeros() == 0)
1242       return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1243 
1244     KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1245     // if Y % 2 != 0
1246     //    (icmp eq/ne X)
1247     if (YKnown.countMaxTrailingZeros() == 0)
1248       return new ICmpInst(Pred, X, Cmp.getOperand(1));
1249 
1250     auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1251     if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1252       const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1253       // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1254       // but to avoid unnecessary work, first just if this is an obvious case.
1255 
1256       // if X non-zero and NoOverflow(X * Y)
1257       //    (icmp eq/ne Y)
1258       if (!XKnown.One.isZero() || isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
1259         return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1260 
1261       // if Y non-zero and NoOverflow(X * Y)
1262       //    (icmp eq/ne X)
1263       if (!YKnown.One.isZero() || isKnownNonZero(Y, DL, 0, Q.AC, Q.CxtI, Q.DT))
1264         return new ICmpInst(Pred, X, Cmp.getOperand(1));
1265     }
1266     // Note, we are skipping cases:
1267     //      if Y % 2 != 0 AND X % 2 != 0
1268     //          (false/true)
1269     //      if X non-zero and Y non-zero and NoOverflow(X * Y)
1270     //          (false/true)
1271     // Those can be simplified later as we would have already replaced the (icmp
1272     // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1273     // will fold to a constant elsewhere.
1274   }
1275   return nullptr;
1276 }
1277 
1278 /// Fold icmp Pred X, C.
1279 /// TODO: This code structure does not make sense. The saturating add fold
1280 /// should be moved to some other helper and extended as noted below (it is also
1281 /// possible that code has been made unnecessary - do we canonicalize IR to
1282 /// overflow/saturating intrinsics or not?).
1283 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1284   // Match the following pattern, which is a common idiom when writing
1285   // overflow-safe integer arithmetic functions. The source performs an addition
1286   // in wider type and explicitly checks for overflow using comparisons against
1287   // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1288   //
1289   // TODO: This could probably be generalized to handle other overflow-safe
1290   // operations if we worked out the formulas to compute the appropriate magic
1291   // constants.
1292   //
1293   // sum = a + b
1294   // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1295   CmpInst::Predicate Pred = Cmp.getPredicate();
1296   Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1297   Value *A, *B;
1298   ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1299   if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1300       match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1301     if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1302       return Res;
1303 
1304   // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1305   Constant *C = dyn_cast<Constant>(Op1);
1306   if (!C)
1307     return nullptr;
1308 
1309   if (auto *Phi = dyn_cast<PHINode>(Op0))
1310     if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1311       SmallVector<Constant *> Ops;
1312       for (Value *V : Phi->incoming_values()) {
1313         Constant *Res =
1314             ConstantFoldCompareInstOperands(Pred, cast<Constant>(V), C, DL);
1315         if (!Res)
1316           return nullptr;
1317         Ops.push_back(Res);
1318       }
1319       Builder.SetInsertPoint(Phi);
1320       PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1321       for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1322         NewPhi->addIncoming(V, Pred);
1323       return replaceInstUsesWith(Cmp, NewPhi);
1324     }
1325 
1326   return nullptr;
1327 }
1328 
1329 /// Canonicalize icmp instructions based on dominating conditions.
1330 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1331   // We already checked simple implication in InstSimplify, only handle complex
1332   // cases here.
1333   Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1334   ICmpInst::Predicate DomPred;
1335   const APInt *C;
1336   if (!match(Y, m_APInt(C)))
1337     return nullptr;
1338 
1339   CmpInst::Predicate Pred = Cmp.getPredicate();
1340   ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);
1341 
1342   auto handleDomCond = [&](Value *DomCond, bool CondIsTrue) -> Instruction * {
1343     const APInt *DomC;
1344     if (!match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1345       return nullptr;
1346     // We have 2 compares of a variable with constants. Calculate the constant
1347     // ranges of those compares to see if we can transform the 2nd compare:
1348     // DomBB:
1349     //   DomCond = icmp DomPred X, DomC
1350     //   br DomCond, CmpBB, FalseBB
1351     // CmpBB:
1352     //   Cmp = icmp Pred X, C
1353     if (!CondIsTrue)
1354       DomPred = CmpInst::getInversePredicate(DomPred);
1355     ConstantRange DominatingCR =
1356         ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1357     ConstantRange Intersection = DominatingCR.intersectWith(CR);
1358     ConstantRange Difference = DominatingCR.difference(CR);
1359     if (Intersection.isEmptySet())
1360       return replaceInstUsesWith(Cmp, Builder.getFalse());
1361     if (Difference.isEmptySet())
1362       return replaceInstUsesWith(Cmp, Builder.getTrue());
1363 
1364     // Canonicalizing a sign bit comparison that gets used in a branch,
1365     // pessimizes codegen by generating branch on zero instruction instead
1366     // of a test and branch. So we avoid canonicalizing in such situations
1367     // because test and branch instruction has better branch displacement
1368     // than compare and branch instruction.
1369     bool UnusedBit;
1370     bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1371     if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1372       return nullptr;
1373 
1374     // Avoid an infinite loop with min/max canonicalization.
1375     // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1376     if (Cmp.hasOneUse() &&
1377         match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1378       return nullptr;
1379 
1380     if (const APInt *EqC = Intersection.getSingleElement())
1381       return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1382     if (const APInt *NeC = Difference.getSingleElement())
1383       return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1384     return nullptr;
1385   };
1386 
1387   for (BranchInst *BI : DC.conditionsFor(X)) {
1388     auto *Cond = BI->getCondition();
1389     BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1390     if (DT.dominates(Edge0, Cmp.getParent())) {
1391       if (auto *V = handleDomCond(Cond, true))
1392         return V;
1393     } else {
1394       BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1395       if (DT.dominates(Edge1, Cmp.getParent()))
1396         if (auto *V = handleDomCond(Cond, false))
1397           return V;
1398     }
1399   }
1400 
1401   return nullptr;
1402 }
1403 
1404 /// Fold icmp (trunc X), C.
1405 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1406                                                      TruncInst *Trunc,
1407                                                      const APInt &C) {
1408   ICmpInst::Predicate Pred = Cmp.getPredicate();
1409   Value *X = Trunc->getOperand(0);
1410   if (C.isOne() && C.getBitWidth() > 1) {
1411     // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1412     Value *V = nullptr;
1413     if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1414       return new ICmpInst(ICmpInst::ICMP_SLT, V,
1415                           ConstantInt::get(V->getType(), 1));
1416   }
1417 
1418   Type *SrcTy = X->getType();
1419   unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1420            SrcBits = SrcTy->getScalarSizeInBits();
1421 
1422   // TODO: Handle any shifted constant by subtracting trailing zeros.
1423   // TODO: Handle non-equality predicates.
1424   Value *Y;
1425   if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1426     // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1427     // (trunc (1 << Y) to iN) != 0 --> Y u<  N
1428     if (C.isZero()) {
1429       auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1430       return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1431     }
1432     // (trunc (1 << Y) to iN) == 2**C --> Y == C
1433     // (trunc (1 << Y) to iN) != 2**C --> Y != C
1434     if (C.isPowerOf2())
1435       return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1436   }
1437 
1438   if (Cmp.isEquality() && Trunc->hasOneUse()) {
1439     // Canonicalize to a mask and wider compare if the wide type is suitable:
1440     // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1441     if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1442       Constant *Mask =
1443           ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1444       Value *And = Builder.CreateAnd(X, Mask);
1445       Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1446       return new ICmpInst(Pred, And, WideC);
1447     }
1448 
1449     // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1450     // of the high bits truncated out of x are known.
1451     KnownBits Known = computeKnownBits(X, 0, &Cmp);
1452 
1453     // If all the high bits are known, we can do this xform.
1454     if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1455       // Pull in the high bits from known-ones set.
1456       APInt NewRHS = C.zext(SrcBits);
1457       NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1458       return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1459     }
1460   }
1461 
1462   // Look through truncated right-shift of the sign-bit for a sign-bit check:
1463   // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0  --> ShOp <  0
1464   // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1465   Value *ShOp;
1466   const APInt *ShAmtC;
1467   bool TrueIfSigned;
1468   if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1469       match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1470       DstBits == SrcBits - ShAmtC->getZExtValue()) {
1471     return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1472                                        ConstantInt::getNullValue(SrcTy))
1473                         : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1474                                        ConstantInt::getAllOnesValue(SrcTy));
1475   }
1476 
1477   return nullptr;
1478 }
1479 
1480 /// Fold icmp (trunc X), (trunc Y).
1481 /// Fold icmp (trunc X), (zext Y).
1482 Instruction *
1483 InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1484                                               const SimplifyQuery &Q) {
1485   if (Cmp.isSigned())
1486     return nullptr;
1487 
1488   Value *X, *Y;
1489   ICmpInst::Predicate Pred;
1490   bool YIsZext = false;
1491   // Try to match icmp (trunc X), (trunc Y)
1492   if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1493     if (X->getType() != Y->getType() &&
1494         (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1495       return nullptr;
1496     if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1497         isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1498       std::swap(X, Y);
1499       Pred = Cmp.getSwappedPredicate(Pred);
1500     }
1501   }
1502   // Try to match icmp (trunc X), (zext Y)
1503   else if (match(&Cmp, m_c_ICmp(Pred, m_Trunc(m_Value(X)),
1504                                 m_OneUse(m_ZExt(m_Value(Y))))))
1505 
1506     YIsZext = true;
1507   else
1508     return nullptr;
1509 
1510   Type *TruncTy = Cmp.getOperand(0)->getType();
1511   unsigned TruncBits = TruncTy->getScalarSizeInBits();
1512 
1513   // If this transform will end up changing from desirable types -> undesirable
1514   // types skip it.
1515   if (isDesirableIntType(TruncBits) &&
1516       !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1517     return nullptr;
1518 
1519   // Check if the trunc is unneeded.
1520   KnownBits KnownX = llvm::computeKnownBits(X, /*Depth*/ 0, Q);
1521   if (KnownX.countMaxActiveBits() > TruncBits)
1522     return nullptr;
1523 
1524   if (!YIsZext) {
1525     // If Y is also a trunc, make sure it is unneeded.
1526     KnownBits KnownY = llvm::computeKnownBits(Y, /*Depth*/ 0, Q);
1527     if (KnownY.countMaxActiveBits() > TruncBits)
1528       return nullptr;
1529   }
1530 
1531   Value *NewY = Builder.CreateZExtOrTrunc(Y, X->getType());
1532   return new ICmpInst(Pred, X, NewY);
1533 }
1534 
1535 /// Fold icmp (xor X, Y), C.
1536 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1537                                                    BinaryOperator *Xor,
1538                                                    const APInt &C) {
1539   if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1540     return I;
1541 
1542   Value *X = Xor->getOperand(0);
1543   Value *Y = Xor->getOperand(1);
1544   const APInt *XorC;
1545   if (!match(Y, m_APInt(XorC)))
1546     return nullptr;
1547 
1548   // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1549   // fold the xor.
1550   ICmpInst::Predicate Pred = Cmp.getPredicate();
1551   bool TrueIfSigned = false;
1552   if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1553 
1554     // If the sign bit of the XorCst is not set, there is no change to
1555     // the operation, just stop using the Xor.
1556     if (!XorC->isNegative())
1557       return replaceOperand(Cmp, 0, X);
1558 
1559     // Emit the opposite comparison.
1560     if (TrueIfSigned)
1561       return new ICmpInst(ICmpInst::ICMP_SGT, X,
1562                           ConstantInt::getAllOnesValue(X->getType()));
1563     else
1564       return new ICmpInst(ICmpInst::ICMP_SLT, X,
1565                           ConstantInt::getNullValue(X->getType()));
1566   }
1567 
1568   if (Xor->hasOneUse()) {
1569     // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1570     if (!Cmp.isEquality() && XorC->isSignMask()) {
1571       Pred = Cmp.getFlippedSignednessPredicate();
1572       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1573     }
1574 
1575     // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1576     if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1577       Pred = Cmp.getFlippedSignednessPredicate();
1578       Pred = Cmp.getSwappedPredicate(Pred);
1579       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1580     }
1581   }
1582 
1583   // Mask constant magic can eliminate an 'xor' with unsigned compares.
1584   if (Pred == ICmpInst::ICMP_UGT) {
1585     // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1586     if (*XorC == ~C && (C + 1).isPowerOf2())
1587       return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1588     // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1589     if (*XorC == C && (C + 1).isPowerOf2())
1590       return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1591   }
1592   if (Pred == ICmpInst::ICMP_ULT) {
1593     // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1594     if (*XorC == -C && C.isPowerOf2())
1595       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1596                           ConstantInt::get(X->getType(), ~C));
1597     // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1598     if (*XorC == C && (-C).isPowerOf2())
1599       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1600                           ConstantInt::get(X->getType(), ~C));
1601   }
1602   return nullptr;
1603 }
1604 
1605 /// For power-of-2 C:
1606 /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1607 /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1608 Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1609                                                      BinaryOperator *Xor,
1610                                                      const APInt &C) {
1611   CmpInst::Predicate Pred = Cmp.getPredicate();
1612   APInt PowerOf2;
1613   if (Pred == ICmpInst::ICMP_ULT)
1614     PowerOf2 = C;
1615   else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1616     PowerOf2 = C + 1;
1617   else
1618     return nullptr;
1619   if (!PowerOf2.isPowerOf2())
1620     return nullptr;
1621   Value *X;
1622   const APInt *ShiftC;
1623   if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
1624                                    m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1625     return nullptr;
1626   uint64_t Shift = ShiftC->getLimitedValue();
1627   Type *XType = X->getType();
1628   if (Shift == 0 || PowerOf2.isMinSignedValue())
1629     return nullptr;
1630   Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1631   APInt Bound =
1632       Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1633   return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1634 }
1635 
1636 /// Fold icmp (and (sh X, Y), C2), C1.
1637 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1638                                                 BinaryOperator *And,
1639                                                 const APInt &C1,
1640                                                 const APInt &C2) {
1641   BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1642   if (!Shift || !Shift->isShift())
1643     return nullptr;
1644 
1645   // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1646   // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1647   // code produced by the clang front-end, for bitfield access.
1648   // This seemingly simple opportunity to fold away a shift turns out to be
1649   // rather complicated. See PR17827 for details.
1650   unsigned ShiftOpcode = Shift->getOpcode();
1651   bool IsShl = ShiftOpcode == Instruction::Shl;
1652   const APInt *C3;
1653   if (match(Shift->getOperand(1), m_APInt(C3))) {
1654     APInt NewAndCst, NewCmpCst;
1655     bool AnyCmpCstBitsShiftedOut;
1656     if (ShiftOpcode == Instruction::Shl) {
1657       // For a left shift, we can fold if the comparison is not signed. We can
1658       // also fold a signed comparison if the mask value and comparison value
1659       // are not negative. These constraints may not be obvious, but we can
1660       // prove that they are correct using an SMT solver.
1661       if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1662         return nullptr;
1663 
1664       NewCmpCst = C1.lshr(*C3);
1665       NewAndCst = C2.lshr(*C3);
1666       AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1667     } else if (ShiftOpcode == Instruction::LShr) {
1668       // For a logical right shift, we can fold if the comparison is not signed.
1669       // We can also fold a signed comparison if the shifted mask value and the
1670       // shifted comparison value are not negative. These constraints may not be
1671       // obvious, but we can prove that they are correct using an SMT solver.
1672       NewCmpCst = C1.shl(*C3);
1673       NewAndCst = C2.shl(*C3);
1674       AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1675       if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1676         return nullptr;
1677     } else {
1678       // For an arithmetic shift, check that both constants don't use (in a
1679       // signed sense) the top bits being shifted out.
1680       assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1681       NewCmpCst = C1.shl(*C3);
1682       NewAndCst = C2.shl(*C3);
1683       AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1684       if (NewAndCst.ashr(*C3) != C2)
1685         return nullptr;
1686     }
1687 
1688     if (AnyCmpCstBitsShiftedOut) {
1689       // If we shifted bits out, the fold is not going to work out. As a
1690       // special case, check to see if this means that the result is always
1691       // true or false now.
1692       if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1693         return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1694       if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1695         return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1696     } else {
1697       Value *NewAnd = Builder.CreateAnd(
1698           Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1699       return new ICmpInst(Cmp.getPredicate(),
1700           NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1701     }
1702   }
1703 
1704   // Turn ((X >> Y) & C2) == 0  into  (X & (C2 << Y)) == 0.  The latter is
1705   // preferable because it allows the C2 << Y expression to be hoisted out of a
1706   // loop if Y is invariant and X is not.
1707   if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1708       !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1709     // Compute C2 << Y.
1710     Value *NewShift =
1711         IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1712               : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1713 
1714     // Compute X & (C2 << Y).
1715     Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1716     return replaceOperand(Cmp, 0, NewAnd);
1717   }
1718 
1719   return nullptr;
1720 }
1721 
1722 /// Fold icmp (and X, C2), C1.
1723 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1724                                                      BinaryOperator *And,
1725                                                      const APInt &C1) {
1726   bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1727 
1728   // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1729   // TODO: We canonicalize to the longer form for scalars because we have
1730   // better analysis/folds for icmp, and codegen may be better with icmp.
1731   if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1732       match(And->getOperand(1), m_One()))
1733     return new TruncInst(And->getOperand(0), Cmp.getType());
1734 
1735   const APInt *C2;
1736   Value *X;
1737   if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1738     return nullptr;
1739 
1740   // Don't perform the following transforms if the AND has multiple uses
1741   if (!And->hasOneUse())
1742     return nullptr;
1743 
1744   if (Cmp.isEquality() && C1.isZero()) {
1745     // Restrict this fold to single-use 'and' (PR10267).
1746     // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1747     if (C2->isSignMask()) {
1748       Constant *Zero = Constant::getNullValue(X->getType());
1749       auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1750       return new ICmpInst(NewPred, X, Zero);
1751     }
1752 
1753     APInt NewC2 = *C2;
1754     KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1755     // Set high zeros of C2 to allow matching negated power-of-2.
1756     NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1757                                         Know.countMinLeadingZeros());
1758 
1759     // Restrict this fold only for single-use 'and' (PR10267).
1760     // ((%x & C) == 0) --> %x u< (-C)  iff (-C) is power of two.
1761     if (NewC2.isNegatedPowerOf2()) {
1762       Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1763       auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1764       return new ICmpInst(NewPred, X, NegBOC);
1765     }
1766   }
1767 
1768   // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1769   // the input width without changing the value produced, eliminate the cast:
1770   //
1771   // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1772   //
1773   // We can do this transformation if the constants do not have their sign bits
1774   // set or if it is an equality comparison. Extending a relational comparison
1775   // when we're checking the sign bit would not work.
1776   Value *W;
1777   if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1778       (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1779     // TODO: Is this a good transform for vectors? Wider types may reduce
1780     // throughput. Should this transform be limited (even for scalars) by using
1781     // shouldChangeType()?
1782     if (!Cmp.getType()->isVectorTy()) {
1783       Type *WideType = W->getType();
1784       unsigned WideScalarBits = WideType->getScalarSizeInBits();
1785       Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1786       Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1787       Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1788       return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1789     }
1790   }
1791 
1792   if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1793     return I;
1794 
1795   // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1796   // (icmp pred (and A, (or (shl 1, B), 1), 0))
1797   //
1798   // iff pred isn't signed
1799   if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1800       match(And->getOperand(1), m_One())) {
1801     Constant *One = cast<Constant>(And->getOperand(1));
1802     Value *Or = And->getOperand(0);
1803     Value *A, *B, *LShr;
1804     if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1805         match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1806       unsigned UsesRemoved = 0;
1807       if (And->hasOneUse())
1808         ++UsesRemoved;
1809       if (Or->hasOneUse())
1810         ++UsesRemoved;
1811       if (LShr->hasOneUse())
1812         ++UsesRemoved;
1813 
1814       // Compute A & ((1 << B) | 1)
1815       unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1816       if (UsesRemoved >= RequireUsesRemoved) {
1817         Value *NewOr =
1818             Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1819                                                /*HasNUW=*/true),
1820                              One, Or->getName());
1821         Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1822         return replaceOperand(Cmp, 0, NewAnd);
1823       }
1824     }
1825   }
1826 
1827   return nullptr;
1828 }
1829 
1830 /// Fold icmp (and X, Y), C.
1831 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1832                                                    BinaryOperator *And,
1833                                                    const APInt &C) {
1834   if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1835     return I;
1836 
1837   const ICmpInst::Predicate Pred = Cmp.getPredicate();
1838   bool TrueIfNeg;
1839   if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1840     // ((X - 1) & ~X) <  0 --> X == 0
1841     // ((X - 1) & ~X) >= 0 --> X != 0
1842     Value *X;
1843     if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1844         match(And->getOperand(1), m_Not(m_Specific(X)))) {
1845       auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1846       return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1847     }
1848     // (X & X) <  0 --> X == MinSignedC
1849     // (X & X) > -1 --> X != MinSignedC
1850     if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1851       Constant *MinSignedC = ConstantInt::get(
1852           X->getType(),
1853           APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1854       auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1855       return new ICmpInst(NewPred, X, MinSignedC);
1856     }
1857   }
1858 
1859   // TODO: These all require that Y is constant too, so refactor with the above.
1860 
1861   // Try to optimize things like "A[i] & 42 == 0" to index computations.
1862   Value *X = And->getOperand(0);
1863   Value *Y = And->getOperand(1);
1864   if (auto *C2 = dyn_cast<ConstantInt>(Y))
1865     if (auto *LI = dyn_cast<LoadInst>(X))
1866       if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1867         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1868           if (Instruction *Res =
1869                   foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1870             return Res;
1871 
1872   if (!Cmp.isEquality())
1873     return nullptr;
1874 
1875   // X & -C == -C -> X >  u ~C
1876   // X & -C != -C -> X <= u ~C
1877   //   iff C is a power of 2
1878   if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1879     auto NewPred =
1880         Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1881     return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1882   }
1883 
1884   // If we are testing the intersection of 2 select-of-nonzero-constants with no
1885   // common bits set, it's the same as checking if exactly one select condition
1886   // is set:
1887   // ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B
1888   // ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)
1889   // TODO: Generalize for non-constant values.
1890   // TODO: Handle signed/unsigned predicates.
1891   // TODO: Handle other bitwise logic connectors.
1892   // TODO: Extend to handle a non-zero compare constant.
1893   if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {
1894     assert(Cmp.isEquality() && "Not expecting non-equality predicates");
1895     Value *A, *B;
1896     const APInt *TC, *FC;
1897     if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&
1898         match(Y,
1899               m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&
1900         !TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {
1901       Value *R = Builder.CreateXor(A, B);
1902       if (Pred == CmpInst::ICMP_NE)
1903         R = Builder.CreateNot(R);
1904       return replaceInstUsesWith(Cmp, R);
1905     }
1906   }
1907 
1908   // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1909   // ((zext i1 X) & Y) != 0 -->  ((trunc Y) & X)
1910   // ((zext i1 X) & Y) == 1 -->  ((trunc Y) & X)
1911   // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1912   if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&
1913       X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1914     Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1915     if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1916       Value *And = Builder.CreateAnd(TruncY, X);
1917       return BinaryOperator::CreateNot(And);
1918     }
1919     return BinaryOperator::CreateAnd(TruncY, X);
1920   }
1921 
1922   return nullptr;
1923 }
1924 
1925 /// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
1926 static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
1927                                     InstCombiner::BuilderTy &Builder) {
1928   // Are we using xors or subs to bitwise check for a pair or pairs of
1929   // (in)equalities? Convert to a shorter form that has more potential to be
1930   // folded even further.
1931   // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
1932   // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
1933   // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
1934   // (X1 == X2) && (X3 == X4) && (X5 == X6)
1935   // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
1936   // (X1 != X2) || (X3 != X4) || (X5 != X6)
1937   SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
1938   SmallVector<Value *, 16> WorkList(1, Or);
1939 
1940   while (!WorkList.empty()) {
1941     auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
1942       Value *Lhs, *Rhs;
1943 
1944       if (match(OrOperatorArgument,
1945                 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
1946         CmpValues.emplace_back(Lhs, Rhs);
1947         return;
1948       }
1949 
1950       if (match(OrOperatorArgument,
1951                 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
1952         CmpValues.emplace_back(Lhs, Rhs);
1953         return;
1954       }
1955 
1956       WorkList.push_back(OrOperatorArgument);
1957     };
1958 
1959     Value *CurrentValue = WorkList.pop_back_val();
1960     Value *OrOperatorLhs, *OrOperatorRhs;
1961 
1962     if (!match(CurrentValue,
1963                m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
1964       return nullptr;
1965     }
1966 
1967     MatchOrOperatorArgument(OrOperatorRhs);
1968     MatchOrOperatorArgument(OrOperatorLhs);
1969   }
1970 
1971   ICmpInst::Predicate Pred = Cmp.getPredicate();
1972   auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1973   Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
1974                                      CmpValues.rbegin()->second);
1975 
1976   for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
1977     Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
1978     LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
1979   }
1980 
1981   return LhsCmp;
1982 }
1983 
1984 /// Fold icmp (or X, Y), C.
1985 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
1986                                                   BinaryOperator *Or,
1987                                                   const APInt &C) {
1988   ICmpInst::Predicate Pred = Cmp.getPredicate();
1989   if (C.isOne()) {
1990     // icmp slt signum(V) 1 --> icmp slt V, 1
1991     Value *V = nullptr;
1992     if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1993       return new ICmpInst(ICmpInst::ICMP_SLT, V,
1994                           ConstantInt::get(V->getType(), 1));
1995   }
1996 
1997   Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1998   const APInt *MaskC;
1999   if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2000     if (*MaskC == C && (C + 1).isPowerOf2()) {
2001       // X | C == C --> X <=u C
2002       // X | C != C --> X  >u C
2003       //   iff C+1 is a power of 2 (C is a bitmask of the low bits)
2004       Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2005       return new ICmpInst(Pred, OrOp0, OrOp1);
2006     }
2007 
2008     // More general: canonicalize 'equality with set bits mask' to
2009     // 'equality with clear bits mask'.
2010     // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2011     // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2012     if (Or->hasOneUse()) {
2013       Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2014       Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2015       return new ICmpInst(Pred, And, NewC);
2016     }
2017   }
2018 
2019   // (X | (X-1)) s<  0 --> X s< 1
2020   // (X | (X-1)) s> -1 --> X s> 0
2021   Value *X;
2022   bool TrueIfSigned;
2023   if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2024       match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {
2025     auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2026     Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2027     return new ICmpInst(NewPred, X, NewC);
2028   }
2029 
2030   const APInt *OrC;
2031   // icmp(X | OrC, C) --> icmp(X, 0)
2032   if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2033     switch (Pred) {
2034     // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2035     case ICmpInst::ICMP_SLT:
2036     // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2037     case ICmpInst::ICMP_SGE:
2038       if (OrC->sge(C))
2039         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2040       break;
2041     // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2042     case ICmpInst::ICMP_SLE:
2043     // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2044     case ICmpInst::ICMP_SGT:
2045       if (OrC->sgt(C))
2046         return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), X,
2047                             ConstantInt::getNullValue(X->getType()));
2048       break;
2049     default:
2050       break;
2051     }
2052   }
2053 
2054   if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2055     return nullptr;
2056 
2057   Value *P, *Q;
2058   if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
2059     // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2060     // -> and (icmp eq P, null), (icmp eq Q, null).
2061     Value *CmpP =
2062         Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2063     Value *CmpQ =
2064         Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2065     auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2066     return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2067   }
2068 
2069   if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2070     return replaceInstUsesWith(Cmp, V);
2071 
2072   return nullptr;
2073 }
2074 
2075 /// Fold icmp (mul X, Y), C.
2076 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2077                                                    BinaryOperator *Mul,
2078                                                    const APInt &C) {
2079   ICmpInst::Predicate Pred = Cmp.getPredicate();
2080   Type *MulTy = Mul->getType();
2081   Value *X = Mul->getOperand(0);
2082 
2083   // If there's no overflow:
2084   // X * X == 0 --> X == 0
2085   // X * X != 0 --> X != 0
2086   if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2087       (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2088     return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2089 
2090   const APInt *MulC;
2091   if (!match(Mul->getOperand(1), m_APInt(MulC)))
2092     return nullptr;
2093 
2094   // If this is a test of the sign bit and the multiply is sign-preserving with
2095   // a constant operand, use the multiply LHS operand instead:
2096   // (X * +MulC) < 0 --> X < 0
2097   // (X * -MulC) < 0 --> X > 0
2098   if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2099     if (MulC->isNegative())
2100       Pred = ICmpInst::getSwappedPredicate(Pred);
2101     return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2102   }
2103 
2104   if (MulC->isZero())
2105     return nullptr;
2106 
2107   // If the multiply does not wrap or the constant is odd, try to divide the
2108   // compare constant by the multiplication factor.
2109   if (Cmp.isEquality()) {
2110     // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2111     if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2112       Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2113       return new ICmpInst(Pred, X, NewC);
2114     }
2115 
2116     // C % MulC == 0 is weaker than we could use if MulC is odd because it
2117     // correct to transform if MulC * N == C including overflow. I.e with i8
2118     // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2119     // miss that case.
2120     if (C.urem(*MulC).isZero()) {
2121       // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2122       // (mul X, OddC) eq/ne N * C --> X eq/ne N
2123       if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2124         Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2125         return new ICmpInst(Pred, X, NewC);
2126       }
2127     }
2128   }
2129 
2130   // With a matching no-overflow guarantee, fold the constants:
2131   // (X * MulC) < C --> X < (C / MulC)
2132   // (X * MulC) > C --> X > (C / MulC)
2133   // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2134   Constant *NewC = nullptr;
2135   if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2136     // MININT / -1 --> overflow.
2137     if (C.isMinSignedValue() && MulC->isAllOnes())
2138       return nullptr;
2139     if (MulC->isNegative())
2140       Pred = ICmpInst::getSwappedPredicate(Pred);
2141 
2142     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2143       NewC = ConstantInt::get(
2144           MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
2145     } else {
2146       assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2147              "Unexpected predicate");
2148       NewC = ConstantInt::get(
2149           MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));
2150     }
2151   } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2152     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2153       NewC = ConstantInt::get(
2154           MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
2155     } else {
2156       assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2157              "Unexpected predicate");
2158       NewC = ConstantInt::get(
2159           MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));
2160     }
2161   }
2162 
2163   return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2164 }
2165 
2166 /// Fold icmp (shl 1, Y), C.
2167 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
2168                                    const APInt &C) {
2169   Value *Y;
2170   if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2171     return nullptr;
2172 
2173   Type *ShiftType = Shl->getType();
2174   unsigned TypeBits = C.getBitWidth();
2175   bool CIsPowerOf2 = C.isPowerOf2();
2176   ICmpInst::Predicate Pred = Cmp.getPredicate();
2177   if (Cmp.isUnsigned()) {
2178     // (1 << Y) pred C -> Y pred Log2(C)
2179     if (!CIsPowerOf2) {
2180       // (1 << Y) <  30 -> Y <= 4
2181       // (1 << Y) <= 30 -> Y <= 4
2182       // (1 << Y) >= 30 -> Y >  4
2183       // (1 << Y) >  30 -> Y >  4
2184       if (Pred == ICmpInst::ICMP_ULT)
2185         Pred = ICmpInst::ICMP_ULE;
2186       else if (Pred == ICmpInst::ICMP_UGE)
2187         Pred = ICmpInst::ICMP_UGT;
2188     }
2189 
2190     unsigned CLog2 = C.logBase2();
2191     return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2192   } else if (Cmp.isSigned()) {
2193     Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2194     // (1 << Y) >  0 -> Y != 31
2195     // (1 << Y) >  C -> Y != 31 if C is negative.
2196     if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2197       return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2198 
2199     // (1 << Y) <  0 -> Y == 31
2200     // (1 << Y) <  1 -> Y == 31
2201     // (1 << Y) <  C -> Y == 31 if C is negative and not signed min.
2202     // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2203     if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
2204       return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2205   }
2206 
2207   return nullptr;
2208 }
2209 
2210 /// Fold icmp (shl X, Y), C.
2211 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2212                                                    BinaryOperator *Shl,
2213                                                    const APInt &C) {
2214   const APInt *ShiftVal;
2215   if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2216     return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2217 
2218   ICmpInst::Predicate Pred = Cmp.getPredicate();
2219   // (icmp pred (shl nuw&nsw X, Y), Csle0)
2220   //      -> (icmp pred X, Csle0)
2221   //
2222   // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2223   // so X's must be what is used.
2224   if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2225     return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2226 
2227   // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2228   //      -> (icmp eq/ne X, 0)
2229   if (ICmpInst::isEquality(Pred) && C.isZero() &&
2230       (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2231     return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2232 
2233   // (icmp slt (shl nsw X, Y), 0/1)
2234   //      -> (icmp slt X, 0/1)
2235   // (icmp sgt (shl nsw X, Y), 0/-1)
2236   //      -> (icmp sgt X, 0/-1)
2237   //
2238   // NB: sge/sle with a constant will canonicalize to sgt/slt.
2239   if (Shl->hasNoSignedWrap() &&
2240       (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2241     if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2242       return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2243 
2244   const APInt *ShiftAmt;
2245   if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2246     return foldICmpShlOne(Cmp, Shl, C);
2247 
2248   // Check that the shift amount is in range. If not, don't perform undefined
2249   // shifts. When the shift is visited, it will be simplified.
2250   unsigned TypeBits = C.getBitWidth();
2251   if (ShiftAmt->uge(TypeBits))
2252     return nullptr;
2253 
2254   Value *X = Shl->getOperand(0);
2255   Type *ShType = Shl->getType();
2256 
2257   // NSW guarantees that we are only shifting out sign bits from the high bits,
2258   // so we can ASHR the compare constant without needing a mask and eliminate
2259   // the shift.
2260   if (Shl->hasNoSignedWrap()) {
2261     if (Pred == ICmpInst::ICMP_SGT) {
2262       // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2263       APInt ShiftedC = C.ashr(*ShiftAmt);
2264       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2265     }
2266     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2267         C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2268       APInt ShiftedC = C.ashr(*ShiftAmt);
2269       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2270     }
2271     if (Pred == ICmpInst::ICMP_SLT) {
2272       // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2273       // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2274       // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2275       // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2276       assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2277       APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2278       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2279     }
2280   }
2281 
2282   // NUW guarantees that we are only shifting out zero bits from the high bits,
2283   // so we can LSHR the compare constant without needing a mask and eliminate
2284   // the shift.
2285   if (Shl->hasNoUnsignedWrap()) {
2286     if (Pred == ICmpInst::ICMP_UGT) {
2287       // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2288       APInt ShiftedC = C.lshr(*ShiftAmt);
2289       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2290     }
2291     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2292         C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2293       APInt ShiftedC = C.lshr(*ShiftAmt);
2294       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2295     }
2296     if (Pred == ICmpInst::ICMP_ULT) {
2297       // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2298       // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2299       // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2300       // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2301       assert(C.ugt(0) && "ult 0 should have been eliminated");
2302       APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2303       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2304     }
2305   }
2306 
2307   if (Cmp.isEquality() && Shl->hasOneUse()) {
2308     // Strength-reduce the shift into an 'and'.
2309     Constant *Mask = ConstantInt::get(
2310         ShType,
2311         APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2312     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2313     Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2314     return new ICmpInst(Pred, And, LShrC);
2315   }
2316 
2317   // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2318   bool TrueIfSigned = false;
2319   if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2320     // (X << 31) <s 0  --> (X & 1) != 0
2321     Constant *Mask = ConstantInt::get(
2322         ShType,
2323         APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2324     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2325     return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2326                         And, Constant::getNullValue(ShType));
2327   }
2328 
2329   // Simplify 'shl' inequality test into 'and' equality test.
2330   if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2331     // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2332     if ((C + 1).isPowerOf2() &&
2333         (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2334       Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2335       return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2336                                                      : ICmpInst::ICMP_NE,
2337                           And, Constant::getNullValue(ShType));
2338     }
2339     // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2340     if (C.isPowerOf2() &&
2341         (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2342       Value *And =
2343           Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2344       return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2345                                                      : ICmpInst::ICMP_NE,
2346                           And, Constant::getNullValue(ShType));
2347     }
2348   }
2349 
2350   // Transform (icmp pred iM (shl iM %v, N), C)
2351   // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2352   // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2353   // This enables us to get rid of the shift in favor of a trunc that may be
2354   // free on the target. It has the additional benefit of comparing to a
2355   // smaller constant that may be more target-friendly.
2356   unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2357   if (Shl->hasOneUse() && Amt != 0 && C.countr_zero() >= Amt &&
2358       DL.isLegalInteger(TypeBits - Amt)) {
2359     Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2360     if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2361       TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2362     Constant *NewC =
2363         ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2364     return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2365   }
2366 
2367   return nullptr;
2368 }
2369 
2370 /// Fold icmp ({al}shr X, Y), C.
2371 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2372                                                    BinaryOperator *Shr,
2373                                                    const APInt &C) {
2374   // An exact shr only shifts out zero bits, so:
2375   // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2376   Value *X = Shr->getOperand(0);
2377   CmpInst::Predicate Pred = Cmp.getPredicate();
2378   if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2379     return new ICmpInst(Pred, X, Cmp.getOperand(1));
2380 
2381   bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2382   const APInt *ShiftValC;
2383   if (match(X, m_APInt(ShiftValC))) {
2384     if (Cmp.isEquality())
2385       return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2386 
2387     // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2388     // (ShiftValC >> Y) <s  0 --> Y == 0 with ShiftValC < 0
2389     bool TrueIfSigned;
2390     if (!IsAShr && ShiftValC->isNegative() &&
2391         isSignBitCheck(Pred, C, TrueIfSigned))
2392       return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2393                           Shr->getOperand(1),
2394                           ConstantInt::getNullValue(X->getType()));
2395 
2396     // If the shifted constant is a power-of-2, test the shift amount directly:
2397     // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2398     // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2399     if (!IsAShr && ShiftValC->isPowerOf2() &&
2400         (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2401       bool IsUGT = Pred == CmpInst::ICMP_UGT;
2402       assert(ShiftValC->uge(C) && "Expected simplify of compare");
2403       assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2404 
2405       unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2406       unsigned ShiftLZ = ShiftValC->countl_zero();
2407       Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2408       auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2409       return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2410     }
2411   }
2412 
2413   const APInt *ShiftAmtC;
2414   if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2415     return nullptr;
2416 
2417   // Check that the shift amount is in range. If not, don't perform undefined
2418   // shifts. When the shift is visited it will be simplified.
2419   unsigned TypeBits = C.getBitWidth();
2420   unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2421   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2422     return nullptr;
2423 
2424   bool IsExact = Shr->isExact();
2425   Type *ShrTy = Shr->getType();
2426   // TODO: If we could guarantee that InstSimplify would handle all of the
2427   // constant-value-based preconditions in the folds below, then we could assert
2428   // those conditions rather than checking them. This is difficult because of
2429   // undef/poison (PR34838).
2430   if (IsAShr && Shr->hasOneUse()) {
2431     if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2432       // When ShAmtC can be shifted losslessly:
2433       // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2434       // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2435       APInt ShiftedC = C.shl(ShAmtVal);
2436       if (ShiftedC.ashr(ShAmtVal) == C)
2437         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2438     }
2439     if (Pred == CmpInst::ICMP_SGT) {
2440       // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2441       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2442       if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2443           (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2444         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2445     }
2446     if (Pred == CmpInst::ICMP_UGT) {
2447       // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2448       // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2449       // clause accounts for that pattern.
2450       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2451       if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2452           (C + 1).shl(ShAmtVal).isMinSignedValue())
2453         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2454     }
2455 
2456     // If the compare constant has significant bits above the lowest sign-bit,
2457     // then convert an unsigned cmp to a test of the sign-bit:
2458     // (ashr X, ShiftC) u> C --> X s< 0
2459     // (ashr X, ShiftC) u< C --> X s> -1
2460     if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2461       if (Pred == CmpInst::ICMP_UGT) {
2462         return new ICmpInst(CmpInst::ICMP_SLT, X,
2463                             ConstantInt::getNullValue(ShrTy));
2464       }
2465       if (Pred == CmpInst::ICMP_ULT) {
2466         return new ICmpInst(CmpInst::ICMP_SGT, X,
2467                             ConstantInt::getAllOnesValue(ShrTy));
2468       }
2469     }
2470   } else if (!IsAShr) {
2471     if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2472       // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2473       // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2474       APInt ShiftedC = C.shl(ShAmtVal);
2475       if (ShiftedC.lshr(ShAmtVal) == C)
2476         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2477     }
2478     if (Pred == CmpInst::ICMP_UGT) {
2479       // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2480       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2481       if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2482         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2483     }
2484   }
2485 
2486   if (!Cmp.isEquality())
2487     return nullptr;
2488 
2489   // Handle equality comparisons of shift-by-constant.
2490 
2491   // If the comparison constant changes with the shift, the comparison cannot
2492   // succeed (bits of the comparison constant cannot match the shifted value).
2493   // This should be known by InstSimplify and already be folded to true/false.
2494   assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2495           (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2496          "Expected icmp+shr simplify did not occur.");
2497 
2498   // If the bits shifted out are known zero, compare the unshifted value:
2499   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
2500   if (Shr->isExact())
2501     return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2502 
2503   if (C.isZero()) {
2504     // == 0 is u< 1.
2505     if (Pred == CmpInst::ICMP_EQ)
2506       return new ICmpInst(CmpInst::ICMP_ULT, X,
2507                           ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2508     else
2509       return new ICmpInst(CmpInst::ICMP_UGT, X,
2510                           ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2511   }
2512 
2513   if (Shr->hasOneUse()) {
2514     // Canonicalize the shift into an 'and':
2515     // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2516     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2517     Constant *Mask = ConstantInt::get(ShrTy, Val);
2518     Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2519     return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2520   }
2521 
2522   return nullptr;
2523 }
2524 
2525 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2526                                                     BinaryOperator *SRem,
2527                                                     const APInt &C) {
2528   // Match an 'is positive' or 'is negative' comparison of remainder by a
2529   // constant power-of-2 value:
2530   // (X % pow2C) sgt/slt 0
2531   const ICmpInst::Predicate Pred = Cmp.getPredicate();
2532   if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2533       Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2534     return nullptr;
2535 
2536   // TODO: The one-use check is standard because we do not typically want to
2537   //       create longer instruction sequences, but this might be a special-case
2538   //       because srem is not good for analysis or codegen.
2539   if (!SRem->hasOneUse())
2540     return nullptr;
2541 
2542   const APInt *DivisorC;
2543   if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2544     return nullptr;
2545 
2546   // For cmp_sgt/cmp_slt only zero valued C is handled.
2547   // For cmp_eq/cmp_ne only positive valued C is handled.
2548   if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2549        !C.isZero()) ||
2550       ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2551        !C.isStrictlyPositive()))
2552     return nullptr;
2553 
2554   // Mask off the sign bit and the modulo bits (low-bits).
2555   Type *Ty = SRem->getType();
2556   APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2557   Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2558   Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2559 
2560   if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2561     return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2562 
2563   // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2564   // bit is set. Example:
2565   // (i8 X % 32) s> 0 --> (X & 159) s> 0
2566   if (Pred == ICmpInst::ICMP_SGT)
2567     return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2568 
2569   // For 'is negative?' check that the sign-bit is set and at least 1 masked
2570   // bit is set. Example:
2571   // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2572   return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2573 }
2574 
2575 /// Fold icmp (udiv X, Y), C.
2576 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2577                                                     BinaryOperator *UDiv,
2578                                                     const APInt &C) {
2579   ICmpInst::Predicate Pred = Cmp.getPredicate();
2580   Value *X = UDiv->getOperand(0);
2581   Value *Y = UDiv->getOperand(1);
2582   Type *Ty = UDiv->getType();
2583 
2584   const APInt *C2;
2585   if (!match(X, m_APInt(C2)))
2586     return nullptr;
2587 
2588   assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2589 
2590   // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2591   if (Pred == ICmpInst::ICMP_UGT) {
2592     assert(!C.isMaxValue() &&
2593            "icmp ugt X, UINT_MAX should have been simplified already.");
2594     return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2595                         ConstantInt::get(Ty, C2->udiv(C + 1)));
2596   }
2597 
2598   // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2599   if (Pred == ICmpInst::ICMP_ULT) {
2600     assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2601     return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2602                         ConstantInt::get(Ty, C2->udiv(C)));
2603   }
2604 
2605   return nullptr;
2606 }
2607 
2608 /// Fold icmp ({su}div X, Y), C.
2609 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2610                                                    BinaryOperator *Div,
2611                                                    const APInt &C) {
2612   ICmpInst::Predicate Pred = Cmp.getPredicate();
2613   Value *X = Div->getOperand(0);
2614   Value *Y = Div->getOperand(1);
2615   Type *Ty = Div->getType();
2616   bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2617 
2618   // If unsigned division and the compare constant is bigger than
2619   // UMAX/2 (negative), there's only one pair of values that satisfies an
2620   // equality check, so eliminate the division:
2621   // (X u/ Y) == C --> (X == C) && (Y == 1)
2622   // (X u/ Y) != C --> (X != C) || (Y != 1)
2623   // Similarly, if signed division and the compare constant is exactly SMIN:
2624   // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2625   // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2626   if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2627       (!DivIsSigned || C.isMinSignedValue()))   {
2628     Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2629     Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2630     auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2631     return BinaryOperator::Create(Logic, XBig, YOne);
2632   }
2633 
2634   // Fold: icmp pred ([us]div X, C2), C -> range test
2635   // Fold this div into the comparison, producing a range check.
2636   // Determine, based on the divide type, what the range is being
2637   // checked.  If there is an overflow on the low or high side, remember
2638   // it, otherwise compute the range [low, hi) bounding the new value.
2639   // See: InsertRangeTest above for the kinds of replacements possible.
2640   const APInt *C2;
2641   if (!match(Y, m_APInt(C2)))
2642     return nullptr;
2643 
2644   // FIXME: If the operand types don't match the type of the divide
2645   // then don't attempt this transform. The code below doesn't have the
2646   // logic to deal with a signed divide and an unsigned compare (and
2647   // vice versa). This is because (x /s C2) <s C  produces different
2648   // results than (x /s C2) <u C or (x /u C2) <s C or even
2649   // (x /u C2) <u C.  Simply casting the operands and result won't
2650   // work. :(  The if statement below tests that condition and bails
2651   // if it finds it.
2652   if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2653     return nullptr;
2654 
2655   // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2656   // INT_MIN will also fail if the divisor is 1. Although folds of all these
2657   // division-by-constant cases should be present, we can not assert that they
2658   // have happened before we reach this icmp instruction.
2659   if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2660     return nullptr;
2661 
2662   // Compute Prod = C * C2. We are essentially solving an equation of
2663   // form X / C2 = C. We solve for X by multiplying C2 and C.
2664   // By solving for X, we can turn this into a range check instead of computing
2665   // a divide.
2666   APInt Prod = C * *C2;
2667 
2668   // Determine if the product overflows by seeing if the product is not equal to
2669   // the divide. Make sure we do the same kind of divide as in the LHS
2670   // instruction that we're folding.
2671   bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2672 
2673   // If the division is known to be exact, then there is no remainder from the
2674   // divide, so the covered range size is unit, otherwise it is the divisor.
2675   APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2676 
2677   // Figure out the interval that is being checked.  For example, a comparison
2678   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2679   // Compute this interval based on the constants involved and the signedness of
2680   // the compare/divide.  This computes a half-open interval, keeping track of
2681   // whether either value in the interval overflows.  After analysis each
2682   // overflow variable is set to 0 if it's corresponding bound variable is valid
2683   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2684   int LoOverflow = 0, HiOverflow = 0;
2685   APInt LoBound, HiBound;
2686 
2687   if (!DivIsSigned) { // udiv
2688     // e.g. X/5 op 3  --> [15, 20)
2689     LoBound = Prod;
2690     HiOverflow = LoOverflow = ProdOV;
2691     if (!HiOverflow) {
2692       // If this is not an exact divide, then many values in the range collapse
2693       // to the same result value.
2694       HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2695     }
2696   } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2697     if (C.isZero()) {                    // (X / pos) op 0
2698       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
2699       LoBound = -(RangeSize - 1);
2700       HiBound = RangeSize;
2701     } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2702       LoBound = Prod;                    // e.g.   X/5 op 3 --> [15, 20)
2703       HiOverflow = LoOverflow = ProdOV;
2704       if (!HiOverflow)
2705         HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2706     } else { // (X / pos) op neg
2707       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
2708       HiBound = Prod + 1;
2709       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2710       if (!LoOverflow) {
2711         APInt DivNeg = -RangeSize;
2712         LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2713       }
2714     }
2715   } else if (C2->isNegative()) { // Divisor is < 0.
2716     if (Div->isExact())
2717       RangeSize.negate();
2718     if (C.isZero()) { // (X / neg) op 0
2719       // e.g. X/-5 op 0  --> [-4, 5)
2720       LoBound = RangeSize + 1;
2721       HiBound = -RangeSize;
2722       if (HiBound == *C2) { // -INTMIN = INTMIN
2723         HiOverflow = 1;     // [INTMIN+1, overflow)
2724         HiBound = APInt();  // e.g. X/INTMIN = 0 --> X > INTMIN
2725       }
2726     } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2727       // e.g. X/-5 op 3  --> [-19, -14)
2728       HiBound = Prod + 1;
2729       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2730       if (!LoOverflow)
2731         LoOverflow =
2732             addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2733     } else {          // (X / neg) op neg
2734       LoBound = Prod; // e.g. X/-5 op -3  --> [15, 20)
2735       LoOverflow = HiOverflow = ProdOV;
2736       if (!HiOverflow)
2737         HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2738     }
2739 
2740     // Dividing by a negative swaps the condition.  LT <-> GT
2741     Pred = ICmpInst::getSwappedPredicate(Pred);
2742   }
2743 
2744   switch (Pred) {
2745   default:
2746     llvm_unreachable("Unhandled icmp predicate!");
2747   case ICmpInst::ICMP_EQ:
2748     if (LoOverflow && HiOverflow)
2749       return replaceInstUsesWith(Cmp, Builder.getFalse());
2750     if (HiOverflow)
2751       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2752                           X, ConstantInt::get(Ty, LoBound));
2753     if (LoOverflow)
2754       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2755                           X, ConstantInt::get(Ty, HiBound));
2756     return replaceInstUsesWith(
2757         Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2758   case ICmpInst::ICMP_NE:
2759     if (LoOverflow && HiOverflow)
2760       return replaceInstUsesWith(Cmp, Builder.getTrue());
2761     if (HiOverflow)
2762       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2763                           X, ConstantInt::get(Ty, LoBound));
2764     if (LoOverflow)
2765       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2766                           X, ConstantInt::get(Ty, HiBound));
2767     return replaceInstUsesWith(
2768         Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2769   case ICmpInst::ICMP_ULT:
2770   case ICmpInst::ICMP_SLT:
2771     if (LoOverflow == +1) // Low bound is greater than input range.
2772       return replaceInstUsesWith(Cmp, Builder.getTrue());
2773     if (LoOverflow == -1) // Low bound is less than input range.
2774       return replaceInstUsesWith(Cmp, Builder.getFalse());
2775     return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2776   case ICmpInst::ICMP_UGT:
2777   case ICmpInst::ICMP_SGT:
2778     if (HiOverflow == +1) // High bound greater than input range.
2779       return replaceInstUsesWith(Cmp, Builder.getFalse());
2780     if (HiOverflow == -1) // High bound less than input range.
2781       return replaceInstUsesWith(Cmp, Builder.getTrue());
2782     if (Pred == ICmpInst::ICMP_UGT)
2783       return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2784     return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2785   }
2786 
2787   return nullptr;
2788 }
2789 
2790 /// Fold icmp (sub X, Y), C.
2791 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2792                                                    BinaryOperator *Sub,
2793                                                    const APInt &C) {
2794   Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2795   ICmpInst::Predicate Pred = Cmp.getPredicate();
2796   Type *Ty = Sub->getType();
2797 
2798   // (SubC - Y) == C) --> Y == (SubC - C)
2799   // (SubC - Y) != C) --> Y != (SubC - C)
2800   Constant *SubC;
2801   if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2802     return new ICmpInst(Pred, Y,
2803                         ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
2804   }
2805 
2806   // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2807   const APInt *C2;
2808   APInt SubResult;
2809   ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2810   bool HasNSW = Sub->hasNoSignedWrap();
2811   bool HasNUW = Sub->hasNoUnsignedWrap();
2812   if (match(X, m_APInt(C2)) &&
2813       ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2814       !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2815     return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2816 
2817   // X - Y == 0 --> X == Y.
2818   // X - Y != 0 --> X != Y.
2819   // TODO: We allow this with multiple uses as long as the other uses are not
2820   //       in phis. The phi use check is guarding against a codegen regression
2821   //       for a loop test. If the backend could undo this (and possibly
2822   //       subsequent transforms), we would not need this hack.
2823   if (Cmp.isEquality() && C.isZero() &&
2824       none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2825     return new ICmpInst(Pred, X, Y);
2826 
2827   // The following transforms are only worth it if the only user of the subtract
2828   // is the icmp.
2829   // TODO: This is an artificial restriction for all of the transforms below
2830   //       that only need a single replacement icmp. Can these use the phi test
2831   //       like the transform above here?
2832   if (!Sub->hasOneUse())
2833     return nullptr;
2834 
2835   if (Sub->hasNoSignedWrap()) {
2836     // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2837     if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2838       return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2839 
2840     // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2841     if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2842       return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2843 
2844     // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2845     if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2846       return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2847 
2848     // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2849     if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2850       return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2851   }
2852 
2853   if (!match(X, m_APInt(C2)))
2854     return nullptr;
2855 
2856   // C2 - Y <u C -> (Y | (C - 1)) == C2
2857   //   iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2858   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2859       (*C2 & (C - 1)) == (C - 1))
2860     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2861 
2862   // C2 - Y >u C -> (Y | C) != C2
2863   //   iff C2 & C == C and C + 1 is a power of 2
2864   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2865     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2866 
2867   // We have handled special cases that reduce.
2868   // Canonicalize any remaining sub to add as:
2869   // (C2 - Y) > C --> (Y + ~C2) < ~C
2870   Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2871                                  HasNUW, HasNSW);
2872   return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2873 }
2874 
2875 static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
2876                                    Value *Op1, IRBuilderBase &Builder,
2877                                    bool HasOneUse) {
2878   auto FoldConstant = [&](bool Val) {
2879     Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
2880     if (Op0->getType()->isVectorTy())
2881       Res = ConstantVector::getSplat(
2882           cast<VectorType>(Op0->getType())->getElementCount(), Res);
2883     return Res;
2884   };
2885 
2886   switch (Table.to_ulong()) {
2887   case 0: // 0 0 0 0
2888     return FoldConstant(false);
2889   case 1: // 0 0 0 1
2890     return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
2891   case 2: // 0 0 1 0
2892     return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
2893   case 3: // 0 0 1 1
2894     return Builder.CreateNot(Op0);
2895   case 4: // 0 1 0 0
2896     return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
2897   case 5: // 0 1 0 1
2898     return Builder.CreateNot(Op1);
2899   case 6: // 0 1 1 0
2900     return Builder.CreateXor(Op0, Op1);
2901   case 7: // 0 1 1 1
2902     return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
2903   case 8: // 1 0 0 0
2904     return Builder.CreateAnd(Op0, Op1);
2905   case 9: // 1 0 0 1
2906     return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
2907   case 10: // 1 0 1 0
2908     return Op1;
2909   case 11: // 1 0 1 1
2910     return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
2911   case 12: // 1 1 0 0
2912     return Op0;
2913   case 13: // 1 1 0 1
2914     return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
2915   case 14: // 1 1 1 0
2916     return Builder.CreateOr(Op0, Op1);
2917   case 15: // 1 1 1 1
2918     return FoldConstant(true);
2919   default:
2920     llvm_unreachable("Invalid Operation");
2921   }
2922   return nullptr;
2923 }
2924 
2925 /// Fold icmp (add X, Y), C.
2926 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
2927                                                    BinaryOperator *Add,
2928                                                    const APInt &C) {
2929   Value *Y = Add->getOperand(1);
2930   Value *X = Add->getOperand(0);
2931 
2932   Value *Op0, *Op1;
2933   Instruction *Ext0, *Ext1;
2934   const CmpInst::Predicate Pred = Cmp.getPredicate();
2935   if (match(Add,
2936             m_Add(m_CombineAnd(m_Instruction(Ext0), m_ZExtOrSExt(m_Value(Op0))),
2937                   m_CombineAnd(m_Instruction(Ext1),
2938                                m_ZExtOrSExt(m_Value(Op1))))) &&
2939       Op0->getType()->isIntOrIntVectorTy(1) &&
2940       Op1->getType()->isIntOrIntVectorTy(1)) {
2941     unsigned BW = C.getBitWidth();
2942     std::bitset<4> Table;
2943     auto ComputeTable = [&](bool Op0Val, bool Op1Val) {
2944       int Res = 0;
2945       if (Op0Val)
2946         Res += isa<ZExtInst>(Ext0) ? 1 : -1;
2947       if (Op1Val)
2948         Res += isa<ZExtInst>(Ext1) ? 1 : -1;
2949       return ICmpInst::compare(APInt(BW, Res, true), C, Pred);
2950     };
2951 
2952     Table[0] = ComputeTable(false, false);
2953     Table[1] = ComputeTable(false, true);
2954     Table[2] = ComputeTable(true, false);
2955     Table[3] = ComputeTable(true, true);
2956     if (auto *Cond =
2957             createLogicFromTable(Table, Op0, Op1, Builder, Add->hasOneUse()))
2958       return replaceInstUsesWith(Cmp, Cond);
2959   }
2960   const APInt *C2;
2961   if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2962     return nullptr;
2963 
2964   // Fold icmp pred (add X, C2), C.
2965   Type *Ty = Add->getType();
2966 
2967   // If the add does not wrap, we can always adjust the compare by subtracting
2968   // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2969   // are canonicalized to SGT/SLT/UGT/ULT.
2970   if ((Add->hasNoSignedWrap() &&
2971        (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2972       (Add->hasNoUnsignedWrap() &&
2973        (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2974     bool Overflow;
2975     APInt NewC =
2976         Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2977     // If there is overflow, the result must be true or false.
2978     // TODO: Can we assert there is no overflow because InstSimplify always
2979     // handles those cases?
2980     if (!Overflow)
2981       // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2982       return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2983   }
2984 
2985   auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2986   const APInt &Upper = CR.getUpper();
2987   const APInt &Lower = CR.getLower();
2988   if (Cmp.isSigned()) {
2989     if (Lower.isSignMask())
2990       return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2991     if (Upper.isSignMask())
2992       return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2993   } else {
2994     if (Lower.isMinValue())
2995       return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2996     if (Upper.isMinValue())
2997       return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2998   }
2999 
3000   // This set of folds is intentionally placed after folds that use no-wrapping
3001   // flags because those folds are likely better for later analysis/codegen.
3002   const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3003   const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3004 
3005   // Fold compare with offset to opposite sign compare if it eliminates offset:
3006   // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3007   if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3008     return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3009 
3010   // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3011   if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3012     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3013 
3014   // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3015   if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3016     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3017 
3018   // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3019   if (Pred == CmpInst::ICMP_SLT && C == *C2)
3020     return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3021 
3022   // (X + -1) <u C --> X <=u C (if X is never null)
3023   if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3024     const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3025     if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
3026       return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3027   }
3028 
3029   if (!Add->hasOneUse())
3030     return nullptr;
3031 
3032   // X+C <u C2 -> (X & -C2) == C
3033   //   iff C & (C2-1) == 0
3034   //       C2 is a power of 2
3035   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3036     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3037                         ConstantExpr::getNeg(cast<Constant>(Y)));
3038 
3039   // X+C >u C2 -> (X & ~C2) != C
3040   //   iff C & C2 == 0
3041   //       C2+1 is a power of 2
3042   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3043     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3044                         ConstantExpr::getNeg(cast<Constant>(Y)));
3045 
3046   // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3047   // to the ult form.
3048   // X+C2 >u C -> X+(C2-C-1) <u ~C
3049   if (Pred == ICmpInst::ICMP_UGT)
3050     return new ICmpInst(ICmpInst::ICMP_ULT,
3051                         Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3052                         ConstantInt::get(Ty, ~C));
3053 
3054   return nullptr;
3055 }
3056 
3057 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3058                                                Value *&RHS, ConstantInt *&Less,
3059                                                ConstantInt *&Equal,
3060                                                ConstantInt *&Greater) {
3061   // TODO: Generalize this to work with other comparison idioms or ensure
3062   // they get canonicalized into this form.
3063 
3064   // select i1 (a == b),
3065   //        i32 Equal,
3066   //        i32 (select i1 (a < b), i32 Less, i32 Greater)
3067   // where Equal, Less and Greater are placeholders for any three constants.
3068   ICmpInst::Predicate PredA;
3069   if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3070       !ICmpInst::isEquality(PredA))
3071     return false;
3072   Value *EqualVal = SI->getTrueValue();
3073   Value *UnequalVal = SI->getFalseValue();
3074   // We still can get non-canonical predicate here, so canonicalize.
3075   if (PredA == ICmpInst::ICMP_NE)
3076     std::swap(EqualVal, UnequalVal);
3077   if (!match(EqualVal, m_ConstantInt(Equal)))
3078     return false;
3079   ICmpInst::Predicate PredB;
3080   Value *LHS2, *RHS2;
3081   if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3082                                   m_ConstantInt(Less), m_ConstantInt(Greater))))
3083     return false;
3084   // We can get predicate mismatch here, so canonicalize if possible:
3085   // First, ensure that 'LHS' match.
3086   if (LHS2 != LHS) {
3087     // x sgt y <--> y slt x
3088     std::swap(LHS2, RHS2);
3089     PredB = ICmpInst::getSwappedPredicate(PredB);
3090   }
3091   if (LHS2 != LHS)
3092     return false;
3093   // We also need to canonicalize 'RHS'.
3094   if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3095     // x sgt C-1  <-->  x sge C  <-->  not(x slt C)
3096     auto FlippedStrictness =
3097         InstCombiner::getFlippedStrictnessPredicateAndConstant(
3098             PredB, cast<Constant>(RHS2));
3099     if (!FlippedStrictness)
3100       return false;
3101     assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3102            "basic correctness failure");
3103     RHS2 = FlippedStrictness->second;
3104     // And kind-of perform the result swap.
3105     std::swap(Less, Greater);
3106     PredB = ICmpInst::ICMP_SLT;
3107   }
3108   return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3109 }
3110 
3111 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3112                                                       SelectInst *Select,
3113                                                       ConstantInt *C) {
3114 
3115   assert(C && "Cmp RHS should be a constant int!");
3116   // If we're testing a constant value against the result of a three way
3117   // comparison, the result can be expressed directly in terms of the
3118   // original values being compared.  Note: We could possibly be more
3119   // aggressive here and remove the hasOneUse test. The original select is
3120   // really likely to simplify or sink when we remove a test of the result.
3121   Value *OrigLHS, *OrigRHS;
3122   ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3123   if (Cmp.hasOneUse() &&
3124       matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3125                               C3GreaterThan)) {
3126     assert(C1LessThan && C2Equal && C3GreaterThan);
3127 
3128     bool TrueWhenLessThan =
3129         ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
3130             ->isAllOnesValue();
3131     bool TrueWhenEqual =
3132         ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
3133             ->isAllOnesValue();
3134     bool TrueWhenGreaterThan =
3135         ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
3136             ->isAllOnesValue();
3137 
3138     // This generates the new instruction that will replace the original Cmp
3139     // Instruction. Instead of enumerating the various combinations when
3140     // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3141     // false, we rely on chaining of ORs and future passes of InstCombine to
3142     // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3143 
3144     // When none of the three constants satisfy the predicate for the RHS (C),
3145     // the entire original Cmp can be simplified to a false.
3146     Value *Cond = Builder.getFalse();
3147     if (TrueWhenLessThan)
3148       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
3149                                                        OrigLHS, OrigRHS));
3150     if (TrueWhenEqual)
3151       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
3152                                                        OrigLHS, OrigRHS));
3153     if (TrueWhenGreaterThan)
3154       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
3155                                                        OrigLHS, OrigRHS));
3156 
3157     return replaceInstUsesWith(Cmp, Cond);
3158   }
3159   return nullptr;
3160 }
3161 
3162 Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3163   auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3164   if (!Bitcast)
3165     return nullptr;
3166 
3167   ICmpInst::Predicate Pred = Cmp.getPredicate();
3168   Value *Op1 = Cmp.getOperand(1);
3169   Value *BCSrcOp = Bitcast->getOperand(0);
3170   Type *SrcType = Bitcast->getSrcTy();
3171   Type *DstType = Bitcast->getType();
3172 
3173   // Make sure the bitcast doesn't change between scalar and vector and
3174   // doesn't change the number of vector elements.
3175   if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3176       SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3177     // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3178     Value *X;
3179     if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3180       // icmp  eq (bitcast (sitofp X)), 0 --> icmp  eq X, 0
3181       // icmp  ne (bitcast (sitofp X)), 0 --> icmp  ne X, 0
3182       // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3183       // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3184       if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3185            Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3186           match(Op1, m_Zero()))
3187         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3188 
3189       // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3190       if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3191         return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3192 
3193       // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3194       if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3195         return new ICmpInst(Pred, X,
3196                             ConstantInt::getAllOnesValue(X->getType()));
3197     }
3198 
3199     // Zero-equality checks are preserved through unsigned floating-point casts:
3200     // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3201     // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3202     if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3203       if (Cmp.isEquality() && match(Op1, m_Zero()))
3204         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3205 
3206     // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3207     // the FP extend/truncate because that cast does not change the sign-bit.
3208     // This is true for all standard IEEE-754 types and the X86 80-bit type.
3209     // The sign-bit is always the most significant bit in those types.
3210     const APInt *C;
3211     bool TrueIfSigned;
3212     if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
3213         isSignBitCheck(Pred, *C, TrueIfSigned)) {
3214       if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3215           match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
3216         // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3217         // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3218         Type *XType = X->getType();
3219 
3220         // We can't currently handle Power style floating point operations here.
3221         if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3222           Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3223           if (auto *XVTy = dyn_cast<VectorType>(XType))
3224             NewType = VectorType::get(NewType, XVTy->getElementCount());
3225           Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3226           if (TrueIfSigned)
3227             return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3228                                 ConstantInt::getNullValue(NewType));
3229           else
3230             return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3231                                 ConstantInt::getAllOnesValue(NewType));
3232         }
3233       }
3234     }
3235   }
3236 
3237   const APInt *C;
3238   if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3239       !SrcType->isIntOrIntVectorTy())
3240     return nullptr;
3241 
3242   // If this is checking if all elements of a vector compare are set or not,
3243   // invert the casted vector equality compare and test if all compare
3244   // elements are clear or not. Compare against zero is generally easier for
3245   // analysis and codegen.
3246   // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3247   // Example: are all elements equal? --> are zero elements not equal?
3248   // TODO: Try harder to reduce compare of 2 freely invertible operands?
3249   if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3250     if (Value *NotBCSrcOp =
3251             getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3252       Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3253       return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3254     }
3255   }
3256 
3257   // If this is checking if all elements of an extended vector are clear or not,
3258   // compare in a narrow type to eliminate the extend:
3259   // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3260   Value *X;
3261   if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3262       match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3263     if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3264       Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3265       Value *NewCast = Builder.CreateBitCast(X, NewType);
3266       return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3267     }
3268   }
3269 
3270   // Folding: icmp <pred> iN X, C
3271   //  where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3272   //    and C is a splat of a K-bit pattern
3273   //    and SC is a constant vector = <C', C', C', ..., C'>
3274   // Into:
3275   //   %E = extractelement <M x iK> %vec, i32 C'
3276   //   icmp <pred> iK %E, trunc(C)
3277   Value *Vec;
3278   ArrayRef<int> Mask;
3279   if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3280     // Check whether every element of Mask is the same constant
3281     if (all_equal(Mask)) {
3282       auto *VecTy = cast<VectorType>(SrcType);
3283       auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3284       if (C->isSplat(EltTy->getBitWidth())) {
3285         // Fold the icmp based on the value of C
3286         // If C is M copies of an iK sized bit pattern,
3287         // then:
3288         //   =>  %E = extractelement <N x iK> %vec, i32 Elem
3289         //       icmp <pred> iK %SplatVal, <pattern>
3290         Value *Elem = Builder.getInt32(Mask[0]);
3291         Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3292         Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3293         return new ICmpInst(Pred, Extract, NewC);
3294       }
3295     }
3296   }
3297   return nullptr;
3298 }
3299 
3300 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3301 /// where X is some kind of instruction.
3302 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3303   const APInt *C;
3304 
3305   if (match(Cmp.getOperand(1), m_APInt(C))) {
3306     if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3307       if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3308         return I;
3309 
3310     if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3311       // For now, we only support constant integers while folding the
3312       // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3313       // similar to the cases handled by binary ops above.
3314       if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3315         if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3316           return I;
3317 
3318     if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3319       if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3320         return I;
3321 
3322     if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3323       if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3324         return I;
3325 
3326     // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3327     // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3328     // TODO: This checks one-use, but that is not strictly necessary.
3329     Value *Cmp0 = Cmp.getOperand(0);
3330     Value *X, *Y;
3331     if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3332         (match(Cmp0,
3333                m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3334                    m_Value(X), m_Value(Y)))) ||
3335          match(Cmp0,
3336                m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3337                    m_Value(X), m_Value(Y))))))
3338       return new ICmpInst(Cmp.getPredicate(), X, Y);
3339   }
3340 
3341   if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3342     return foldICmpInstWithConstantAllowUndef(Cmp, *C);
3343 
3344   return nullptr;
3345 }
3346 
3347 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3348 /// icmp eq/ne BO, C.
3349 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3350     ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3351   // TODO: Some of these folds could work with arbitrary constants, but this
3352   // function is limited to scalar and vector splat constants.
3353   if (!Cmp.isEquality())
3354     return nullptr;
3355 
3356   ICmpInst::Predicate Pred = Cmp.getPredicate();
3357   bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3358   Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3359   Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3360 
3361   switch (BO->getOpcode()) {
3362   case Instruction::SRem:
3363     // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3364     if (C.isZero() && BO->hasOneUse()) {
3365       const APInt *BOC;
3366       if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3367         Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3368         return new ICmpInst(Pred, NewRem,
3369                             Constant::getNullValue(BO->getType()));
3370       }
3371     }
3372     break;
3373   case Instruction::Add: {
3374     // (A + C2) == C --> A == (C - C2)
3375     // (A + C2) != C --> A != (C - C2)
3376     // TODO: Remove the one-use limitation? See discussion in D58633.
3377     if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3378       if (BO->hasOneUse())
3379         return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3380     } else if (C.isZero()) {
3381       // Replace ((add A, B) != 0) with (A != -B) if A or B is
3382       // efficiently invertible, or if the add has just this one use.
3383       if (Value *NegVal = dyn_castNegVal(BOp1))
3384         return new ICmpInst(Pred, BOp0, NegVal);
3385       if (Value *NegVal = dyn_castNegVal(BOp0))
3386         return new ICmpInst(Pred, NegVal, BOp1);
3387       if (BO->hasOneUse()) {
3388         Value *Neg = Builder.CreateNeg(BOp1);
3389         Neg->takeName(BO);
3390         return new ICmpInst(Pred, BOp0, Neg);
3391       }
3392     }
3393     break;
3394   }
3395   case Instruction::Xor:
3396     if (BO->hasOneUse()) {
3397       if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3398         // For the xor case, we can xor two constants together, eliminating
3399         // the explicit xor.
3400         return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3401       } else if (C.isZero()) {
3402         // Replace ((xor A, B) != 0) with (A != B)
3403         return new ICmpInst(Pred, BOp0, BOp1);
3404       }
3405     }
3406     break;
3407   case Instruction::Or: {
3408     const APInt *BOC;
3409     if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3410       // Comparing if all bits outside of a constant mask are set?
3411       // Replace (X | C) == -1 with (X & ~C) == ~C.
3412       // This removes the -1 constant.
3413       Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3414       Value *And = Builder.CreateAnd(BOp0, NotBOC);
3415       return new ICmpInst(Pred, And, NotBOC);
3416     }
3417     break;
3418   }
3419   case Instruction::UDiv:
3420   case Instruction::SDiv:
3421     if (BO->isExact()) {
3422       // div exact X, Y eq/ne 0 -> X eq/ne 0
3423       // div exact X, Y eq/ne 1 -> X eq/ne Y
3424       // div exact X, Y eq/ne C ->
3425       //    if Y * C never-overflow && OneUse:
3426       //      -> Y * C eq/ne X
3427       if (C.isZero())
3428         return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3429       else if (C.isOne())
3430         return new ICmpInst(Pred, BOp0, BOp1);
3431       else if (BO->hasOneUse()) {
3432         OverflowResult OR = computeOverflow(
3433             Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3434             Cmp.getOperand(1), BO);
3435         if (OR == OverflowResult::NeverOverflows) {
3436           Value *YC =
3437               Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3438           return new ICmpInst(Pred, YC, BOp0);
3439         }
3440       }
3441     }
3442     if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3443       // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3444       auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3445       return new ICmpInst(NewPred, BOp1, BOp0);
3446     }
3447     break;
3448   default:
3449     break;
3450   }
3451   return nullptr;
3452 }
3453 
3454 static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3455                                       const APInt &CRhs,
3456                                       InstCombiner::BuilderTy &Builder,
3457                                       const SimplifyQuery &Q) {
3458   assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3459          "Non-ctpop intrin in ctpop fold");
3460   if (!CtpopLhs->hasOneUse())
3461     return nullptr;
3462 
3463   // Power of 2 test:
3464   //    isPow2OrZero : ctpop(X) u< 2
3465   //    isPow2       : ctpop(X) == 1
3466   //    NotPow2OrZero: ctpop(X) u> 1
3467   //    NotPow2      : ctpop(X) != 1
3468   // If we know any bit of X can be folded to:
3469   //    IsPow2       : X & (~Bit) == 0
3470   //    NotPow2      : X & (~Bit) != 0
3471   const ICmpInst::Predicate Pred = I.getPredicate();
3472   if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3473       (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3474     Value *Op = CtpopLhs->getArgOperand(0);
3475     KnownBits OpKnown = computeKnownBits(Op, Q.DL,
3476                                          /*Depth*/ 0, Q.AC, Q.CxtI, Q.DT);
3477     // No need to check for count > 1, that should be already constant folded.
3478     if (OpKnown.countMinPopulation() == 1) {
3479       Value *And = Builder.CreateAnd(
3480           Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3481       return new ICmpInst(
3482           (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3483               ? ICmpInst::ICMP_EQ
3484               : ICmpInst::ICMP_NE,
3485           And, Constant::getNullValue(Op->getType()));
3486     }
3487   }
3488 
3489   return nullptr;
3490 }
3491 
3492 /// Fold an equality icmp with LLVM intrinsic and constant operand.
3493 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3494     ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3495   Type *Ty = II->getType();
3496   unsigned BitWidth = C.getBitWidth();
3497   const ICmpInst::Predicate Pred = Cmp.getPredicate();
3498 
3499   switch (II->getIntrinsicID()) {
3500   case Intrinsic::abs:
3501     // abs(A) == 0  ->  A == 0
3502     // abs(A) == INT_MIN  ->  A == INT_MIN
3503     if (C.isZero() || C.isMinSignedValue())
3504       return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3505     break;
3506 
3507   case Intrinsic::bswap:
3508     // bswap(A) == C  ->  A == bswap(C)
3509     return new ICmpInst(Pred, II->getArgOperand(0),
3510                         ConstantInt::get(Ty, C.byteSwap()));
3511 
3512   case Intrinsic::bitreverse:
3513     // bitreverse(A) == C  ->  A == bitreverse(C)
3514     return new ICmpInst(Pred, II->getArgOperand(0),
3515                         ConstantInt::get(Ty, C.reverseBits()));
3516 
3517   case Intrinsic::ctlz:
3518   case Intrinsic::cttz: {
3519     // ctz(A) == bitwidth(A)  ->  A == 0 and likewise for !=
3520     if (C == BitWidth)
3521       return new ICmpInst(Pred, II->getArgOperand(0),
3522                           ConstantInt::getNullValue(Ty));
3523 
3524     // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3525     // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3526     // Limit to one use to ensure we don't increase instruction count.
3527     unsigned Num = C.getLimitedValue(BitWidth);
3528     if (Num != BitWidth && II->hasOneUse()) {
3529       bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3530       APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3531                                : APInt::getHighBitsSet(BitWidth, Num + 1);
3532       APInt Mask2 = IsTrailing
3533         ? APInt::getOneBitSet(BitWidth, Num)
3534         : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3535       return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3536                           ConstantInt::get(Ty, Mask2));
3537     }
3538     break;
3539   }
3540 
3541   case Intrinsic::ctpop: {
3542     // popcount(A) == 0  ->  A == 0 and likewise for !=
3543     // popcount(A) == bitwidth(A)  ->  A == -1 and likewise for !=
3544     bool IsZero = C.isZero();
3545     if (IsZero || C == BitWidth)
3546       return new ICmpInst(Pred, II->getArgOperand(0),
3547                           IsZero ? Constant::getNullValue(Ty)
3548                                  : Constant::getAllOnesValue(Ty));
3549 
3550     break;
3551   }
3552 
3553   case Intrinsic::fshl:
3554   case Intrinsic::fshr:
3555     if (II->getArgOperand(0) == II->getArgOperand(1)) {
3556       const APInt *RotAmtC;
3557       // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3558       // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3559       if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3560         return new ICmpInst(Pred, II->getArgOperand(0),
3561                             II->getIntrinsicID() == Intrinsic::fshl
3562                                 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3563                                 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3564     }
3565     break;
3566 
3567   case Intrinsic::umax:
3568   case Intrinsic::uadd_sat: {
3569     // uadd.sat(a, b) == 0  ->  (a | b) == 0
3570     // umax(a, b) == 0  ->  (a | b) == 0
3571     if (C.isZero() && II->hasOneUse()) {
3572       Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3573       return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3574     }
3575     break;
3576   }
3577 
3578   case Intrinsic::ssub_sat:
3579     // ssub.sat(a, b) == 0 -> a == b
3580     if (C.isZero())
3581       return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3582     break;
3583   case Intrinsic::usub_sat: {
3584     // usub.sat(a, b) == 0  ->  a <= b
3585     if (C.isZero()) {
3586       ICmpInst::Predicate NewPred =
3587           Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3588       return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3589     }
3590     break;
3591   }
3592   default:
3593     break;
3594   }
3595 
3596   return nullptr;
3597 }
3598 
3599 /// Fold an icmp with LLVM intrinsics
3600 static Instruction *
3601 foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
3602                                InstCombiner::BuilderTy &Builder) {
3603   assert(Cmp.isEquality());
3604 
3605   ICmpInst::Predicate Pred = Cmp.getPredicate();
3606   Value *Op0 = Cmp.getOperand(0);
3607   Value *Op1 = Cmp.getOperand(1);
3608   const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3609   const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3610   if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3611     return nullptr;
3612 
3613   switch (IIOp0->getIntrinsicID()) {
3614   case Intrinsic::bswap:
3615   case Intrinsic::bitreverse:
3616     // If both operands are byte-swapped or bit-reversed, just compare the
3617     // original values.
3618     return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3619   case Intrinsic::fshl:
3620   case Intrinsic::fshr: {
3621     // If both operands are rotated by same amount, just compare the
3622     // original values.
3623     if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3624       break;
3625     if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3626       break;
3627     if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3628       return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3629 
3630     // rotate(X, AmtX) == rotate(Y, AmtY)
3631     //  -> rotate(X, AmtX - AmtY) == Y
3632     // Do this if either both rotates have one use or if only one has one use
3633     // and AmtX/AmtY are constants.
3634     unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3635     if (OneUses == 2 ||
3636         (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
3637          match(IIOp1->getOperand(2), m_ImmConstant()))) {
3638       Value *SubAmt =
3639           Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3640       Value *CombinedRotate = Builder.CreateIntrinsic(
3641           Op0->getType(), IIOp0->getIntrinsicID(),
3642           {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3643       return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3644     }
3645   } break;
3646   default:
3647     break;
3648   }
3649 
3650   return nullptr;
3651 }
3652 
3653 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3654 /// where X is some kind of instruction and C is AllowUndef.
3655 /// TODO: Move more folds which allow undef to this function.
3656 Instruction *
3657 InstCombinerImpl::foldICmpInstWithConstantAllowUndef(ICmpInst &Cmp,
3658                                                      const APInt &C) {
3659   const ICmpInst::Predicate Pred = Cmp.getPredicate();
3660   if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3661     switch (II->getIntrinsicID()) {
3662     default:
3663       break;
3664     case Intrinsic::fshl:
3665     case Intrinsic::fshr:
3666       if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3667         // (rot X, ?) == 0/-1 --> X == 0/-1
3668         if (C.isZero() || C.isAllOnes())
3669           return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3670       }
3671       break;
3672     }
3673   }
3674 
3675   return nullptr;
3676 }
3677 
3678 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3679 Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3680                                                          BinaryOperator *BO,
3681                                                          const APInt &C) {
3682   switch (BO->getOpcode()) {
3683   case Instruction::Xor:
3684     if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3685       return I;
3686     break;
3687   case Instruction::And:
3688     if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3689       return I;
3690     break;
3691   case Instruction::Or:
3692     if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3693       return I;
3694     break;
3695   case Instruction::Mul:
3696     if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3697       return I;
3698     break;
3699   case Instruction::Shl:
3700     if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3701       return I;
3702     break;
3703   case Instruction::LShr:
3704   case Instruction::AShr:
3705     if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3706       return I;
3707     break;
3708   case Instruction::SRem:
3709     if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3710       return I;
3711     break;
3712   case Instruction::UDiv:
3713     if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3714       return I;
3715     [[fallthrough]];
3716   case Instruction::SDiv:
3717     if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3718       return I;
3719     break;
3720   case Instruction::Sub:
3721     if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3722       return I;
3723     break;
3724   case Instruction::Add:
3725     if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3726       return I;
3727     break;
3728   default:
3729     break;
3730   }
3731 
3732   // TODO: These folds could be refactored to be part of the above calls.
3733   return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3734 }
3735 
3736 static Instruction *
3737 foldICmpUSubSatOrUAddSatWithConstant(ICmpInst::Predicate Pred,
3738                                      SaturatingInst *II, const APInt &C,
3739                                      InstCombiner::BuilderTy &Builder) {
3740   // This transform may end up producing more than one instruction for the
3741   // intrinsic, so limit it to one user of the intrinsic.
3742   if (!II->hasOneUse())
3743     return nullptr;
3744 
3745   // Let Y        = [add/sub]_sat(X, C) pred C2
3746   //     SatVal   = The saturating value for the operation
3747   //     WillWrap = Whether or not the operation will underflow / overflow
3748   // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
3749   // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
3750   //
3751   // When (SatVal pred C2) is true, then
3752   //    Y = WillWrap ? true : ((X binop C) pred C2)
3753   // => Y = WillWrap || ((X binop C) pred C2)
3754   // else
3755   //    Y =  WillWrap ? false : ((X binop C) pred C2)
3756   // => Y = !WillWrap ?  ((X binop C) pred C2) : false
3757   // => Y = !WillWrap && ((X binop C) pred C2)
3758   Value *Op0 = II->getOperand(0);
3759   Value *Op1 = II->getOperand(1);
3760 
3761   const APInt *COp1;
3762   // This transform only works when the intrinsic has an integral constant or
3763   // splat vector as the second operand.
3764   if (!match(Op1, m_APInt(COp1)))
3765     return nullptr;
3766 
3767   APInt SatVal;
3768   switch (II->getIntrinsicID()) {
3769   default:
3770     llvm_unreachable(
3771         "This function only works with usub_sat and uadd_sat for now!");
3772   case Intrinsic::uadd_sat:
3773     SatVal = APInt::getAllOnes(C.getBitWidth());
3774     break;
3775   case Intrinsic::usub_sat:
3776     SatVal = APInt::getZero(C.getBitWidth());
3777     break;
3778   }
3779 
3780   // Check (SatVal pred C2)
3781   bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
3782 
3783   // !WillWrap.
3784   ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
3785       II->getBinaryOp(), *COp1, II->getNoWrapKind());
3786 
3787   // WillWrap.
3788   if (SatValCheck)
3789     C1 = C1.inverse();
3790 
3791   ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, C);
3792   if (II->getBinaryOp() == Instruction::Add)
3793     C2 = C2.sub(*COp1);
3794   else
3795     C2 = C2.add(*COp1);
3796 
3797   Instruction::BinaryOps CombiningOp =
3798       SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
3799 
3800   std::optional<ConstantRange> Combination;
3801   if (CombiningOp == Instruction::BinaryOps::Or)
3802     Combination = C1.exactUnionWith(C2);
3803   else /* CombiningOp == Instruction::BinaryOps::And */
3804     Combination = C1.exactIntersectWith(C2);
3805 
3806   if (!Combination)
3807     return nullptr;
3808 
3809   CmpInst::Predicate EquivPred;
3810   APInt EquivInt;
3811   APInt EquivOffset;
3812 
3813   Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3814 
3815   return new ICmpInst(
3816       EquivPred,
3817       Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
3818       ConstantInt::get(Op1->getType(), EquivInt));
3819 }
3820 
3821 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3822 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
3823                                                              IntrinsicInst *II,
3824                                                              const APInt &C) {
3825   ICmpInst::Predicate Pred = Cmp.getPredicate();
3826 
3827   // Handle folds that apply for any kind of icmp.
3828   switch (II->getIntrinsicID()) {
3829   default:
3830     break;
3831   case Intrinsic::uadd_sat:
3832   case Intrinsic::usub_sat:
3833     if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
3834             Pred, cast<SaturatingInst>(II), C, Builder))
3835       return Folded;
3836     break;
3837   case Intrinsic::ctpop: {
3838     const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3839     if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
3840       return R;
3841   } break;
3842   }
3843 
3844   if (Cmp.isEquality())
3845     return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3846 
3847   Type *Ty = II->getType();
3848   unsigned BitWidth = C.getBitWidth();
3849   switch (II->getIntrinsicID()) {
3850   case Intrinsic::ctpop: {
3851     // (ctpop X > BitWidth - 1) --> X == -1
3852     Value *X = II->getArgOperand(0);
3853     if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3854       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3855                              ConstantInt::getAllOnesValue(Ty));
3856     // (ctpop X < BitWidth) --> X != -1
3857     if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3858       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3859                              ConstantInt::getAllOnesValue(Ty));
3860     break;
3861   }
3862   case Intrinsic::ctlz: {
3863     // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3864     if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3865       unsigned Num = C.getLimitedValue();
3866       APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3867       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3868                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3869     }
3870 
3871     // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3872     if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3873       unsigned Num = C.getLimitedValue();
3874       APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3875       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3876                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3877     }
3878     break;
3879   }
3880   case Intrinsic::cttz: {
3881     // Limit to one use to ensure we don't increase instruction count.
3882     if (!II->hasOneUse())
3883       return nullptr;
3884 
3885     // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3886     if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3887       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3888       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3889                              Builder.CreateAnd(II->getArgOperand(0), Mask),
3890                              ConstantInt::getNullValue(Ty));
3891     }
3892 
3893     // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3894     if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3895       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3896       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3897                              Builder.CreateAnd(II->getArgOperand(0), Mask),
3898                              ConstantInt::getNullValue(Ty));
3899     }
3900     break;
3901   }
3902   case Intrinsic::ssub_sat:
3903     // ssub.sat(a, b) spred 0 -> a spred b
3904     if (ICmpInst::isSigned(Pred)) {
3905       if (C.isZero())
3906         return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3907       // X s<= 0 is cannonicalized to X s< 1
3908       if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3909         return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
3910                             II->getArgOperand(1));
3911       // X s>= 0 is cannonicalized to X s> -1
3912       if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3913         return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
3914                             II->getArgOperand(1));
3915     }
3916     break;
3917   default:
3918     break;
3919   }
3920 
3921   return nullptr;
3922 }
3923 
3924 /// Handle icmp with constant (but not simple integer constant) RHS.
3925 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
3926   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3927   Constant *RHSC = dyn_cast<Constant>(Op1);
3928   Instruction *LHSI = dyn_cast<Instruction>(Op0);
3929   if (!RHSC || !LHSI)
3930     return nullptr;
3931 
3932   switch (LHSI->getOpcode()) {
3933   case Instruction::PHI:
3934     if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3935       return NV;
3936     break;
3937   case Instruction::IntToPtr:
3938     // icmp pred inttoptr(X), null -> icmp pred X, 0
3939     if (RHSC->isNullValue() &&
3940         DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3941       return new ICmpInst(
3942           I.getPredicate(), LHSI->getOperand(0),
3943           Constant::getNullValue(LHSI->getOperand(0)->getType()));
3944     break;
3945 
3946   case Instruction::Load:
3947     // Try to optimize things like "A[i] > 4" to index computations.
3948     if (GetElementPtrInst *GEP =
3949             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3950       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3951         if (Instruction *Res =
3952                 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3953           return Res;
3954     break;
3955   }
3956 
3957   return nullptr;
3958 }
3959 
3960 Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred,
3961                                               SelectInst *SI, Value *RHS,
3962                                               const ICmpInst &I) {
3963   // Try to fold the comparison into the select arms, which will cause the
3964   // select to be converted into a logical and/or.
3965   auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3966     if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3967       return Res;
3968     if (std::optional<bool> Impl = isImpliedCondition(
3969             SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
3970       return ConstantInt::get(I.getType(), *Impl);
3971     return nullptr;
3972   };
3973 
3974   ConstantInt *CI = nullptr;
3975   Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3976   if (Op1)
3977     CI = dyn_cast<ConstantInt>(Op1);
3978 
3979   Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3980   if (Op2)
3981     CI = dyn_cast<ConstantInt>(Op2);
3982 
3983   // We only want to perform this transformation if it will not lead to
3984   // additional code. This is true if either both sides of the select
3985   // fold to a constant (in which case the icmp is replaced with a select
3986   // which will usually simplify) or this is the only user of the
3987   // select (in which case we are trading a select+icmp for a simpler
3988   // select+icmp) or all uses of the select can be replaced based on
3989   // dominance information ("Global cases").
3990   bool Transform = false;
3991   if (Op1 && Op2)
3992     Transform = true;
3993   else if (Op1 || Op2) {
3994     // Local case
3995     if (SI->hasOneUse())
3996       Transform = true;
3997     // Global cases
3998     else if (CI && !CI->isZero())
3999       // When Op1 is constant try replacing select with second operand.
4000       // Otherwise Op2 is constant and try replacing select with first
4001       // operand.
4002       Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4003   }
4004   if (Transform) {
4005     if (!Op1)
4006       Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4007     if (!Op2)
4008       Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4009     return SelectInst::Create(SI->getOperand(0), Op1, Op2);
4010   }
4011 
4012   return nullptr;
4013 }
4014 
4015 /// Some comparisons can be simplified.
4016 /// In this case, we are looking for comparisons that look like
4017 /// a check for a lossy truncation.
4018 /// Folds:
4019 ///   icmp SrcPred (x & Mask), x    to    icmp DstPred x, Mask
4020 /// Where Mask is some pattern that produces all-ones in low bits:
4021 ///    (-1 >> y)
4022 ///    ((-1 << y) >> y)     <- non-canonical, has extra uses
4023 ///   ~(-1 << y)
4024 ///    ((1 << y) + (-1))    <- non-canonical, has extra uses
4025 /// The Mask can be a constant, too.
4026 /// For some predicates, the operands are commutative.
4027 /// For others, x can only be on a specific side.
4028 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
4029                                           InstCombiner::BuilderTy &Builder) {
4030   ICmpInst::Predicate SrcPred;
4031   Value *X, *M, *Y;
4032   auto m_VariableMask = m_CombineOr(
4033       m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
4034                   m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
4035       m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
4036                   m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
4037   auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
4038   if (!match(&I, m_c_ICmp(SrcPred,
4039                           m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
4040                           m_Deferred(X))))
4041     return nullptr;
4042 
4043   ICmpInst::Predicate DstPred;
4044   switch (SrcPred) {
4045   case ICmpInst::Predicate::ICMP_EQ:
4046     //  x & (-1 >> y) == x    ->    x u<= (-1 >> y)
4047     DstPred = ICmpInst::Predicate::ICMP_ULE;
4048     break;
4049   case ICmpInst::Predicate::ICMP_NE:
4050     //  x & (-1 >> y) != x    ->    x u> (-1 >> y)
4051     DstPred = ICmpInst::Predicate::ICMP_UGT;
4052     break;
4053   case ICmpInst::Predicate::ICMP_ULT:
4054     //  x & (-1 >> y) u< x    ->    x u> (-1 >> y)
4055     //  x u> x & (-1 >> y)    ->    x u> (-1 >> y)
4056     DstPred = ICmpInst::Predicate::ICMP_UGT;
4057     break;
4058   case ICmpInst::Predicate::ICMP_UGE:
4059     //  x & (-1 >> y) u>= x    ->    x u<= (-1 >> y)
4060     //  x u<= x & (-1 >> y)    ->    x u<= (-1 >> y)
4061     DstPred = ICmpInst::Predicate::ICMP_ULE;
4062     break;
4063   case ICmpInst::Predicate::ICMP_SLT:
4064     //  x & (-1 >> y) s< x    ->    x s> (-1 >> y)
4065     //  x s> x & (-1 >> y)    ->    x s> (-1 >> y)
4066     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
4067       return nullptr;
4068     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
4069       return nullptr;
4070     DstPred = ICmpInst::Predicate::ICMP_SGT;
4071     break;
4072   case ICmpInst::Predicate::ICMP_SGE:
4073     //  x & (-1 >> y) s>= x    ->    x s<= (-1 >> y)
4074     //  x s<= x & (-1 >> y)    ->    x s<= (-1 >> y)
4075     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
4076       return nullptr;
4077     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
4078       return nullptr;
4079     DstPred = ICmpInst::Predicate::ICMP_SLE;
4080     break;
4081   case ICmpInst::Predicate::ICMP_SGT:
4082   case ICmpInst::Predicate::ICMP_SLE:
4083     return nullptr;
4084   case ICmpInst::Predicate::ICMP_UGT:
4085   case ICmpInst::Predicate::ICMP_ULE:
4086     llvm_unreachable("Instsimplify took care of commut. variant");
4087     break;
4088   default:
4089     llvm_unreachable("All possible folds are handled.");
4090   }
4091 
4092   // The mask value may be a vector constant that has undefined elements. But it
4093   // may not be safe to propagate those undefs into the new compare, so replace
4094   // those elements by copying an existing, defined, and safe scalar constant.
4095   Type *OpTy = M->getType();
4096   auto *VecC = dyn_cast<Constant>(M);
4097   auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
4098   if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
4099     Constant *SafeReplacementConstant = nullptr;
4100     for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
4101       if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
4102         SafeReplacementConstant = VecC->getAggregateElement(i);
4103         break;
4104       }
4105     }
4106     assert(SafeReplacementConstant && "Failed to find undef replacement");
4107     M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
4108   }
4109 
4110   return Builder.CreateICmp(DstPred, X, M);
4111 }
4112 
4113 /// Some comparisons can be simplified.
4114 /// In this case, we are looking for comparisons that look like
4115 /// a check for a lossy signed truncation.
4116 /// Folds:   (MaskedBits is a constant.)
4117 ///   ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4118 /// Into:
4119 ///   (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4120 /// Where  KeptBits = bitwidth(%x) - MaskedBits
4121 static Value *
4122 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4123                                  InstCombiner::BuilderTy &Builder) {
4124   ICmpInst::Predicate SrcPred;
4125   Value *X;
4126   const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4127   // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4128   if (!match(&I, m_c_ICmp(SrcPred,
4129                           m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
4130                                           m_APInt(C1))),
4131                           m_Deferred(X))))
4132     return nullptr;
4133 
4134   // Potential handling of non-splats: for each element:
4135   //  * if both are undef, replace with constant 0.
4136   //    Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4137   //  * if both are not undef, and are different, bailout.
4138   //  * else, only one is undef, then pick the non-undef one.
4139 
4140   // The shift amount must be equal.
4141   if (*C0 != *C1)
4142     return nullptr;
4143   const APInt &MaskedBits = *C0;
4144   assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4145 
4146   ICmpInst::Predicate DstPred;
4147   switch (SrcPred) {
4148   case ICmpInst::Predicate::ICMP_EQ:
4149     // ((%x << MaskedBits) a>> MaskedBits) == %x
4150     //   =>
4151     // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4152     DstPred = ICmpInst::Predicate::ICMP_ULT;
4153     break;
4154   case ICmpInst::Predicate::ICMP_NE:
4155     // ((%x << MaskedBits) a>> MaskedBits) != %x
4156     //   =>
4157     // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4158     DstPred = ICmpInst::Predicate::ICMP_UGE;
4159     break;
4160   // FIXME: are more folds possible?
4161   default:
4162     return nullptr;
4163   }
4164 
4165   auto *XType = X->getType();
4166   const unsigned XBitWidth = XType->getScalarSizeInBits();
4167   const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4168   assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4169 
4170   // KeptBits = bitwidth(%x) - MaskedBits
4171   const APInt KeptBits = BitWidth - MaskedBits;
4172   assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4173   // ICmpCst = (1 << KeptBits)
4174   const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4175   assert(ICmpCst.isPowerOf2());
4176   // AddCst = (1 << (KeptBits-1))
4177   const APInt AddCst = ICmpCst.lshr(1);
4178   assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4179 
4180   // T0 = add %x, AddCst
4181   Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4182   // T1 = T0 DstPred ICmpCst
4183   Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4184 
4185   return T1;
4186 }
4187 
4188 // Given pattern:
4189 //   icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4190 // we should move shifts to the same hand of 'and', i.e. rewrite as
4191 //   icmp eq/ne (and (x shift (Q+K)), y), 0  iff (Q+K) u< bitwidth(x)
4192 // We are only interested in opposite logical shifts here.
4193 // One of the shifts can be truncated.
4194 // If we can, we want to end up creating 'lshr' shift.
4195 static Value *
4196 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4197                                            InstCombiner::BuilderTy &Builder) {
4198   if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4199       !I.getOperand(0)->hasOneUse())
4200     return nullptr;
4201 
4202   auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4203 
4204   // Look for an 'and' of two logical shifts, one of which may be truncated.
4205   // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4206   Instruction *XShift, *MaybeTruncation, *YShift;
4207   if (!match(
4208           I.getOperand(0),
4209           m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4210                   m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
4211                                    m_AnyLogicalShift, m_Instruction(YShift))),
4212                                m_Instruction(MaybeTruncation)))))
4213     return nullptr;
4214 
4215   // We potentially looked past 'trunc', but only when matching YShift,
4216   // therefore YShift must have the widest type.
4217   Instruction *WidestShift = YShift;
4218   // Therefore XShift must have the shallowest type.
4219   // Or they both have identical types if there was no truncation.
4220   Instruction *NarrowestShift = XShift;
4221 
4222   Type *WidestTy = WidestShift->getType();
4223   Type *NarrowestTy = NarrowestShift->getType();
4224   assert(NarrowestTy == I.getOperand(0)->getType() &&
4225          "We did not look past any shifts while matching XShift though.");
4226   bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4227 
4228   // If YShift is a 'lshr', swap the shifts around.
4229   if (match(YShift, m_LShr(m_Value(), m_Value())))
4230     std::swap(XShift, YShift);
4231 
4232   // The shifts must be in opposite directions.
4233   auto XShiftOpcode = XShift->getOpcode();
4234   if (XShiftOpcode == YShift->getOpcode())
4235     return nullptr; // Do not care about same-direction shifts here.
4236 
4237   Value *X, *XShAmt, *Y, *YShAmt;
4238   match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4239   match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4240 
4241   // If one of the values being shifted is a constant, then we will end with
4242   // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4243   // however, we will need to ensure that we won't increase instruction count.
4244   if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4245     // At least one of the hands of the 'and' should be one-use shift.
4246     if (!match(I.getOperand(0),
4247                m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4248       return nullptr;
4249     if (HadTrunc) {
4250       // Due to the 'trunc', we will need to widen X. For that either the old
4251       // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4252       if (!MaybeTruncation->hasOneUse() &&
4253           !NarrowestShift->getOperand(1)->hasOneUse())
4254         return nullptr;
4255     }
4256   }
4257 
4258   // We have two shift amounts from two different shifts. The types of those
4259   // shift amounts may not match. If that's the case let's bailout now.
4260   if (XShAmt->getType() != YShAmt->getType())
4261     return nullptr;
4262 
4263   // As input, we have the following pattern:
4264   //   icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4265   // We want to rewrite that as:
4266   //   icmp eq/ne (and (x shift (Q+K)), y), 0  iff (Q+K) u< bitwidth(x)
4267   // While we know that originally (Q+K) would not overflow
4268   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
4269   // shift amounts. so it may now overflow in smaller bitwidth.
4270   // To ensure that does not happen, we need to ensure that the total maximal
4271   // shift amount is still representable in that smaller bit width.
4272   unsigned MaximalPossibleTotalShiftAmount =
4273       (WidestTy->getScalarSizeInBits() - 1) +
4274       (NarrowestTy->getScalarSizeInBits() - 1);
4275   APInt MaximalRepresentableShiftAmount =
4276       APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());
4277   if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4278     return nullptr;
4279 
4280   // Can we fold (XShAmt+YShAmt) ?
4281   auto *NewShAmt = dyn_cast_or_null<Constant>(
4282       simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4283                       /*isNUW=*/false, SQ.getWithInstruction(&I)));
4284   if (!NewShAmt)
4285     return nullptr;
4286   if (NewShAmt->getType() != WidestTy) {
4287     NewShAmt =
4288         ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4289     if (!NewShAmt)
4290       return nullptr;
4291   }
4292   unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4293 
4294   // Is the new shift amount smaller than the bit width?
4295   // FIXME: could also rely on ConstantRange.
4296   if (!match(NewShAmt,
4297              m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
4298                                 APInt(WidestBitWidth, WidestBitWidth))))
4299     return nullptr;
4300 
4301   // An extra legality check is needed if we had trunc-of-lshr.
4302   if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4303     auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4304                     WidestShift]() {
4305       // It isn't obvious whether it's worth it to analyze non-constants here.
4306       // Also, let's basically give up on non-splat cases, pessimizing vectors.
4307       // If *any* of these preconditions matches we can perform the fold.
4308       Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4309                                     ? NewShAmt->getSplatValue()
4310                                     : NewShAmt;
4311       // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4312       if (NewShAmtSplat &&
4313           (NewShAmtSplat->isNullValue() ||
4314            NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4315         return true;
4316       // We consider *min* leading zeros so a single outlier
4317       // blocks the transform as opposed to allowing it.
4318       if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4319         KnownBits Known = computeKnownBits(C, SQ.DL);
4320         unsigned MinLeadZero = Known.countMinLeadingZeros();
4321         // If the value being shifted has at most lowest bit set we can fold.
4322         unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4323         if (MaxActiveBits <= 1)
4324           return true;
4325         // Precondition:  NewShAmt u<= countLeadingZeros(C)
4326         if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4327           return true;
4328       }
4329       if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4330         KnownBits Known = computeKnownBits(C, SQ.DL);
4331         unsigned MinLeadZero = Known.countMinLeadingZeros();
4332         // If the value being shifted has at most lowest bit set we can fold.
4333         unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4334         if (MaxActiveBits <= 1)
4335           return true;
4336         // Precondition:  ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4337         if (NewShAmtSplat) {
4338           APInt AdjNewShAmt =
4339               (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4340           if (AdjNewShAmt.ule(MinLeadZero))
4341             return true;
4342         }
4343       }
4344       return false; // Can't tell if it's ok.
4345     };
4346     if (!CanFold())
4347       return nullptr;
4348   }
4349 
4350   // All good, we can do this fold.
4351   X = Builder.CreateZExt(X, WidestTy);
4352   Y = Builder.CreateZExt(Y, WidestTy);
4353   // The shift is the same that was for X.
4354   Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4355                   ? Builder.CreateLShr(X, NewShAmt)
4356                   : Builder.CreateShl(X, NewShAmt);
4357   Value *T1 = Builder.CreateAnd(T0, Y);
4358   return Builder.CreateICmp(I.getPredicate(), T1,
4359                             Constant::getNullValue(WidestTy));
4360 }
4361 
4362 /// Fold
4363 ///   (-1 u/ x) u< y
4364 ///   ((x * y) ?/ x) != y
4365 /// to
4366 ///   @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4367 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4368 /// will mean that we are looking for the opposite answer.
4369 Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
4370   ICmpInst::Predicate Pred;
4371   Value *X, *Y;
4372   Instruction *Mul;
4373   Instruction *Div;
4374   bool NeedNegation;
4375   // Look for: (-1 u/ x) u</u>= y
4376   if (!I.isEquality() &&
4377       match(&I, m_c_ICmp(Pred,
4378                          m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
4379                                       m_Instruction(Div)),
4380                          m_Value(Y)))) {
4381     Mul = nullptr;
4382 
4383     // Are we checking that overflow does not happen, or does happen?
4384     switch (Pred) {
4385     case ICmpInst::Predicate::ICMP_ULT:
4386       NeedNegation = false;
4387       break; // OK
4388     case ICmpInst::Predicate::ICMP_UGE:
4389       NeedNegation = true;
4390       break; // OK
4391     default:
4392       return nullptr; // Wrong predicate.
4393     }
4394   } else // Look for: ((x * y) / x) !=/== y
4395       if (I.isEquality() &&
4396           match(&I,
4397                 m_c_ICmp(Pred, m_Value(Y),
4398                          m_CombineAnd(
4399                              m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),
4400                                                                   m_Value(X)),
4401                                                           m_Instruction(Mul)),
4402                                              m_Deferred(X))),
4403                              m_Instruction(Div))))) {
4404     NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4405   } else
4406     return nullptr;
4407 
4408   BuilderTy::InsertPointGuard Guard(Builder);
4409   // If the pattern included (x * y), we'll want to insert new instructions
4410   // right before that original multiplication so that we can replace it.
4411   bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4412   if (MulHadOtherUses)
4413     Builder.SetInsertPoint(Mul);
4414 
4415   Function *F = Intrinsic::getDeclaration(I.getModule(),
4416                                           Div->getOpcode() == Instruction::UDiv
4417                                               ? Intrinsic::umul_with_overflow
4418                                               : Intrinsic::smul_with_overflow,
4419                                           X->getType());
4420   CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
4421 
4422   // If the multiplication was used elsewhere, to ensure that we don't leave
4423   // "duplicate" instructions, replace uses of that original multiplication
4424   // with the multiplication result from the with.overflow intrinsic.
4425   if (MulHadOtherUses)
4426     replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4427 
4428   Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4429   if (NeedNegation) // This technically increases instruction count.
4430     Res = Builder.CreateNot(Res, "mul.not.ov");
4431 
4432   // If we replaced the mul, erase it. Do this after all uses of Builder,
4433   // as the mul is used as insertion point.
4434   if (MulHadOtherUses)
4435     eraseInstFromFunction(*Mul);
4436 
4437   return Res;
4438 }
4439 
4440 static Instruction *foldICmpXNegX(ICmpInst &I,
4441                                   InstCombiner::BuilderTy &Builder) {
4442   CmpInst::Predicate Pred;
4443   Value *X;
4444   if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
4445 
4446     if (ICmpInst::isSigned(Pred))
4447       Pred = ICmpInst::getSwappedPredicate(Pred);
4448     else if (ICmpInst::isUnsigned(Pred))
4449       Pred = ICmpInst::getSignedPredicate(Pred);
4450     // else for equality-comparisons just keep the predicate.
4451 
4452     return ICmpInst::Create(Instruction::ICmp, Pred, X,
4453                             Constant::getNullValue(X->getType()), I.getName());
4454   }
4455 
4456   // A value is not equal to its negation unless that value is 0 or
4457   // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4458   if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
4459       ICmpInst::isEquality(Pred)) {
4460     Type *Ty = X->getType();
4461     uint32_t BitWidth = Ty->getScalarSizeInBits();
4462     Constant *MaxSignedVal =
4463         ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
4464     Value *And = Builder.CreateAnd(X, MaxSignedVal);
4465     Constant *Zero = Constant::getNullValue(Ty);
4466     return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
4467   }
4468 
4469   return nullptr;
4470 }
4471 
4472 static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
4473                                   InstCombinerImpl &IC) {
4474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4475   // Normalize and operand as operand 0.
4476   CmpInst::Predicate Pred = I.getPredicate();
4477   if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
4478     std::swap(Op0, Op1);
4479     Pred = ICmpInst::getSwappedPredicate(Pred);
4480   }
4481 
4482   if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
4483     return nullptr;
4484 
4485   // (icmp (X & Y) u< X --> (X & Y) != X
4486   if (Pred == ICmpInst::ICMP_ULT)
4487     return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4488 
4489   // (icmp (X & Y) u>= X --> (X & Y) == X
4490   if (Pred == ICmpInst::ICMP_UGE)
4491     return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4492 
4493   return nullptr;
4494 }
4495 
4496 static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
4497                                  InstCombinerImpl &IC) {
4498   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4499 
4500   // Normalize or operand as operand 0.
4501   CmpInst::Predicate Pred = I.getPredicate();
4502   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
4503     std::swap(Op0, Op1);
4504     Pred = ICmpInst::getSwappedPredicate(Pred);
4505   } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
4506     return nullptr;
4507   }
4508 
4509   // icmp (X | Y) u<= X --> (X | Y) == X
4510   if (Pred == ICmpInst::ICMP_ULE)
4511     return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4512 
4513   // icmp (X | Y) u> X --> (X | Y) != X
4514   if (Pred == ICmpInst::ICMP_UGT)
4515     return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4516 
4517   if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
4518     // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
4519     if (Value *NotOp1 =
4520             IC.getFreelyInverted(Op1, Op1->hasOneUse(), &IC.Builder))
4521       return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
4522                           Constant::getNullValue(Op1->getType()));
4523     // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X  is freely invertible.
4524     if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
4525       return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
4526                           Constant::getAllOnesValue(Op1->getType()));
4527   }
4528   return nullptr;
4529 }
4530 
4531 static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
4532                                   InstCombinerImpl &IC) {
4533   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4534   // Normalize xor operand as operand 0.
4535   CmpInst::Predicate Pred = I.getPredicate();
4536   if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
4537     std::swap(Op0, Op1);
4538     Pred = ICmpInst::getSwappedPredicate(Pred);
4539   }
4540   if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
4541     return nullptr;
4542 
4543   // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
4544   // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
4545   // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
4546   // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
4547   CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(Pred);
4548   if (PredOut != Pred &&
4549       isKnownNonZero(A, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4550     return new ICmpInst(PredOut, Op0, Op1);
4551 
4552   return nullptr;
4553 }
4554 
4555 /// Try to fold icmp (binop), X or icmp X, (binop).
4556 /// TODO: A large part of this logic is duplicated in InstSimplify's
4557 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4558 /// duplication.
4559 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
4560                                              const SimplifyQuery &SQ) {
4561   const SimplifyQuery Q = SQ.getWithInstruction(&I);
4562   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4563 
4564   // Special logic for binary operators.
4565   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
4566   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
4567   if (!BO0 && !BO1)
4568     return nullptr;
4569 
4570   if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
4571     return NewICmp;
4572 
4573   const CmpInst::Predicate Pred = I.getPredicate();
4574   Value *X;
4575 
4576   // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
4577   // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
4578   if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
4579       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4580     return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
4581   // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
4582   if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
4583       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4584     return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
4585 
4586   {
4587     // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
4588     Constant *C;
4589     if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
4590                                   m_ImmConstant(C)))) &&
4591         (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
4592       Constant *C2 = ConstantExpr::getNot(C);
4593       return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
4594     }
4595     // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
4596     if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
4597                                   m_ImmConstant(C)))) &&
4598         (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
4599       Constant *C2 = ConstantExpr::getNot(C);
4600       return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
4601     }
4602   }
4603 
4604   {
4605     // Similar to above: an unsigned overflow comparison may use offset + mask:
4606     // ((Op1 + C) & C) u<  Op1 --> Op1 != 0
4607     // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
4608     // Op0 u>  ((Op0 + C) & C) --> Op0 != 0
4609     // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
4610     BinaryOperator *BO;
4611     const APInt *C;
4612     if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
4613         match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4614         match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowUndef(*C)))) {
4615       CmpInst::Predicate NewPred =
4616           Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4617       Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4618       return new ICmpInst(NewPred, Op1, Zero);
4619     }
4620 
4621     if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
4622         match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4623         match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowUndef(*C)))) {
4624       CmpInst::Predicate NewPred =
4625           Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4626       Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4627       return new ICmpInst(NewPred, Op0, Zero);
4628     }
4629   }
4630 
4631   bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
4632   bool Op0HasNUW = false, Op1HasNUW = false;
4633   bool Op0HasNSW = false, Op1HasNSW = false;
4634   // Analyze the case when either Op0 or Op1 is an add instruction.
4635   // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
4636   auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
4637                              bool &HasNSW, bool &HasNUW) -> bool {
4638     if (isa<OverflowingBinaryOperator>(BO)) {
4639       HasNUW = BO.hasNoUnsignedWrap();
4640       HasNSW = BO.hasNoSignedWrap();
4641       return ICmpInst::isEquality(Pred) ||
4642              (CmpInst::isUnsigned(Pred) && HasNUW) ||
4643              (CmpInst::isSigned(Pred) && HasNSW);
4644     } else if (BO.getOpcode() == Instruction::Or) {
4645       HasNUW = true;
4646       HasNSW = true;
4647       return true;
4648     } else {
4649       return false;
4650     }
4651   };
4652   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
4653 
4654   if (BO0) {
4655     match(BO0, m_AddLike(m_Value(A), m_Value(B)));
4656     NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
4657   }
4658   if (BO1) {
4659     match(BO1, m_AddLike(m_Value(C), m_Value(D)));
4660     NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
4661   }
4662 
4663   // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
4664   // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
4665   if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
4666     return new ICmpInst(Pred, A == Op1 ? B : A,
4667                         Constant::getNullValue(Op1->getType()));
4668 
4669   // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
4670   // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
4671   if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
4672     return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
4673                         C == Op0 ? D : C);
4674 
4675   // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
4676   if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
4677       NoOp1WrapProblem) {
4678     // Determine Y and Z in the form icmp (X+Y), (X+Z).
4679     Value *Y, *Z;
4680     if (A == C) {
4681       // C + B == C + D  ->  B == D
4682       Y = B;
4683       Z = D;
4684     } else if (A == D) {
4685       // D + B == C + D  ->  B == C
4686       Y = B;
4687       Z = C;
4688     } else if (B == C) {
4689       // A + C == C + D  ->  A == D
4690       Y = A;
4691       Z = D;
4692     } else {
4693       assert(B == D);
4694       // A + D == C + D  ->  A == C
4695       Y = A;
4696       Z = C;
4697     }
4698     return new ICmpInst(Pred, Y, Z);
4699   }
4700 
4701   // icmp slt (A + -1), Op1 -> icmp sle A, Op1
4702   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
4703       match(B, m_AllOnes()))
4704     return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
4705 
4706   // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
4707   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
4708       match(B, m_AllOnes()))
4709     return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
4710 
4711   // icmp sle (A + 1), Op1 -> icmp slt A, Op1
4712   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
4713     return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
4714 
4715   // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
4716   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
4717     return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
4718 
4719   // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
4720   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
4721       match(D, m_AllOnes()))
4722     return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
4723 
4724   // icmp sle Op0, (C + -1) -> icmp slt Op0, C
4725   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
4726       match(D, m_AllOnes()))
4727     return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
4728 
4729   // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
4730   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
4731     return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
4732 
4733   // icmp slt Op0, (C + 1) -> icmp sle Op0, C
4734   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
4735     return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
4736 
4737   // TODO: The subtraction-related identities shown below also hold, but
4738   // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
4739   // wouldn't happen even if they were implemented.
4740   //
4741   // icmp ult (A - 1), Op1 -> icmp ule A, Op1
4742   // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
4743   // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
4744   // icmp ule Op0, (C - 1) -> icmp ult Op0, C
4745 
4746   // icmp ule (A + 1), Op0 -> icmp ult A, Op1
4747   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
4748     return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
4749 
4750   // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
4751   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
4752     return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
4753 
4754   // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
4755   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
4756     return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
4757 
4758   // icmp ult Op0, (C + 1) -> icmp ule Op0, C
4759   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
4760     return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
4761 
4762   // if C1 has greater magnitude than C2:
4763   //  icmp (A + C1), (C + C2) -> icmp (A + C3), C
4764   //  s.t. C3 = C1 - C2
4765   //
4766   // if C2 has greater magnitude than C1:
4767   //  icmp (A + C1), (C + C2) -> icmp A, (C + C3)
4768   //  s.t. C3 = C2 - C1
4769   if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4770       (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
4771     const APInt *AP1, *AP2;
4772     // TODO: Support non-uniform vectors.
4773     // TODO: Allow undef passthrough if B AND D's element is undef.
4774     if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) &&
4775         AP1->isNegative() == AP2->isNegative()) {
4776       APInt AP1Abs = AP1->abs();
4777       APInt AP2Abs = AP2->abs();
4778       if (AP1Abs.uge(AP2Abs)) {
4779         APInt Diff = *AP1 - *AP2;
4780         Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4781         Value *NewAdd = Builder.CreateAdd(
4782             A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
4783         return new ICmpInst(Pred, NewAdd, C);
4784       } else {
4785         APInt Diff = *AP2 - *AP1;
4786         Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4787         Value *NewAdd = Builder.CreateAdd(
4788             C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
4789         return new ICmpInst(Pred, A, NewAdd);
4790       }
4791     }
4792     Constant *Cst1, *Cst2;
4793     if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
4794         ICmpInst::isEquality(Pred)) {
4795       Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
4796       Value *NewAdd = Builder.CreateAdd(C, Diff);
4797       return new ICmpInst(Pred, A, NewAdd);
4798     }
4799   }
4800 
4801   // Analyze the case when either Op0 or Op1 is a sub instruction.
4802   // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
4803   A = nullptr;
4804   B = nullptr;
4805   C = nullptr;
4806   D = nullptr;
4807   if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4808     A = BO0->getOperand(0);
4809     B = BO0->getOperand(1);
4810   }
4811   if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4812     C = BO1->getOperand(0);
4813     D = BO1->getOperand(1);
4814   }
4815 
4816   // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
4817   if (A == Op1 && NoOp0WrapProblem)
4818     return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4819   // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
4820   if (C == Op0 && NoOp1WrapProblem)
4821     return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4822 
4823   // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
4824   // (A - B) u>/u<= A --> B u>/u<= A
4825   if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4826     return new ICmpInst(Pred, B, A);
4827   // C u</u>= (C - D) --> C u</u>= D
4828   if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4829     return new ICmpInst(Pred, C, D);
4830   // (A - B) u>=/u< A --> B u>/u<= A  iff B != 0
4831   if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
4832       isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4833     return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
4834   // C u<=/u> (C - D) --> C u</u>= D  iff B != 0
4835   if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
4836       isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4837     return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
4838 
4839   // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
4840   if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
4841     return new ICmpInst(Pred, A, C);
4842 
4843   // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
4844   if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
4845     return new ICmpInst(Pred, D, B);
4846 
4847   // icmp (0-X) < cst --> x > -cst
4848   if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4849     Value *X;
4850     if (match(BO0, m_Neg(m_Value(X))))
4851       if (Constant *RHSC = dyn_cast<Constant>(Op1))
4852         if (RHSC->isNotMinSignedValue())
4853           return new ICmpInst(I.getSwappedPredicate(), X,
4854                               ConstantExpr::getNeg(RHSC));
4855   }
4856 
4857   if (Instruction * R = foldICmpXorXX(I, Q, *this))
4858     return R;
4859   if (Instruction *R = foldICmpOrXX(I, Q, *this))
4860     return R;
4861 
4862   {
4863     // Try to remove shared multiplier from comparison:
4864     // X * Z u{lt/le/gt/ge}/eq/ne Y * Z
4865     Value *X, *Y, *Z;
4866     if (Pred == ICmpInst::getUnsignedPredicate(Pred) &&
4867         ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
4868           match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
4869          (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
4870           match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))))) {
4871       bool NonZero;
4872       if (ICmpInst::isEquality(Pred)) {
4873         KnownBits ZKnown = computeKnownBits(Z, 0, &I);
4874         // if Z % 2 != 0
4875         //    X * Z eq/ne Y * Z -> X eq/ne Y
4876         if (ZKnown.countMaxTrailingZeros() == 0)
4877           return new ICmpInst(Pred, X, Y);
4878         NonZero = !ZKnown.One.isZero() ||
4879                   isKnownNonZero(Z, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
4880         // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
4881         //    X * Z eq/ne Y * Z -> X eq/ne Y
4882         if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
4883           return new ICmpInst(Pred, X, Y);
4884       } else
4885         NonZero = isKnownNonZero(Z, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
4886 
4887       // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
4888       //    X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
4889       if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
4890         return new ICmpInst(Pred, X, Y);
4891     }
4892   }
4893 
4894   BinaryOperator *SRem = nullptr;
4895   // icmp (srem X, Y), Y
4896   if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
4897     SRem = BO0;
4898   // icmp Y, (srem X, Y)
4899   else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4900            Op0 == BO1->getOperand(1))
4901     SRem = BO1;
4902   if (SRem) {
4903     // We don't check hasOneUse to avoid increasing register pressure because
4904     // the value we use is the same value this instruction was already using.
4905     switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4906     default:
4907       break;
4908     case ICmpInst::ICMP_EQ:
4909       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4910     case ICmpInst::ICMP_NE:
4911       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4912     case ICmpInst::ICMP_SGT:
4913     case ICmpInst::ICMP_SGE:
4914       return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4915                           Constant::getAllOnesValue(SRem->getType()));
4916     case ICmpInst::ICMP_SLT:
4917     case ICmpInst::ICMP_SLE:
4918       return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4919                           Constant::getNullValue(SRem->getType()));
4920     }
4921   }
4922 
4923   if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
4924       BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
4925     switch (BO0->getOpcode()) {
4926     default:
4927       break;
4928     case Instruction::Add:
4929     case Instruction::Sub:
4930     case Instruction::Xor: {
4931       if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4932         return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4933 
4934       const APInt *C;
4935       if (match(BO0->getOperand(1), m_APInt(C))) {
4936         // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
4937         if (C->isSignMask()) {
4938           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4939           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4940         }
4941 
4942         // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
4943         if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
4944           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4945           NewPred = I.getSwappedPredicate(NewPred);
4946           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4947         }
4948       }
4949       break;
4950     }
4951     case Instruction::Mul: {
4952       if (!I.isEquality())
4953         break;
4954 
4955       const APInt *C;
4956       if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
4957           !C->isOne()) {
4958         // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
4959         // Mask = -1 >> count-trailing-zeros(C).
4960         if (unsigned TZs = C->countr_zero()) {
4961           Constant *Mask = ConstantInt::get(
4962               BO0->getType(),
4963               APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
4964           Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
4965           Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
4966           return new ICmpInst(Pred, And1, And2);
4967         }
4968       }
4969       break;
4970     }
4971     case Instruction::UDiv:
4972     case Instruction::LShr:
4973       if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
4974         break;
4975       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4976 
4977     case Instruction::SDiv:
4978       if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
4979           !BO0->isExact() || !BO1->isExact())
4980         break;
4981       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4982 
4983     case Instruction::AShr:
4984       if (!BO0->isExact() || !BO1->isExact())
4985         break;
4986       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4987 
4988     case Instruction::Shl: {
4989       bool NUW = Op0HasNUW && Op1HasNUW;
4990       bool NSW = Op0HasNSW && Op1HasNSW;
4991       if (!NUW && !NSW)
4992         break;
4993       if (!NSW && I.isSigned())
4994         break;
4995       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4996     }
4997     }
4998   }
4999 
5000   if (BO0) {
5001     // Transform  A & (L - 1) `ult` L --> L != 0
5002     auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5003     auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5004 
5005     if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5006       auto *Zero = Constant::getNullValue(BO0->getType());
5007       return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5008     }
5009   }
5010 
5011   // For unsigned predicates / eq / ne:
5012   // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5013   // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5014   if (!ICmpInst::isSigned(Pred)) {
5015     if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5016       return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5017                           Constant::getNullValue(Op1->getType()));
5018     else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5019       return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5020                           Constant::getNullValue(Op0->getType()), Op0);
5021   }
5022 
5023   if (Value *V = foldMultiplicationOverflowCheck(I))
5024     return replaceInstUsesWith(I, V);
5025 
5026   if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
5027     return replaceInstUsesWith(I, V);
5028 
5029   if (Instruction *R = foldICmpAndXX(I, Q, *this))
5030     return R;
5031 
5032   if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5033     return replaceInstUsesWith(I, V);
5034 
5035   if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5036     return replaceInstUsesWith(I, V);
5037 
5038   return nullptr;
5039 }
5040 
5041 /// Fold icmp Pred min|max(X, Y), Z.
5042 Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5043                                                   MinMaxIntrinsic *MinMax,
5044                                                   Value *Z,
5045                                                   ICmpInst::Predicate Pred) {
5046   Value *X = MinMax->getLHS();
5047   Value *Y = MinMax->getRHS();
5048   if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5049     return nullptr;
5050   if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned())
5051     return nullptr;
5052   SimplifyQuery Q = SQ.getWithInstruction(&I);
5053   auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5054     if (!Val)
5055       return std::nullopt;
5056     if (match(Val, m_One()))
5057       return true;
5058     if (match(Val, m_Zero()))
5059       return false;
5060     return std::nullopt;
5061   };
5062   auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5063   auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5064   if (!CmpXZ.has_value() && !CmpYZ.has_value())
5065     return nullptr;
5066   if (!CmpXZ.has_value()) {
5067     std::swap(X, Y);
5068     std::swap(CmpXZ, CmpYZ);
5069   }
5070 
5071   auto FoldIntoCmpYZ = [&]() -> Instruction * {
5072     if (CmpYZ.has_value())
5073       return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5074     return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5075   };
5076 
5077   switch (Pred) {
5078   case ICmpInst::ICMP_EQ:
5079   case ICmpInst::ICMP_NE: {
5080     // If X == Z:
5081     //     Expr       Result
5082     // min(X, Y) == Z X <= Y
5083     // max(X, Y) == Z X >= Y
5084     // min(X, Y) != Z X > Y
5085     // max(X, Y) != Z X < Y
5086     if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5087       ICmpInst::Predicate NewPred =
5088           ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5089       if (Pred == ICmpInst::ICMP_NE)
5090         NewPred = ICmpInst::getInversePredicate(NewPred);
5091       return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5092     }
5093     // Otherwise (X != Z):
5094     ICmpInst::Predicate NewPred = MinMax->getPredicate();
5095     auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5096     if (!MinMaxCmpXZ.has_value()) {
5097       std::swap(X, Y);
5098       std::swap(CmpXZ, CmpYZ);
5099       // Re-check pre-condition X != Z
5100       if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5101         break;
5102       MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5103     }
5104     if (!MinMaxCmpXZ.has_value())
5105       break;
5106     if (*MinMaxCmpXZ) {
5107       //    Expr         Fact    Result
5108       // min(X, Y) == Z  X < Z   false
5109       // max(X, Y) == Z  X > Z   false
5110       // min(X, Y) != Z  X < Z    true
5111       // max(X, Y) != Z  X > Z    true
5112       return replaceInstUsesWith(
5113           I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5114     } else {
5115       //    Expr         Fact    Result
5116       // min(X, Y) == Z  X > Z   Y == Z
5117       // max(X, Y) == Z  X < Z   Y == Z
5118       // min(X, Y) != Z  X > Z   Y != Z
5119       // max(X, Y) != Z  X < Z   Y != Z
5120       return FoldIntoCmpYZ();
5121     }
5122     break;
5123   }
5124   case ICmpInst::ICMP_SLT:
5125   case ICmpInst::ICMP_ULT:
5126   case ICmpInst::ICMP_SLE:
5127   case ICmpInst::ICMP_ULE:
5128   case ICmpInst::ICMP_SGT:
5129   case ICmpInst::ICMP_UGT:
5130   case ICmpInst::ICMP_SGE:
5131   case ICmpInst::ICMP_UGE: {
5132     bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5133     if (*CmpXZ) {
5134       if (IsSame) {
5135         //      Expr        Fact    Result
5136         // min(X, Y) < Z    X < Z   true
5137         // min(X, Y) <= Z   X <= Z  true
5138         // max(X, Y) > Z    X > Z   true
5139         // max(X, Y) >= Z   X >= Z  true
5140         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5141       } else {
5142         //      Expr        Fact    Result
5143         // max(X, Y) < Z    X < Z   Y < Z
5144         // max(X, Y) <= Z   X <= Z  Y <= Z
5145         // min(X, Y) > Z    X > Z   Y > Z
5146         // min(X, Y) >= Z   X >= Z  Y >= Z
5147         return FoldIntoCmpYZ();
5148       }
5149     } else {
5150       if (IsSame) {
5151         //      Expr        Fact    Result
5152         // min(X, Y) < Z    X >= Z  Y < Z
5153         // min(X, Y) <= Z   X > Z   Y <= Z
5154         // max(X, Y) > Z    X <= Z  Y > Z
5155         // max(X, Y) >= Z   X < Z   Y >= Z
5156         return FoldIntoCmpYZ();
5157       } else {
5158         //      Expr        Fact    Result
5159         // max(X, Y) < Z    X >= Z  false
5160         // max(X, Y) <= Z   X > Z   false
5161         // min(X, Y) > Z    X <= Z  false
5162         // min(X, Y) >= Z   X < Z   false
5163         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5164       }
5165     }
5166     break;
5167   }
5168   default:
5169     break;
5170   }
5171 
5172   return nullptr;
5173 }
5174 
5175 // Canonicalize checking for a power-of-2-or-zero value:
5176 static Instruction *foldICmpPow2Test(ICmpInst &I,
5177                                      InstCombiner::BuilderTy &Builder) {
5178   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5179   const CmpInst::Predicate Pred = I.getPredicate();
5180   Value *A = nullptr;
5181   bool CheckIs;
5182   if (I.isEquality()) {
5183     // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5184     // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5185     if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5186                                      m_Deferred(A)))) ||
5187         !match(Op1, m_ZeroInt()))
5188       A = nullptr;
5189 
5190     // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5191     // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5192     if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5193       A = Op1;
5194     else if (match(Op1,
5195                    m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
5196       A = Op0;
5197 
5198     CheckIs = Pred == ICmpInst::ICMP_EQ;
5199   } else if (ICmpInst::isUnsigned(Pred)) {
5200     // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5201     // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5202 
5203     if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5204         match(Op0, m_OneUse(m_c_Xor(m_Add(m_Specific(Op1), m_AllOnes()),
5205                                     m_Specific(Op1))))) {
5206       A = Op1;
5207       CheckIs = Pred == ICmpInst::ICMP_UGE;
5208     } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5209                match(Op1, m_OneUse(m_c_Xor(m_Add(m_Specific(Op0), m_AllOnes()),
5210                                            m_Specific(Op0))))) {
5211       A = Op0;
5212       CheckIs = Pred == ICmpInst::ICMP_ULE;
5213     }
5214   }
5215 
5216   if (A) {
5217     Type *Ty = A->getType();
5218     CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5219     return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5220                                   ConstantInt::get(Ty, 2))
5221                    : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5222                                   ConstantInt::get(Ty, 1));
5223   }
5224 
5225   return nullptr;
5226 }
5227 
5228 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
5229   if (!I.isEquality())
5230     return nullptr;
5231 
5232   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5233   const CmpInst::Predicate Pred = I.getPredicate();
5234   Value *A, *B, *C, *D;
5235   if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5236     if (A == Op1 || B == Op1) { // (A^B) == A  ->  B == 0
5237       Value *OtherVal = A == Op1 ? B : A;
5238       return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5239     }
5240 
5241     if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5242       // A^c1 == C^c2 --> A == C^(c1^c2)
5243       ConstantInt *C1, *C2;
5244       if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
5245           Op1->hasOneUse()) {
5246         Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
5247         Value *Xor = Builder.CreateXor(C, NC);
5248         return new ICmpInst(Pred, A, Xor);
5249       }
5250 
5251       // A^B == A^D -> B == D
5252       if (A == C)
5253         return new ICmpInst(Pred, B, D);
5254       if (A == D)
5255         return new ICmpInst(Pred, B, C);
5256       if (B == C)
5257         return new ICmpInst(Pred, A, D);
5258       if (B == D)
5259         return new ICmpInst(Pred, A, C);
5260     }
5261   }
5262 
5263   // canoncalize:
5264   // (icmp eq/ne (and X, C), X)
5265   //    -> (icmp eq/ne (and X, ~C), 0)
5266   {
5267     Constant *CMask;
5268     A = nullptr;
5269     if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_ImmConstant(CMask)))))
5270       A = Op1;
5271     else if (match(Op1, m_OneUse(m_And(m_Specific(Op0), m_ImmConstant(CMask)))))
5272       A = Op0;
5273     if (A)
5274       return new ICmpInst(Pred, Builder.CreateAnd(A, Builder.CreateNot(CMask)),
5275                           Constant::getNullValue(A->getType()));
5276   }
5277 
5278   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
5279     // A == (A^B)  ->  B == 0
5280     Value *OtherVal = A == Op0 ? B : A;
5281     return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5282   }
5283 
5284   // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5285   if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
5286       match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
5287     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
5288 
5289     if (A == C) {
5290       X = B;
5291       Y = D;
5292       Z = A;
5293     } else if (A == D) {
5294       X = B;
5295       Y = C;
5296       Z = A;
5297     } else if (B == C) {
5298       X = A;
5299       Y = D;
5300       Z = B;
5301     } else if (B == D) {
5302       X = A;
5303       Y = C;
5304       Z = B;
5305     }
5306 
5307     if (X) { // Build (X^Y) & Z
5308       Op1 = Builder.CreateXor(X, Y);
5309       Op1 = Builder.CreateAnd(Op1, Z);
5310       return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
5311     }
5312   }
5313 
5314   {
5315     // Similar to above, but specialized for constant because invert is needed:
5316     // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
5317     Value *X, *Y;
5318     Constant *C;
5319     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
5320         match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
5321       Value *Xor = Builder.CreateXor(X, Y);
5322       Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
5323       return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
5324     }
5325   }
5326 
5327   if (match(Op1, m_ZExt(m_Value(A))) &&
5328       (Op0->hasOneUse() || Op1->hasOneUse())) {
5329     // (B & (Pow2C-1)) == zext A --> A == trunc B
5330     // (B & (Pow2C-1)) != zext A --> A != trunc B
5331     const APInt *MaskC;
5332     if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
5333         MaskC->countr_one() == A->getType()->getScalarSizeInBits())
5334       return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
5335   }
5336 
5337   // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
5338   // For lshr and ashr pairs.
5339   const APInt *AP1, *AP2;
5340   if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5341        match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) ||
5342       (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5343        match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) {
5344     if (AP1 != AP2)
5345       return nullptr;
5346     unsigned TypeBits = AP1->getBitWidth();
5347     unsigned ShAmt = AP1->getLimitedValue(TypeBits);
5348     if (ShAmt < TypeBits && ShAmt != 0) {
5349       ICmpInst::Predicate NewPred =
5350           Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5351       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5352       APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
5353       return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
5354     }
5355   }
5356 
5357   // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
5358   ConstantInt *Cst1;
5359   if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
5360       match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
5361     unsigned TypeBits = Cst1->getBitWidth();
5362     unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
5363     if (ShAmt < TypeBits && ShAmt != 0) {
5364       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5365       APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
5366       Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
5367                                       I.getName() + ".mask");
5368       return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
5369     }
5370   }
5371 
5372   // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
5373   // "icmp (and X, mask), cst"
5374   uint64_t ShAmt = 0;
5375   if (Op0->hasOneUse() &&
5376       match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
5377       match(Op1, m_ConstantInt(Cst1)) &&
5378       // Only do this when A has multiple uses.  This is most important to do
5379       // when it exposes other optimizations.
5380       !A->hasOneUse()) {
5381     unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
5382 
5383     if (ShAmt < ASize) {
5384       APInt MaskV =
5385           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
5386       MaskV <<= ShAmt;
5387 
5388       APInt CmpV = Cst1->getValue().zext(ASize);
5389       CmpV <<= ShAmt;
5390 
5391       Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
5392       return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
5393     }
5394   }
5395 
5396   if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I, Builder))
5397     return ICmp;
5398 
5399   // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the
5400   // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",
5401   // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps
5402   // of instcombine.
5403   unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5404   if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
5405       match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
5406       A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
5407       (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
5408     APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
5409     Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
5410     return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
5411                                                   : ICmpInst::ICMP_UGE,
5412                         Add, ConstantInt::get(A->getType(), C.shl(1)));
5413   }
5414 
5415   // Canonicalize:
5416   // Assume B_Pow2 != 0
5417   // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
5418   // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
5419   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
5420       isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
5421     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
5422                         ConstantInt::getNullValue(Op0->getType()));
5423 
5424   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
5425       isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
5426     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
5427                         ConstantInt::getNullValue(Op1->getType()));
5428 
5429   // Canonicalize:
5430   // icmp eq/ne X, OneUse(rotate-right(X))
5431   //    -> icmp eq/ne X, rotate-left(X)
5432   // We generally try to convert rotate-right -> rotate-left, this just
5433   // canonicalizes another case.
5434   CmpInst::Predicate PredUnused = Pred;
5435   if (match(&I, m_c_ICmp(PredUnused, m_Value(A),
5436                          m_OneUse(m_Intrinsic<Intrinsic::fshr>(
5437                              m_Deferred(A), m_Deferred(A), m_Value(B))))))
5438     return new ICmpInst(
5439         Pred, A,
5440         Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
5441 
5442   // Canonicalize:
5443   // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
5444   Constant *Cst;
5445   if (match(&I, m_c_ICmp(PredUnused,
5446                          m_OneUse(m_Xor(m_Value(A), m_ImmConstant(Cst))),
5447                          m_CombineAnd(m_Value(B), m_Unless(m_ImmConstant())))))
5448     return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
5449 
5450   {
5451     // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
5452     auto m_Matcher =
5453         m_CombineOr(m_CombineOr(m_c_Add(m_Value(B), m_Deferred(A)),
5454                                 m_c_Xor(m_Value(B), m_Deferred(A))),
5455                     m_Sub(m_Value(B), m_Deferred(A)));
5456     std::optional<bool> IsZero = std::nullopt;
5457     if (match(&I, m_c_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),
5458                            m_Deferred(A))))
5459       IsZero = false;
5460     // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
5461     else if (match(&I,
5462                    m_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),
5463                           m_Zero())))
5464       IsZero = true;
5465 
5466     if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, /*Depth*/ 0, &I))
5467       // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
5468       //    -> (icmp eq/ne (and X, P2), 0)
5469       // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
5470       //    -> (icmp eq/ne (and X, P2), P2)
5471       return new ICmpInst(Pred, Builder.CreateAnd(B, A),
5472                           *IsZero ? A
5473                                   : ConstantInt::getNullValue(A->getType()));
5474   }
5475 
5476   return nullptr;
5477 }
5478 
5479 Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
5480   ICmpInst::Predicate Pred = ICmp.getPredicate();
5481   Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
5482 
5483   // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
5484   // The trunc masks high bits while the compare may effectively mask low bits.
5485   Value *X;
5486   const APInt *C;
5487   if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
5488     return nullptr;
5489 
5490   // This matches patterns corresponding to tests of the signbit as well as:
5491   // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)
5492   // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)
5493   APInt Mask;
5494   if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {
5495     Value *And = Builder.CreateAnd(X, Mask);
5496     Constant *Zero = ConstantInt::getNullValue(X->getType());
5497     return new ICmpInst(Pred, And, Zero);
5498   }
5499 
5500   unsigned SrcBits = X->getType()->getScalarSizeInBits();
5501   if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {
5502     // If C is a negative power-of-2 (high-bit mask):
5503     // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)
5504     Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));
5505     Value *And = Builder.CreateAnd(X, MaskC);
5506     return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);
5507   }
5508 
5509   if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {
5510     // If C is not-of-power-of-2 (one clear bit):
5511     // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)
5512     Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));
5513     Value *And = Builder.CreateAnd(X, MaskC);
5514     return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);
5515   }
5516 
5517   if (auto *II = dyn_cast<IntrinsicInst>(X)) {
5518     if (II->getIntrinsicID() == Intrinsic::cttz ||
5519         II->getIntrinsicID() == Intrinsic::ctlz) {
5520       unsigned MaxRet = SrcBits;
5521       // If the "is_zero_poison" argument is set, then we know at least
5522       // one bit is set in the input, so the result is always at least one
5523       // less than the full bitwidth of that input.
5524       if (match(II->getArgOperand(1), m_One()))
5525         MaxRet--;
5526 
5527       // Make sure the destination is wide enough to hold the largest output of
5528       // the intrinsic.
5529       if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
5530         if (Instruction *I =
5531                 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
5532           return I;
5533     }
5534   }
5535 
5536   return nullptr;
5537 }
5538 
5539 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
5540   assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
5541   auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
5542   Value *X;
5543   if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
5544     return nullptr;
5545 
5546   bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
5547   bool IsSignedCmp = ICmp.isSigned();
5548 
5549   // icmp Pred (ext X), (ext Y)
5550   Value *Y;
5551   if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
5552     bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
5553     bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
5554 
5555     if (IsZext0 != IsZext1) {
5556         // If X and Y and both i1
5557         // (icmp eq/ne (zext X) (sext Y))
5558         //      eq -> (icmp eq (or X, Y), 0)
5559         //      ne -> (icmp ne (or X, Y), 0)
5560       if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
5561           Y->getType()->isIntOrIntVectorTy(1))
5562         return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
5563                             Constant::getNullValue(X->getType()));
5564 
5565       // If we have mismatched casts and zext has the nneg flag, we can
5566       //  treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
5567 
5568       auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
5569       auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
5570 
5571       bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
5572       bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
5573 
5574       if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
5575         IsSignedExt = true;
5576       else
5577         return nullptr;
5578     }
5579 
5580     // Not an extension from the same type?
5581     Type *XTy = X->getType(), *YTy = Y->getType();
5582     if (XTy != YTy) {
5583       // One of the casts must have one use because we are creating a new cast.
5584       if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
5585         return nullptr;
5586       // Extend the narrower operand to the type of the wider operand.
5587       CastInst::CastOps CastOpcode =
5588           IsSignedExt ? Instruction::SExt : Instruction::ZExt;
5589       if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
5590         X = Builder.CreateCast(CastOpcode, X, YTy);
5591       else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
5592         Y = Builder.CreateCast(CastOpcode, Y, XTy);
5593       else
5594         return nullptr;
5595     }
5596 
5597     // (zext X) == (zext Y) --> X == Y
5598     // (sext X) == (sext Y) --> X == Y
5599     if (ICmp.isEquality())
5600       return new ICmpInst(ICmp.getPredicate(), X, Y);
5601 
5602     // A signed comparison of sign extended values simplifies into a
5603     // signed comparison.
5604     if (IsSignedCmp && IsSignedExt)
5605       return new ICmpInst(ICmp.getPredicate(), X, Y);
5606 
5607     // The other three cases all fold into an unsigned comparison.
5608     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
5609   }
5610 
5611   // Below here, we are only folding a compare with constant.
5612   auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
5613   if (!C)
5614     return nullptr;
5615 
5616   // If a lossless truncate is possible...
5617   Type *SrcTy = CastOp0->getSrcTy();
5618   Constant *Res = getLosslessTrunc(C, SrcTy, CastOp0->getOpcode());
5619   if (Res) {
5620     if (ICmp.isEquality())
5621       return new ICmpInst(ICmp.getPredicate(), X, Res);
5622 
5623     // A signed comparison of sign extended values simplifies into a
5624     // signed comparison.
5625     if (IsSignedExt && IsSignedCmp)
5626       return new ICmpInst(ICmp.getPredicate(), X, Res);
5627 
5628     // The other three cases all fold into an unsigned comparison.
5629     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
5630   }
5631 
5632   // The re-extended constant changed, partly changed (in the case of a vector),
5633   // or could not be determined to be equal (in the case of a constant
5634   // expression), so the constant cannot be represented in the shorter type.
5635   // All the cases that fold to true or false will have already been handled
5636   // by simplifyICmpInst, so only deal with the tricky case.
5637   if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
5638     return nullptr;
5639 
5640   // Is source op positive?
5641   // icmp ult (sext X), C --> icmp sgt X, -1
5642   if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
5643     return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
5644 
5645   // Is source op negative?
5646   // icmp ugt (sext X), C --> icmp slt X, 0
5647   assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
5648   return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
5649 }
5650 
5651 /// Handle icmp (cast x), (cast or constant).
5652 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
5653   // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
5654   // icmp compares only pointer's value.
5655   // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
5656   Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
5657   Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
5658   if (SimplifiedOp0 || SimplifiedOp1)
5659     return new ICmpInst(ICmp.getPredicate(),
5660                         SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
5661                         SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
5662 
5663   auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
5664   if (!CastOp0)
5665     return nullptr;
5666   if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
5667     return nullptr;
5668 
5669   Value *Op0Src = CastOp0->getOperand(0);
5670   Type *SrcTy = CastOp0->getSrcTy();
5671   Type *DestTy = CastOp0->getDestTy();
5672 
5673   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5674   // integer type is the same size as the pointer type.
5675   auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
5676     if (isa<VectorType>(SrcTy)) {
5677       SrcTy = cast<VectorType>(SrcTy)->getElementType();
5678       DestTy = cast<VectorType>(DestTy)->getElementType();
5679     }
5680     return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
5681   };
5682   if (CastOp0->getOpcode() == Instruction::PtrToInt &&
5683       CompatibleSizes(SrcTy, DestTy)) {
5684     Value *NewOp1 = nullptr;
5685     if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
5686       Value *PtrSrc = PtrToIntOp1->getOperand(0);
5687       if (PtrSrc->getType() == Op0Src->getType())
5688         NewOp1 = PtrToIntOp1->getOperand(0);
5689     } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
5690       NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5691     }
5692 
5693     if (NewOp1)
5694       return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
5695   }
5696 
5697   if (Instruction *R = foldICmpWithTrunc(ICmp))
5698     return R;
5699 
5700   return foldICmpWithZextOrSext(ICmp);
5701 }
5702 
5703 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {
5704   switch (BinaryOp) {
5705     default:
5706       llvm_unreachable("Unsupported binary op");
5707     case Instruction::Add:
5708     case Instruction::Sub:
5709       return match(RHS, m_Zero());
5710     case Instruction::Mul:
5711       return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
5712              match(RHS, m_One());
5713   }
5714 }
5715 
5716 OverflowResult
5717 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
5718                                   bool IsSigned, Value *LHS, Value *RHS,
5719                                   Instruction *CxtI) const {
5720   switch (BinaryOp) {
5721     default:
5722       llvm_unreachable("Unsupported binary op");
5723     case Instruction::Add:
5724       if (IsSigned)
5725         return computeOverflowForSignedAdd(LHS, RHS, CxtI);
5726       else
5727         return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
5728     case Instruction::Sub:
5729       if (IsSigned)
5730         return computeOverflowForSignedSub(LHS, RHS, CxtI);
5731       else
5732         return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
5733     case Instruction::Mul:
5734       if (IsSigned)
5735         return computeOverflowForSignedMul(LHS, RHS, CxtI);
5736       else
5737         return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
5738   }
5739 }
5740 
5741 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
5742                                              bool IsSigned, Value *LHS,
5743                                              Value *RHS, Instruction &OrigI,
5744                                              Value *&Result,
5745                                              Constant *&Overflow) {
5746   if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
5747     std::swap(LHS, RHS);
5748 
5749   // If the overflow check was an add followed by a compare, the insertion point
5750   // may be pointing to the compare.  We want to insert the new instructions
5751   // before the add in case there are uses of the add between the add and the
5752   // compare.
5753   Builder.SetInsertPoint(&OrigI);
5754 
5755   Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
5756   if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
5757     OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
5758 
5759   if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
5760     Result = LHS;
5761     Overflow = ConstantInt::getFalse(OverflowTy);
5762     return true;
5763   }
5764 
5765   switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
5766     case OverflowResult::MayOverflow:
5767       return false;
5768     case OverflowResult::AlwaysOverflowsLow:
5769     case OverflowResult::AlwaysOverflowsHigh:
5770       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5771       Result->takeName(&OrigI);
5772       Overflow = ConstantInt::getTrue(OverflowTy);
5773       return true;
5774     case OverflowResult::NeverOverflows:
5775       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5776       Result->takeName(&OrigI);
5777       Overflow = ConstantInt::getFalse(OverflowTy);
5778       if (auto *Inst = dyn_cast<Instruction>(Result)) {
5779         if (IsSigned)
5780           Inst->setHasNoSignedWrap();
5781         else
5782           Inst->setHasNoUnsignedWrap();
5783       }
5784       return true;
5785   }
5786 
5787   llvm_unreachable("Unexpected overflow result");
5788 }
5789 
5790 /// Recognize and process idiom involving test for multiplication
5791 /// overflow.
5792 ///
5793 /// The caller has matched a pattern of the form:
5794 ///   I = cmp u (mul(zext A, zext B), V
5795 /// The function checks if this is a test for overflow and if so replaces
5796 /// multiplication with call to 'mul.with.overflow' intrinsic.
5797 ///
5798 /// \param I Compare instruction.
5799 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
5800 ///               the compare instruction.  Must be of integer type.
5801 /// \param OtherVal The other argument of compare instruction.
5802 /// \returns Instruction which must replace the compare instruction, NULL if no
5803 ///          replacement required.
5804 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
5805                                          const APInt *OtherVal,
5806                                          InstCombinerImpl &IC) {
5807   // Don't bother doing this transformation for pointers, don't do it for
5808   // vectors.
5809   if (!isa<IntegerType>(MulVal->getType()))
5810     return nullptr;
5811 
5812   auto *MulInstr = dyn_cast<Instruction>(MulVal);
5813   if (!MulInstr)
5814     return nullptr;
5815   assert(MulInstr->getOpcode() == Instruction::Mul);
5816 
5817   auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
5818        *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
5819   assert(LHS->getOpcode() == Instruction::ZExt);
5820   assert(RHS->getOpcode() == Instruction::ZExt);
5821   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
5822 
5823   // Calculate type and width of the result produced by mul.with.overflow.
5824   Type *TyA = A->getType(), *TyB = B->getType();
5825   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
5826            WidthB = TyB->getPrimitiveSizeInBits();
5827   unsigned MulWidth;
5828   Type *MulType;
5829   if (WidthB > WidthA) {
5830     MulWidth = WidthB;
5831     MulType = TyB;
5832   } else {
5833     MulWidth = WidthA;
5834     MulType = TyA;
5835   }
5836 
5837   // In order to replace the original mul with a narrower mul.with.overflow,
5838   // all uses must ignore upper bits of the product.  The number of used low
5839   // bits must be not greater than the width of mul.with.overflow.
5840   if (MulVal->hasNUsesOrMore(2))
5841     for (User *U : MulVal->users()) {
5842       if (U == &I)
5843         continue;
5844       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5845         // Check if truncation ignores bits above MulWidth.
5846         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
5847         if (TruncWidth > MulWidth)
5848           return nullptr;
5849       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5850         // Check if AND ignores bits above MulWidth.
5851         if (BO->getOpcode() != Instruction::And)
5852           return nullptr;
5853         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5854           const APInt &CVal = CI->getValue();
5855           if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
5856             return nullptr;
5857         } else {
5858           // In this case we could have the operand of the binary operation
5859           // being defined in another block, and performing the replacement
5860           // could break the dominance relation.
5861           return nullptr;
5862         }
5863       } else {
5864         // Other uses prohibit this transformation.
5865         return nullptr;
5866       }
5867     }
5868 
5869   // Recognize patterns
5870   switch (I.getPredicate()) {
5871   case ICmpInst::ICMP_UGT: {
5872     // Recognize pattern:
5873     //   mulval = mul(zext A, zext B)
5874     //   cmp ugt mulval, max
5875     APInt MaxVal = APInt::getMaxValue(MulWidth);
5876     MaxVal = MaxVal.zext(OtherVal->getBitWidth());
5877     if (MaxVal.eq(*OtherVal))
5878       break; // Recognized
5879     return nullptr;
5880   }
5881 
5882   case ICmpInst::ICMP_ULT: {
5883     // Recognize pattern:
5884     //   mulval = mul(zext A, zext B)
5885     //   cmp ule mulval, max + 1
5886     APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
5887     if (MaxVal.eq(*OtherVal))
5888       break; // Recognized
5889     return nullptr;
5890   }
5891 
5892   default:
5893     return nullptr;
5894   }
5895 
5896   InstCombiner::BuilderTy &Builder = IC.Builder;
5897   Builder.SetInsertPoint(MulInstr);
5898 
5899   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
5900   Value *MulA = A, *MulB = B;
5901   if (WidthA < MulWidth)
5902     MulA = Builder.CreateZExt(A, MulType);
5903   if (WidthB < MulWidth)
5904     MulB = Builder.CreateZExt(B, MulType);
5905   Function *F = Intrinsic::getDeclaration(
5906       I.getModule(), Intrinsic::umul_with_overflow, MulType);
5907   CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
5908   IC.addToWorklist(MulInstr);
5909 
5910   // If there are uses of mul result other than the comparison, we know that
5911   // they are truncation or binary AND. Change them to use result of
5912   // mul.with.overflow and adjust properly mask/size.
5913   if (MulVal->hasNUsesOrMore(2)) {
5914     Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
5915     for (User *U : make_early_inc_range(MulVal->users())) {
5916       if (U == &I)
5917         continue;
5918       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5919         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
5920           IC.replaceInstUsesWith(*TI, Mul);
5921         else
5922           TI->setOperand(0, Mul);
5923       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5924         assert(BO->getOpcode() == Instruction::And);
5925         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
5926         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
5927         APInt ShortMask = CI->getValue().trunc(MulWidth);
5928         Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
5929         Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
5930         IC.replaceInstUsesWith(*BO, Zext);
5931       } else {
5932         llvm_unreachable("Unexpected Binary operation");
5933       }
5934       IC.addToWorklist(cast<Instruction>(U));
5935     }
5936   }
5937 
5938   // The original icmp gets replaced with the overflow value, maybe inverted
5939   // depending on predicate.
5940   if (I.getPredicate() == ICmpInst::ICMP_ULT) {
5941     Value *Res = Builder.CreateExtractValue(Call, 1);
5942     return BinaryOperator::CreateNot(Res);
5943   }
5944 
5945   return ExtractValueInst::Create(Call, 1);
5946 }
5947 
5948 /// When performing a comparison against a constant, it is possible that not all
5949 /// the bits in the LHS are demanded. This helper method computes the mask that
5950 /// IS demanded.
5951 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
5952   const APInt *RHS;
5953   if (!match(I.getOperand(1), m_APInt(RHS)))
5954     return APInt::getAllOnes(BitWidth);
5955 
5956   // If this is a normal comparison, it demands all bits. If it is a sign bit
5957   // comparison, it only demands the sign bit.
5958   bool UnusedBit;
5959   if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
5960     return APInt::getSignMask(BitWidth);
5961 
5962   switch (I.getPredicate()) {
5963   // For a UGT comparison, we don't care about any bits that
5964   // correspond to the trailing ones of the comparand.  The value of these
5965   // bits doesn't impact the outcome of the comparison, because any value
5966   // greater than the RHS must differ in a bit higher than these due to carry.
5967   case ICmpInst::ICMP_UGT:
5968     return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
5969 
5970   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
5971   // Any value less than the RHS must differ in a higher bit because of carries.
5972   case ICmpInst::ICMP_ULT:
5973     return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
5974 
5975   default:
5976     return APInt::getAllOnes(BitWidth);
5977   }
5978 }
5979 
5980 /// Check that one use is in the same block as the definition and all
5981 /// other uses are in blocks dominated by a given block.
5982 ///
5983 /// \param DI Definition
5984 /// \param UI Use
5985 /// \param DB Block that must dominate all uses of \p DI outside
5986 ///           the parent block
5987 /// \return true when \p UI is the only use of \p DI in the parent block
5988 /// and all other uses of \p DI are in blocks dominated by \p DB.
5989 ///
5990 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
5991                                         const Instruction *UI,
5992                                         const BasicBlock *DB) const {
5993   assert(DI && UI && "Instruction not defined\n");
5994   // Ignore incomplete definitions.
5995   if (!DI->getParent())
5996     return false;
5997   // DI and UI must be in the same block.
5998   if (DI->getParent() != UI->getParent())
5999     return false;
6000   // Protect from self-referencing blocks.
6001   if (DI->getParent() == DB)
6002     return false;
6003   for (const User *U : DI->users()) {
6004     auto *Usr = cast<Instruction>(U);
6005     if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6006       return false;
6007   }
6008   return true;
6009 }
6010 
6011 /// Return true when the instruction sequence within a block is select-cmp-br.
6012 static bool isChainSelectCmpBranch(const SelectInst *SI) {
6013   const BasicBlock *BB = SI->getParent();
6014   if (!BB)
6015     return false;
6016   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
6017   if (!BI || BI->getNumSuccessors() != 2)
6018     return false;
6019   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
6020   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
6021     return false;
6022   return true;
6023 }
6024 
6025 /// True when a select result is replaced by one of its operands
6026 /// in select-icmp sequence. This will eventually result in the elimination
6027 /// of the select.
6028 ///
6029 /// \param SI    Select instruction
6030 /// \param Icmp  Compare instruction
6031 /// \param SIOpd Operand that replaces the select
6032 ///
6033 /// Notes:
6034 /// - The replacement is global and requires dominator information
6035 /// - The caller is responsible for the actual replacement
6036 ///
6037 /// Example:
6038 ///
6039 /// entry:
6040 ///  %4 = select i1 %3, %C* %0, %C* null
6041 ///  %5 = icmp eq %C* %4, null
6042 ///  br i1 %5, label %9, label %7
6043 ///  ...
6044 ///  ; <label>:7                                       ; preds = %entry
6045 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6046 ///  ...
6047 ///
6048 /// can be transformed to
6049 ///
6050 ///  %5 = icmp eq %C* %0, null
6051 ///  %6 = select i1 %3, i1 %5, i1 true
6052 ///  br i1 %6, label %9, label %7
6053 ///  ...
6054 ///  ; <label>:7                                       ; preds = %entry
6055 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
6056 ///
6057 /// Similar when the first operand of the select is a constant or/and
6058 /// the compare is for not equal rather than equal.
6059 ///
6060 /// NOTE: The function is only called when the select and compare constants
6061 /// are equal, the optimization can work only for EQ predicates. This is not a
6062 /// major restriction since a NE compare should be 'normalized' to an equal
6063 /// compare, which usually happens in the combiner and test case
6064 /// select-cmp-br.ll checks for it.
6065 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
6066                                                  const ICmpInst *Icmp,
6067                                                  const unsigned SIOpd) {
6068   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6069   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
6070     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
6071     // The check for the single predecessor is not the best that can be
6072     // done. But it protects efficiently against cases like when SI's
6073     // home block has two successors, Succ and Succ1, and Succ1 predecessor
6074     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6075     // replaced can be reached on either path. So the uniqueness check
6076     // guarantees that the path all uses of SI (outside SI's parent) are on
6077     // is disjoint from all other paths out of SI. But that information
6078     // is more expensive to compute, and the trade-off here is in favor
6079     // of compile-time. It should also be noticed that we check for a single
6080     // predecessor and not only uniqueness. This to handle the situation when
6081     // Succ and Succ1 points to the same basic block.
6082     if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
6083       NumSel++;
6084       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
6085       return true;
6086     }
6087   }
6088   return false;
6089 }
6090 
6091 /// Try to fold the comparison based on range information we can get by checking
6092 /// whether bits are known to be zero or one in the inputs.
6093 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6094   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6095   Type *Ty = Op0->getType();
6096   ICmpInst::Predicate Pred = I.getPredicate();
6097 
6098   // Get scalar or pointer size.
6099   unsigned BitWidth = Ty->isIntOrIntVectorTy()
6100                           ? Ty->getScalarSizeInBits()
6101                           : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6102 
6103   if (!BitWidth)
6104     return nullptr;
6105 
6106   KnownBits Op0Known(BitWidth);
6107   KnownBits Op1Known(BitWidth);
6108 
6109   {
6110     // Don't use dominating conditions when folding icmp using known bits. This
6111     // may convert signed into unsigned predicates in ways that other passes
6112     // (especially IndVarSimplify) may not be able to reliably undo.
6113     SQ.DC = nullptr;
6114     auto _ = make_scope_exit([&]() { SQ.DC = &DC; });
6115     if (SimplifyDemandedBits(&I, 0, getDemandedBitsLHSMask(I, BitWidth),
6116                              Op0Known, 0))
6117       return &I;
6118 
6119     if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0))
6120       return &I;
6121   }
6122 
6123   // Given the known and unknown bits, compute a range that the LHS could be
6124   // in.  Compute the Min, Max and RHS values based on the known bits. For the
6125   // EQ and NE we use unsigned values.
6126   APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127   APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128   if (I.isSigned()) {
6129     Op0Min = Op0Known.getSignedMinValue();
6130     Op0Max = Op0Known.getSignedMaxValue();
6131     Op1Min = Op1Known.getSignedMinValue();
6132     Op1Max = Op1Known.getSignedMaxValue();
6133   } else {
6134     Op0Min = Op0Known.getMinValue();
6135     Op0Max = Op0Known.getMaxValue();
6136     Op1Min = Op1Known.getMinValue();
6137     Op1Max = Op1Known.getMaxValue();
6138   }
6139 
6140   // If Min and Max are known to be the same, then SimplifyDemandedBits figured
6141   // out that the LHS or RHS is a constant. Constant fold this now, so that
6142   // code below can assume that Min != Max.
6143   if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6144     return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
6145   if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6146     return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
6147 
6148   // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6149   // min/max canonical compare with some other compare. That could lead to
6150   // conflict with select canonicalization and infinite looping.
6151   // FIXME: This constraint may go away if min/max intrinsics are canonical.
6152   auto isMinMaxCmp = [&](Instruction &Cmp) {
6153     if (!Cmp.hasOneUse())
6154       return false;
6155     Value *A, *B;
6156     SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
6157     if (!SelectPatternResult::isMinOrMax(SPF))
6158       return false;
6159     return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
6160            match(Op1, m_MaxOrMin(m_Value(), m_Value()));
6161   };
6162   if (!isMinMaxCmp(I)) {
6163     switch (Pred) {
6164     default:
6165       break;
6166     case ICmpInst::ICMP_ULT: {
6167       if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6168         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6169       const APInt *CmpC;
6170       if (match(Op1, m_APInt(CmpC))) {
6171         // A <u C -> A == C-1 if min(A)+1 == C
6172         if (*CmpC == Op0Min + 1)
6173           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6174                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6175         // X <u C --> X == 0, if the number of zero bits in the bottom of X
6176         // exceeds the log2 of C.
6177         if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
6178           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6179                               Constant::getNullValue(Op1->getType()));
6180       }
6181       break;
6182     }
6183     case ICmpInst::ICMP_UGT: {
6184       if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6185         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6186       const APInt *CmpC;
6187       if (match(Op1, m_APInt(CmpC))) {
6188         // A >u C -> A == C+1 if max(a)-1 == C
6189         if (*CmpC == Op0Max - 1)
6190           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6191                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6192         // X >u C --> X != 0, if the number of zero bits in the bottom of X
6193         // exceeds the log2 of C.
6194         if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
6195           return new ICmpInst(ICmpInst::ICMP_NE, Op0,
6196                               Constant::getNullValue(Op1->getType()));
6197       }
6198       break;
6199     }
6200     case ICmpInst::ICMP_SLT: {
6201       if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6202         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6203       const APInt *CmpC;
6204       if (match(Op1, m_APInt(CmpC))) {
6205         if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
6206           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6207                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6208       }
6209       break;
6210     }
6211     case ICmpInst::ICMP_SGT: {
6212       if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6213         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6214       const APInt *CmpC;
6215       if (match(Op1, m_APInt(CmpC))) {
6216         if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
6217           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6218                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6219       }
6220       break;
6221     }
6222     }
6223   }
6224 
6225   // Based on the range information we know about the LHS, see if we can
6226   // simplify this comparison.  For example, (x&4) < 8 is always true.
6227   switch (Pred) {
6228   default:
6229     llvm_unreachable("Unknown icmp opcode!");
6230   case ICmpInst::ICMP_EQ:
6231   case ICmpInst::ICMP_NE: {
6232     if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6233       return replaceInstUsesWith(
6234           I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));
6235 
6236     // If all bits are known zero except for one, then we know at most one bit
6237     // is set. If the comparison is against zero, then this is a check to see if
6238     // *that* bit is set.
6239     APInt Op0KnownZeroInverted = ~Op0Known.Zero;
6240     if (Op1Known.isZero()) {
6241       // If the LHS is an AND with the same constant, look through it.
6242       Value *LHS = nullptr;
6243       const APInt *LHSC;
6244       if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
6245           *LHSC != Op0KnownZeroInverted)
6246         LHS = Op0;
6247 
6248       Value *X;
6249       const APInt *C1;
6250       if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
6251         Type *XTy = X->getType();
6252         unsigned Log2C1 = C1->countr_zero();
6253         APInt C2 = Op0KnownZeroInverted;
6254         APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
6255         if (C2Pow2.isPowerOf2()) {
6256           // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
6257           // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
6258           // ((C1 << X) & C2) != 0 -> X  < (Log2(C2+C1) - Log2(C1))
6259           unsigned Log2C2 = C2Pow2.countr_zero();
6260           auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
6261           auto NewPred =
6262               Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
6263           return new ICmpInst(NewPred, X, CmpC);
6264         }
6265       }
6266     }
6267 
6268     // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
6269     if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
6270         (Op0Known & Op1Known) == Op0Known)
6271       return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6272                           ConstantInt::getNullValue(Op1->getType()));
6273     break;
6274   }
6275   case ICmpInst::ICMP_ULT: {
6276     if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6277       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6278     if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6279       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6280     break;
6281   }
6282   case ICmpInst::ICMP_UGT: {
6283     if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6284       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6285     if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6286       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6287     break;
6288   }
6289   case ICmpInst::ICMP_SLT: {
6290     if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6291       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6292     if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6293       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6294     break;
6295   }
6296   case ICmpInst::ICMP_SGT: {
6297     if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6298       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6299     if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6300       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6301     break;
6302   }
6303   case ICmpInst::ICMP_SGE:
6304     assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6305     if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6306       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6307     if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6308       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6309     if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
6310       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6311     break;
6312   case ICmpInst::ICMP_SLE:
6313     assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6314     if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6315       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6316     if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6317       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6318     if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
6319       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6320     break;
6321   case ICmpInst::ICMP_UGE:
6322     assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6323     if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6324       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6325     if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6326       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6327     if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
6328       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6329     break;
6330   case ICmpInst::ICMP_ULE:
6331     assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6332     if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6333       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6334     if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6335       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6336     if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
6337       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6338     break;
6339   }
6340 
6341   // Turn a signed comparison into an unsigned one if both operands are known to
6342   // have the same sign.
6343   if (I.isSigned() &&
6344       ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
6345        (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
6346     return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6347 
6348   return nullptr;
6349 }
6350 
6351 /// If one operand of an icmp is effectively a bool (value range of {0,1}),
6352 /// then try to reduce patterns based on that limit.
6353 Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
6354   Value *X, *Y;
6355   ICmpInst::Predicate Pred;
6356 
6357   // X must be 0 and bool must be true for "ULT":
6358   // X <u (zext i1 Y) --> (X == 0) & Y
6359   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
6360       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
6361     return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
6362 
6363   // X must be 0 or bool must be true for "ULE":
6364   // X <=u (sext i1 Y) --> (X == 0) | Y
6365   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
6366       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
6367     return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
6368 
6369   // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
6370   ICmpInst::Predicate Pred1, Pred2;
6371   const APInt *C;
6372   Instruction *ExtI;
6373   if (match(&I, m_c_ICmp(Pred1, m_Value(X),
6374                          m_CombineAnd(m_Instruction(ExtI),
6375                                       m_ZExtOrSExt(m_ICmp(Pred2, m_Deferred(X),
6376                                                           m_APInt(C)))))) &&
6377       ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
6378     bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
6379     bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
6380     auto CreateRangeCheck = [&] {
6381       Value *CmpV1 =
6382           Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
6383       Value *CmpV2 = Builder.CreateICmp(
6384           Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
6385       return BinaryOperator::Create(
6386           Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
6387           CmpV1, CmpV2);
6388     };
6389     if (C->isZero()) {
6390       if (Pred2 == ICmpInst::ICMP_EQ) {
6391         // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
6392         // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
6393         return replaceInstUsesWith(
6394             I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6395       } else if (!IsSExt || HasOneUse) {
6396         // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
6397         // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
6398         // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
6399         // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X == -1
6400         return CreateRangeCheck();
6401       }
6402     } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
6403       if (Pred2 == ICmpInst::ICMP_NE) {
6404         // icmp eq X, (zext (icmp ne X, 1)) --> false
6405         // icmp ne X, (zext (icmp ne X, 1)) --> true
6406         // icmp eq X, (sext (icmp ne X, -1)) --> false
6407         // icmp ne X, (sext (icmp ne X, -1)) --> true
6408         return replaceInstUsesWith(
6409             I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6410       } else if (!IsSExt || HasOneUse) {
6411         // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
6412         // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
6413         // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
6414         // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
6415         return CreateRangeCheck();
6416       }
6417     } else {
6418       // when C != 0 && C != 1:
6419       //   icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
6420       //   icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
6421       //   icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
6422       //   icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
6423       // when C != 0 && C != -1:
6424       //   icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
6425       //   icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
6426       //   icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
6427       //   icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
6428       return ICmpInst::Create(
6429           Instruction::ICmp, Pred1, X,
6430           ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
6431                                                    ? (IsSExt ? -1 : 1)
6432                                                    : 0));
6433     }
6434   }
6435 
6436   return nullptr;
6437 }
6438 
6439 std::optional<std::pair<CmpInst::Predicate, Constant *>>
6440 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
6441                                                        Constant *C) {
6442   assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
6443          "Only for relational integer predicates.");
6444 
6445   Type *Type = C->getType();
6446   bool IsSigned = ICmpInst::isSigned(Pred);
6447 
6448   CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
6449   bool WillIncrement =
6450       UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
6451 
6452   // Check if the constant operand can be safely incremented/decremented
6453   // without overflowing/underflowing.
6454   auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
6455     return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
6456   };
6457 
6458   Constant *SafeReplacementConstant = nullptr;
6459   if (auto *CI = dyn_cast<ConstantInt>(C)) {
6460     // Bail out if the constant can't be safely incremented/decremented.
6461     if (!ConstantIsOk(CI))
6462       return std::nullopt;
6463   } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
6464     unsigned NumElts = FVTy->getNumElements();
6465     for (unsigned i = 0; i != NumElts; ++i) {
6466       Constant *Elt = C->getAggregateElement(i);
6467       if (!Elt)
6468         return std::nullopt;
6469 
6470       if (isa<UndefValue>(Elt))
6471         continue;
6472 
6473       // Bail out if we can't determine if this constant is min/max or if we
6474       // know that this constant is min/max.
6475       auto *CI = dyn_cast<ConstantInt>(Elt);
6476       if (!CI || !ConstantIsOk(CI))
6477         return std::nullopt;
6478 
6479       if (!SafeReplacementConstant)
6480         SafeReplacementConstant = CI;
6481     }
6482   } else {
6483     // ConstantExpr?
6484     return std::nullopt;
6485   }
6486 
6487   // It may not be safe to change a compare predicate in the presence of
6488   // undefined elements, so replace those elements with the first safe constant
6489   // that we found.
6490   // TODO: in case of poison, it is safe; let's replace undefs only.
6491   if (C->containsUndefOrPoisonElement()) {
6492     assert(SafeReplacementConstant && "Replacement constant not set");
6493     C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
6494   }
6495 
6496   CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
6497 
6498   // Increment or decrement the constant.
6499   Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
6500   Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
6501 
6502   return std::make_pair(NewPred, NewC);
6503 }
6504 
6505 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
6506 /// it into the appropriate icmp lt or icmp gt instruction. This transform
6507 /// allows them to be folded in visitICmpInst.
6508 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
6509   ICmpInst::Predicate Pred = I.getPredicate();
6510   if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
6511       InstCombiner::isCanonicalPredicate(Pred))
6512     return nullptr;
6513 
6514   Value *Op0 = I.getOperand(0);
6515   Value *Op1 = I.getOperand(1);
6516   auto *Op1C = dyn_cast<Constant>(Op1);
6517   if (!Op1C)
6518     return nullptr;
6519 
6520   auto FlippedStrictness =
6521       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
6522   if (!FlippedStrictness)
6523     return nullptr;
6524 
6525   return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
6526 }
6527 
6528 /// If we have a comparison with a non-canonical predicate, if we can update
6529 /// all the users, invert the predicate and adjust all the users.
6530 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
6531   // Is the predicate already canonical?
6532   CmpInst::Predicate Pred = I.getPredicate();
6533   if (InstCombiner::isCanonicalPredicate(Pred))
6534     return nullptr;
6535 
6536   // Can all users be adjusted to predicate inversion?
6537   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
6538     return nullptr;
6539 
6540   // Ok, we can canonicalize comparison!
6541   // Let's first invert the comparison's predicate.
6542   I.setPredicate(CmpInst::getInversePredicate(Pred));
6543   I.setName(I.getName() + ".not");
6544 
6545   // And, adapt users.
6546   freelyInvertAllUsersOf(&I);
6547 
6548   return &I;
6549 }
6550 
6551 /// Integer compare with boolean values can always be turned into bitwise ops.
6552 static Instruction *canonicalizeICmpBool(ICmpInst &I,
6553                                          InstCombiner::BuilderTy &Builder) {
6554   Value *A = I.getOperand(0), *B = I.getOperand(1);
6555   assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
6556 
6557   // A boolean compared to true/false can be simplified to Op0/true/false in
6558   // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
6559   // Cases not handled by InstSimplify are always 'not' of Op0.
6560   if (match(B, m_Zero())) {
6561     switch (I.getPredicate()) {
6562       case CmpInst::ICMP_EQ:  // A ==   0 -> !A
6563       case CmpInst::ICMP_ULE: // A <=u  0 -> !A
6564       case CmpInst::ICMP_SGE: // A >=s  0 -> !A
6565         return BinaryOperator::CreateNot(A);
6566       default:
6567         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6568     }
6569   } else if (match(B, m_One())) {
6570     switch (I.getPredicate()) {
6571       case CmpInst::ICMP_NE:  // A !=  1 -> !A
6572       case CmpInst::ICMP_ULT: // A <u  1 -> !A
6573       case CmpInst::ICMP_SGT: // A >s -1 -> !A
6574         return BinaryOperator::CreateNot(A);
6575       default:
6576         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6577     }
6578   }
6579 
6580   switch (I.getPredicate()) {
6581   default:
6582     llvm_unreachable("Invalid icmp instruction!");
6583   case ICmpInst::ICMP_EQ:
6584     // icmp eq i1 A, B -> ~(A ^ B)
6585     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
6586 
6587   case ICmpInst::ICMP_NE:
6588     // icmp ne i1 A, B -> A ^ B
6589     return BinaryOperator::CreateXor(A, B);
6590 
6591   case ICmpInst::ICMP_UGT:
6592     // icmp ugt -> icmp ult
6593     std::swap(A, B);
6594     [[fallthrough]];
6595   case ICmpInst::ICMP_ULT:
6596     // icmp ult i1 A, B -> ~A & B
6597     return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
6598 
6599   case ICmpInst::ICMP_SGT:
6600     // icmp sgt -> icmp slt
6601     std::swap(A, B);
6602     [[fallthrough]];
6603   case ICmpInst::ICMP_SLT:
6604     // icmp slt i1 A, B -> A & ~B
6605     return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
6606 
6607   case ICmpInst::ICMP_UGE:
6608     // icmp uge -> icmp ule
6609     std::swap(A, B);
6610     [[fallthrough]];
6611   case ICmpInst::ICMP_ULE:
6612     // icmp ule i1 A, B -> ~A | B
6613     return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
6614 
6615   case ICmpInst::ICMP_SGE:
6616     // icmp sge -> icmp sle
6617     std::swap(A, B);
6618     [[fallthrough]];
6619   case ICmpInst::ICMP_SLE:
6620     // icmp sle i1 A, B -> A | ~B
6621     return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
6622   }
6623 }
6624 
6625 // Transform pattern like:
6626 //   (1 << Y) u<= X  or  ~(-1 << Y) u<  X  or  ((1 << Y)+(-1)) u<  X
6627 //   (1 << Y) u>  X  or  ~(-1 << Y) u>= X  or  ((1 << Y)+(-1)) u>= X
6628 // Into:
6629 //   (X l>> Y) != 0
6630 //   (X l>> Y) == 0
6631 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
6632                                             InstCombiner::BuilderTy &Builder) {
6633   ICmpInst::Predicate Pred, NewPred;
6634   Value *X, *Y;
6635   if (match(&Cmp,
6636             m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
6637     switch (Pred) {
6638     case ICmpInst::ICMP_ULE:
6639       NewPred = ICmpInst::ICMP_NE;
6640       break;
6641     case ICmpInst::ICMP_UGT:
6642       NewPred = ICmpInst::ICMP_EQ;
6643       break;
6644     default:
6645       return nullptr;
6646     }
6647   } else if (match(&Cmp, m_c_ICmp(Pred,
6648                                   m_OneUse(m_CombineOr(
6649                                       m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
6650                                       m_Add(m_Shl(m_One(), m_Value(Y)),
6651                                             m_AllOnes()))),
6652                                   m_Value(X)))) {
6653     // The variant with 'add' is not canonical, (the variant with 'not' is)
6654     // we only get it because it has extra uses, and can't be canonicalized,
6655 
6656     switch (Pred) {
6657     case ICmpInst::ICMP_ULT:
6658       NewPred = ICmpInst::ICMP_NE;
6659       break;
6660     case ICmpInst::ICMP_UGE:
6661       NewPred = ICmpInst::ICMP_EQ;
6662       break;
6663     default:
6664       return nullptr;
6665     }
6666   } else
6667     return nullptr;
6668 
6669   Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
6670   Constant *Zero = Constant::getNullValue(NewX->getType());
6671   return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
6672 }
6673 
6674 static Instruction *foldVectorCmp(CmpInst &Cmp,
6675                                   InstCombiner::BuilderTy &Builder) {
6676   const CmpInst::Predicate Pred = Cmp.getPredicate();
6677   Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
6678   Value *V1, *V2;
6679 
6680   auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
6681     Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
6682     if (auto *I = dyn_cast<Instruction>(V))
6683       I->copyIRFlags(&Cmp);
6684     Module *M = Cmp.getModule();
6685     Function *F = Intrinsic::getDeclaration(
6686         M, Intrinsic::experimental_vector_reverse, V->getType());
6687     return CallInst::Create(F, V);
6688   };
6689 
6690   if (match(LHS, m_VecReverse(m_Value(V1)))) {
6691     // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
6692     if (match(RHS, m_VecReverse(m_Value(V2))) &&
6693         (LHS->hasOneUse() || RHS->hasOneUse()))
6694       return createCmpReverse(Pred, V1, V2);
6695 
6696     // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
6697     if (LHS->hasOneUse() && isSplatValue(RHS))
6698       return createCmpReverse(Pred, V1, RHS);
6699   }
6700   // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
6701   else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
6702     return createCmpReverse(Pred, LHS, V2);
6703 
6704   ArrayRef<int> M;
6705   if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
6706     return nullptr;
6707 
6708   // If both arguments of the cmp are shuffles that use the same mask and
6709   // shuffle within a single vector, move the shuffle after the cmp:
6710   // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
6711   Type *V1Ty = V1->getType();
6712   if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
6713       V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
6714     Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
6715     return new ShuffleVectorInst(NewCmp, M);
6716   }
6717 
6718   // Try to canonicalize compare with splatted operand and splat constant.
6719   // TODO: We could generalize this for more than splats. See/use the code in
6720   //       InstCombiner::foldVectorBinop().
6721   Constant *C;
6722   if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
6723     return nullptr;
6724 
6725   // Length-changing splats are ok, so adjust the constants as needed:
6726   // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
6727   Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true);
6728   int MaskSplatIndex;
6729   if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) {
6730     // We allow undefs in matching, but this transform removes those for safety.
6731     // Demanded elements analysis should be able to recover some/all of that.
6732     C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
6733                                  ScalarC);
6734     SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
6735     Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
6736     return new ShuffleVectorInst(NewCmp, NewM);
6737   }
6738 
6739   return nullptr;
6740 }
6741 
6742 // extract(uadd.with.overflow(A, B), 0) ult A
6743 //  -> extract(uadd.with.overflow(A, B), 1)
6744 static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
6745   CmpInst::Predicate Pred = I.getPredicate();
6746   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6747 
6748   Value *UAddOv;
6749   Value *A, *B;
6750   auto UAddOvResultPat = m_ExtractValue<0>(
6751       m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
6752   if (match(Op0, UAddOvResultPat) &&
6753       ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
6754        (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
6755         (match(A, m_One()) || match(B, m_One()))) ||
6756        (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
6757         (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
6758     // extract(uadd.with.overflow(A, B), 0) < A
6759     // extract(uadd.with.overflow(A, 1), 0) == 0
6760     // extract(uadd.with.overflow(A, -1), 0) != -1
6761     UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
6762   else if (match(Op1, UAddOvResultPat) &&
6763            Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))
6764     // A > extract(uadd.with.overflow(A, B), 0)
6765     UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
6766   else
6767     return nullptr;
6768 
6769   return ExtractValueInst::Create(UAddOv, 1);
6770 }
6771 
6772 static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
6773   if (!I.getOperand(0)->getType()->isPointerTy() ||
6774       NullPointerIsDefined(
6775           I.getParent()->getParent(),
6776           I.getOperand(0)->getType()->getPointerAddressSpace())) {
6777     return nullptr;
6778   }
6779   Instruction *Op;
6780   if (match(I.getOperand(0), m_Instruction(Op)) &&
6781       match(I.getOperand(1), m_Zero()) &&
6782       Op->isLaunderOrStripInvariantGroup()) {
6783     return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
6784                             Op->getOperand(0), I.getOperand(1));
6785   }
6786   return nullptr;
6787 }
6788 
6789 /// This function folds patterns produced by lowering of reduce idioms, such as
6790 /// llvm.vector.reduce.and which are lowered into instruction chains. This code
6791 /// attempts to generate fewer number of scalar comparisons instead of vector
6792 /// comparisons when possible.
6793 static Instruction *foldReductionIdiom(ICmpInst &I,
6794                                        InstCombiner::BuilderTy &Builder,
6795                                        const DataLayout &DL) {
6796   if (I.getType()->isVectorTy())
6797     return nullptr;
6798   ICmpInst::Predicate OuterPred, InnerPred;
6799   Value *LHS, *RHS;
6800 
6801   // Match lowering of @llvm.vector.reduce.and. Turn
6802   ///   %vec_ne = icmp ne <8 x i8> %lhs, %rhs
6803   ///   %scalar_ne = bitcast <8 x i1> %vec_ne to i8
6804   ///   %res = icmp <pred> i8 %scalar_ne, 0
6805   ///
6806   /// into
6807   ///
6808   ///   %lhs.scalar = bitcast <8 x i8> %lhs to i64
6809   ///   %rhs.scalar = bitcast <8 x i8> %rhs to i64
6810   ///   %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
6811   ///
6812   /// for <pred> in {ne, eq}.
6813   if (!match(&I, m_ICmp(OuterPred,
6814                         m_OneUse(m_BitCast(m_OneUse(
6815                             m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
6816                         m_Zero())))
6817     return nullptr;
6818   auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
6819   if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
6820     return nullptr;
6821   unsigned NumBits =
6822       LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
6823   // TODO: Relax this to "not wider than max legal integer type"?
6824   if (!DL.isLegalInteger(NumBits))
6825     return nullptr;
6826 
6827   if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
6828     auto *ScalarTy = Builder.getIntNTy(NumBits);
6829     LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
6830     RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
6831     return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
6832                             I.getName());
6833   }
6834 
6835   return nullptr;
6836 }
6837 
6838 // This helper will be called with icmp operands in both orders.
6839 Instruction *InstCombinerImpl::foldICmpCommutative(ICmpInst::Predicate Pred,
6840                                                    Value *Op0, Value *Op1,
6841                                                    ICmpInst &CxtI) {
6842   // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
6843   if (auto *GEP = dyn_cast<GEPOperator>(Op0))
6844     if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
6845       return NI;
6846 
6847   if (auto *SI = dyn_cast<SelectInst>(Op0))
6848     if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
6849       return NI;
6850 
6851   if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0))
6852     if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
6853       return Res;
6854 
6855   {
6856     Value *X;
6857     const APInt *C;
6858     // icmp X+Cst, X
6859     if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
6860       return foldICmpAddOpConst(X, *C, Pred);
6861   }
6862 
6863   return nullptr;
6864 }
6865 
6866 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
6867   bool Changed = false;
6868   const SimplifyQuery Q = SQ.getWithInstruction(&I);
6869   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6870   unsigned Op0Cplxity = getComplexity(Op0);
6871   unsigned Op1Cplxity = getComplexity(Op1);
6872 
6873   /// Orders the operands of the compare so that they are listed from most
6874   /// complex to least complex.  This puts constants before unary operators,
6875   /// before binary operators.
6876   if (Op0Cplxity < Op1Cplxity) {
6877     I.swapOperands();
6878     std::swap(Op0, Op1);
6879     Changed = true;
6880   }
6881 
6882   if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
6883     return replaceInstUsesWith(I, V);
6884 
6885   // Comparing -val or val with non-zero is the same as just comparing val
6886   // ie, abs(val) != 0 -> val != 0
6887   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
6888     Value *Cond, *SelectTrue, *SelectFalse;
6889     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
6890                             m_Value(SelectFalse)))) {
6891       if (Value *V = dyn_castNegVal(SelectTrue)) {
6892         if (V == SelectFalse)
6893           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6894       }
6895       else if (Value *V = dyn_castNegVal(SelectFalse)) {
6896         if (V == SelectTrue)
6897           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6898       }
6899     }
6900   }
6901 
6902   if (Op0->getType()->isIntOrIntVectorTy(1))
6903     if (Instruction *Res = canonicalizeICmpBool(I, Builder))
6904       return Res;
6905 
6906   if (Instruction *Res = canonicalizeCmpWithConstant(I))
6907     return Res;
6908 
6909   if (Instruction *Res = canonicalizeICmpPredicate(I))
6910     return Res;
6911 
6912   if (Instruction *Res = foldICmpWithConstant(I))
6913     return Res;
6914 
6915   if (Instruction *Res = foldICmpWithDominatingICmp(I))
6916     return Res;
6917 
6918   if (Instruction *Res = foldICmpUsingBoolRange(I))
6919     return Res;
6920 
6921   if (Instruction *Res = foldICmpUsingKnownBits(I))
6922     return Res;
6923 
6924   if (Instruction *Res = foldICmpTruncWithTruncOrExt(I, Q))
6925     return Res;
6926 
6927   // Test if the ICmpInst instruction is used exclusively by a select as
6928   // part of a minimum or maximum operation. If so, refrain from doing
6929   // any other folding. This helps out other analyses which understand
6930   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6931   // and CodeGen. And in this case, at least one of the comparison
6932   // operands has at least one user besides the compare (the select),
6933   // which would often largely negate the benefit of folding anyway.
6934   //
6935   // Do the same for the other patterns recognized by matchSelectPattern.
6936   if (I.hasOneUse())
6937     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
6938       Value *A, *B;
6939       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
6940       if (SPR.Flavor != SPF_UNKNOWN)
6941         return nullptr;
6942     }
6943 
6944   // Do this after checking for min/max to prevent infinite looping.
6945   if (Instruction *Res = foldICmpWithZero(I))
6946     return Res;
6947 
6948   // FIXME: We only do this after checking for min/max to prevent infinite
6949   // looping caused by a reverse canonicalization of these patterns for min/max.
6950   // FIXME: The organization of folds is a mess. These would naturally go into
6951   // canonicalizeCmpWithConstant(), but we can't move all of the above folds
6952   // down here after the min/max restriction.
6953   ICmpInst::Predicate Pred = I.getPredicate();
6954   const APInt *C;
6955   if (match(Op1, m_APInt(C))) {
6956     // For i32: x >u 2147483647 -> x <s 0  -> true if sign bit set
6957     if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
6958       Constant *Zero = Constant::getNullValue(Op0->getType());
6959       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
6960     }
6961 
6962     // For i32: x <u 2147483648 -> x >s -1  -> true if sign bit clear
6963     if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
6964       Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
6965       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
6966     }
6967   }
6968 
6969   // The folds in here may rely on wrapping flags and special constants, so
6970   // they can break up min/max idioms in some cases but not seemingly similar
6971   // patterns.
6972   // FIXME: It may be possible to enhance select folding to make this
6973   //        unnecessary. It may also be moot if we canonicalize to min/max
6974   //        intrinsics.
6975   if (Instruction *Res = foldICmpBinOp(I, Q))
6976     return Res;
6977 
6978   if (Instruction *Res = foldICmpInstWithConstant(I))
6979     return Res;
6980 
6981   // Try to match comparison as a sign bit test. Intentionally do this after
6982   // foldICmpInstWithConstant() to potentially let other folds to happen first.
6983   if (Instruction *New = foldSignBitTest(I))
6984     return New;
6985 
6986   if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
6987     return Res;
6988 
6989   if (Instruction *Res = foldICmpCommutative(I.getPredicate(), Op0, Op1, I))
6990     return Res;
6991   if (Instruction *Res =
6992           foldICmpCommutative(I.getSwappedPredicate(), Op1, Op0, I))
6993     return Res;
6994 
6995   // In case of a comparison with two select instructions having the same
6996   // condition, check whether one of the resulting branches can be simplified.
6997   // If so, just compare the other branch and select the appropriate result.
6998   // For example:
6999   //   %tmp1 = select i1 %cmp, i32 %y, i32 %x
7000   //   %tmp2 = select i1 %cmp, i32 %z, i32 %x
7001   //   %cmp2 = icmp slt i32 %tmp2, %tmp1
7002   // The icmp will result false for the false value of selects and the result
7003   // will depend upon the comparison of true values of selects if %cmp is
7004   // true. Thus, transform this into:
7005   //   %cmp = icmp slt i32 %y, %z
7006   //   %sel = select i1 %cond, i1 %cmp, i1 false
7007   // This handles similar cases to transform.
7008   {
7009     Value *Cond, *A, *B, *C, *D;
7010     if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
7011         match(Op1, m_Select(m_Specific(Cond), m_Value(C), m_Value(D))) &&
7012         (Op0->hasOneUse() || Op1->hasOneUse())) {
7013       // Check whether comparison of TrueValues can be simplified
7014       if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
7015         Value *NewICMP = Builder.CreateICmp(Pred, B, D);
7016         return SelectInst::Create(Cond, Res, NewICMP);
7017       }
7018       // Check whether comparison of FalseValues can be simplified
7019       if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
7020         Value *NewICMP = Builder.CreateICmp(Pred, A, C);
7021         return SelectInst::Create(Cond, NewICMP, Res);
7022       }
7023     }
7024   }
7025 
7026   // Try to optimize equality comparisons against alloca-based pointers.
7027   if (Op0->getType()->isPointerTy() && I.isEquality()) {
7028     assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
7029     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
7030       if (foldAllocaCmp(Alloca))
7031         return nullptr;
7032     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
7033       if (foldAllocaCmp(Alloca))
7034         return nullptr;
7035   }
7036 
7037   if (Instruction *Res = foldICmpBitCast(I))
7038     return Res;
7039 
7040   // TODO: Hoist this above the min/max bailout.
7041   if (Instruction *R = foldICmpWithCastOp(I))
7042     return R;
7043 
7044   {
7045     Value *X, *Y;
7046     // Transform (X & ~Y) == 0 --> (X & Y) != 0
7047     // and       (X & ~Y) != 0 --> (X & Y) == 0
7048     // if A is a power of 2.
7049     if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
7050         match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, 0, &I) &&
7051         I.isEquality())
7052       return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
7053                           Op1);
7054 
7055     // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7056     if (Op0->getType()->isIntOrIntVectorTy()) {
7057       bool ConsumesOp0, ConsumesOp1;
7058       if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
7059           isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
7060           (ConsumesOp0 || ConsumesOp1)) {
7061         Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
7062         Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
7063         assert(InvOp0 && InvOp1 &&
7064                "Mismatch between isFreeToInvert and getFreelyInverted");
7065         return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7066       }
7067     }
7068 
7069     Instruction *AddI = nullptr;
7070     if (match(&I, m_UAddWithOverflow(m_Value(X), m_Value(Y),
7071                                      m_Instruction(AddI))) &&
7072         isa<IntegerType>(X->getType())) {
7073       Value *Result;
7074       Constant *Overflow;
7075       // m_UAddWithOverflow can match patterns that do not include  an explicit
7076       // "add" instruction, so check the opcode of the matched op.
7077       if (AddI->getOpcode() == Instruction::Add &&
7078           OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
7079                                 Result, Overflow)) {
7080         replaceInstUsesWith(*AddI, Result);
7081         eraseInstFromFunction(*AddI);
7082         return replaceInstUsesWith(I, Overflow);
7083       }
7084     }
7085 
7086     // (zext X) * (zext Y)  --> llvm.umul.with.overflow.
7087     if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
7088         match(Op1, m_APInt(C))) {
7089       if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
7090         return R;
7091     }
7092 
7093     // Signbit test folds
7094     // Fold (X u>> BitWidth - 1 Pred ZExt(i1))  -->  X s< 0 Pred i1
7095     // Fold (X s>> BitWidth - 1 Pred SExt(i1))  -->  X s< 0 Pred i1
7096     Instruction *ExtI;
7097     if ((I.isUnsigned() || I.isEquality()) &&
7098         match(Op1,
7099               m_CombineAnd(m_Instruction(ExtI), m_ZExtOrSExt(m_Value(Y)))) &&
7100         Y->getType()->getScalarSizeInBits() == 1 &&
7101         (Op0->hasOneUse() || Op1->hasOneUse())) {
7102       unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
7103       Instruction *ShiftI;
7104       if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
7105                                   m_Shr(m_Value(X), m_SpecificIntAllowUndef(
7106                                                         OpWidth - 1))))) {
7107         unsigned ExtOpc = ExtI->getOpcode();
7108         unsigned ShiftOpc = ShiftI->getOpcode();
7109         if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
7110             (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
7111           Value *SLTZero =
7112               Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
7113           Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
7114           return replaceInstUsesWith(I, Cmp);
7115         }
7116       }
7117     }
7118   }
7119 
7120   if (Instruction *Res = foldICmpEquality(I))
7121     return Res;
7122 
7123   if (Instruction *Res = foldICmpPow2Test(I, Builder))
7124     return Res;
7125 
7126   if (Instruction *Res = foldICmpOfUAddOv(I))
7127     return Res;
7128 
7129   // The 'cmpxchg' instruction returns an aggregate containing the old value and
7130   // an i1 which indicates whether or not we successfully did the swap.
7131   //
7132   // Replace comparisons between the old value and the expected value with the
7133   // indicator that 'cmpxchg' returns.
7134   //
7135   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
7136   // spuriously fail.  In those cases, the old value may equal the expected
7137   // value but it is possible for the swap to not occur.
7138   if (I.getPredicate() == ICmpInst::ICMP_EQ)
7139     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
7140       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
7141         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
7142             !ACXI->isWeak())
7143           return ExtractValueInst::Create(ACXI, 1);
7144 
7145   if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
7146     return Res;
7147 
7148   if (I.getType()->isVectorTy())
7149     if (Instruction *Res = foldVectorCmp(I, Builder))
7150       return Res;
7151 
7152   if (Instruction *Res = foldICmpInvariantGroup(I))
7153     return Res;
7154 
7155   if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
7156     return Res;
7157 
7158   return Changed ? &I : nullptr;
7159 }
7160 
7161 /// Fold fcmp ([us]itofp x, cst) if possible.
7162 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
7163                                                     Instruction *LHSI,
7164                                                     Constant *RHSC) {
7165   if (!isa<ConstantFP>(RHSC)) return nullptr;
7166   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
7167 
7168   // Get the width of the mantissa.  We don't want to hack on conversions that
7169   // might lose information from the integer, e.g. "i64 -> float"
7170   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
7171   if (MantissaWidth == -1) return nullptr;  // Unknown.
7172 
7173   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
7174 
7175   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
7176 
7177   if (I.isEquality()) {
7178     FCmpInst::Predicate P = I.getPredicate();
7179     bool IsExact = false;
7180     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
7181     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
7182 
7183     // If the floating point constant isn't an integer value, we know if we will
7184     // ever compare equal / not equal to it.
7185     if (!IsExact) {
7186       // TODO: Can never be -0.0 and other non-representable values
7187       APFloat RHSRoundInt(RHS);
7188       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
7189       if (RHS != RHSRoundInt) {
7190         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
7191           return replaceInstUsesWith(I, Builder.getFalse());
7192 
7193         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
7194         return replaceInstUsesWith(I, Builder.getTrue());
7195       }
7196     }
7197 
7198     // TODO: If the constant is exactly representable, is it always OK to do
7199     // equality compares as integer?
7200   }
7201 
7202   // Check to see that the input is converted from an integer type that is small
7203   // enough that preserves all bits.  TODO: check here for "known" sign bits.
7204   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
7205   unsigned InputSize = IntTy->getScalarSizeInBits();
7206 
7207   // Following test does NOT adjust InputSize downwards for signed inputs,
7208   // because the most negative value still requires all the mantissa bits
7209   // to distinguish it from one less than that value.
7210   if ((int)InputSize > MantissaWidth) {
7211     // Conversion would lose accuracy. Check if loss can impact comparison.
7212     int Exp = ilogb(RHS);
7213     if (Exp == APFloat::IEK_Inf) {
7214       int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
7215       if (MaxExponent < (int)InputSize - !LHSUnsigned)
7216         // Conversion could create infinity.
7217         return nullptr;
7218     } else {
7219       // Note that if RHS is zero or NaN, then Exp is negative
7220       // and first condition is trivially false.
7221       if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
7222         // Conversion could affect comparison.
7223         return nullptr;
7224     }
7225   }
7226 
7227   // Otherwise, we can potentially simplify the comparison.  We know that it
7228   // will always come through as an integer value and we know the constant is
7229   // not a NAN (it would have been previously simplified).
7230   assert(!RHS.isNaN() && "NaN comparison not already folded!");
7231 
7232   ICmpInst::Predicate Pred;
7233   switch (I.getPredicate()) {
7234   default: llvm_unreachable("Unexpected predicate!");
7235   case FCmpInst::FCMP_UEQ:
7236   case FCmpInst::FCMP_OEQ:
7237     Pred = ICmpInst::ICMP_EQ;
7238     break;
7239   case FCmpInst::FCMP_UGT:
7240   case FCmpInst::FCMP_OGT:
7241     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
7242     break;
7243   case FCmpInst::FCMP_UGE:
7244   case FCmpInst::FCMP_OGE:
7245     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
7246     break;
7247   case FCmpInst::FCMP_ULT:
7248   case FCmpInst::FCMP_OLT:
7249     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
7250     break;
7251   case FCmpInst::FCMP_ULE:
7252   case FCmpInst::FCMP_OLE:
7253     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
7254     break;
7255   case FCmpInst::FCMP_UNE:
7256   case FCmpInst::FCMP_ONE:
7257     Pred = ICmpInst::ICMP_NE;
7258     break;
7259   case FCmpInst::FCMP_ORD:
7260     return replaceInstUsesWith(I, Builder.getTrue());
7261   case FCmpInst::FCMP_UNO:
7262     return replaceInstUsesWith(I, Builder.getFalse());
7263   }
7264 
7265   // Now we know that the APFloat is a normal number, zero or inf.
7266 
7267   // See if the FP constant is too large for the integer.  For example,
7268   // comparing an i8 to 300.0.
7269   unsigned IntWidth = IntTy->getScalarSizeInBits();
7270 
7271   if (!LHSUnsigned) {
7272     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
7273     // and large values.
7274     APFloat SMax(RHS.getSemantics());
7275     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
7276                           APFloat::rmNearestTiesToEven);
7277     if (SMax < RHS) { // smax < 13123.0
7278       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
7279           Pred == ICmpInst::ICMP_SLE)
7280         return replaceInstUsesWith(I, Builder.getTrue());
7281       return replaceInstUsesWith(I, Builder.getFalse());
7282     }
7283   } else {
7284     // If the RHS value is > UnsignedMax, fold the comparison. This handles
7285     // +INF and large values.
7286     APFloat UMax(RHS.getSemantics());
7287     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
7288                           APFloat::rmNearestTiesToEven);
7289     if (UMax < RHS) { // umax < 13123.0
7290       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
7291           Pred == ICmpInst::ICMP_ULE)
7292         return replaceInstUsesWith(I, Builder.getTrue());
7293       return replaceInstUsesWith(I, Builder.getFalse());
7294     }
7295   }
7296 
7297   if (!LHSUnsigned) {
7298     // See if the RHS value is < SignedMin.
7299     APFloat SMin(RHS.getSemantics());
7300     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
7301                           APFloat::rmNearestTiesToEven);
7302     if (SMin > RHS) { // smin > 12312.0
7303       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
7304           Pred == ICmpInst::ICMP_SGE)
7305         return replaceInstUsesWith(I, Builder.getTrue());
7306       return replaceInstUsesWith(I, Builder.getFalse());
7307     }
7308   } else {
7309     // See if the RHS value is < UnsignedMin.
7310     APFloat UMin(RHS.getSemantics());
7311     UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
7312                           APFloat::rmNearestTiesToEven);
7313     if (UMin > RHS) { // umin > 12312.0
7314       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
7315           Pred == ICmpInst::ICMP_UGE)
7316         return replaceInstUsesWith(I, Builder.getTrue());
7317       return replaceInstUsesWith(I, Builder.getFalse());
7318     }
7319   }
7320 
7321   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
7322   // [0, UMAX], but it may still be fractional. Check whether this is the case
7323   // using the IsExact flag.
7324   // Don't do this for zero, because -0.0 is not fractional.
7325   APSInt RHSInt(IntWidth, LHSUnsigned);
7326   bool IsExact;
7327   RHS.convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
7328   if (!RHS.isZero()) {
7329     if (!IsExact) {
7330       // If we had a comparison against a fractional value, we have to adjust
7331       // the compare predicate and sometimes the value.  RHSC is rounded towards
7332       // zero at this point.
7333       switch (Pred) {
7334       default: llvm_unreachable("Unexpected integer comparison!");
7335       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
7336         return replaceInstUsesWith(I, Builder.getTrue());
7337       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
7338         return replaceInstUsesWith(I, Builder.getFalse());
7339       case ICmpInst::ICMP_ULE:
7340         // (float)int <= 4.4   --> int <= 4
7341         // (float)int <= -4.4  --> false
7342         if (RHS.isNegative())
7343           return replaceInstUsesWith(I, Builder.getFalse());
7344         break;
7345       case ICmpInst::ICMP_SLE:
7346         // (float)int <= 4.4   --> int <= 4
7347         // (float)int <= -4.4  --> int < -4
7348         if (RHS.isNegative())
7349           Pred = ICmpInst::ICMP_SLT;
7350         break;
7351       case ICmpInst::ICMP_ULT:
7352         // (float)int < -4.4   --> false
7353         // (float)int < 4.4    --> int <= 4
7354         if (RHS.isNegative())
7355           return replaceInstUsesWith(I, Builder.getFalse());
7356         Pred = ICmpInst::ICMP_ULE;
7357         break;
7358       case ICmpInst::ICMP_SLT:
7359         // (float)int < -4.4   --> int < -4
7360         // (float)int < 4.4    --> int <= 4
7361         if (!RHS.isNegative())
7362           Pred = ICmpInst::ICMP_SLE;
7363         break;
7364       case ICmpInst::ICMP_UGT:
7365         // (float)int > 4.4    --> int > 4
7366         // (float)int > -4.4   --> true
7367         if (RHS.isNegative())
7368           return replaceInstUsesWith(I, Builder.getTrue());
7369         break;
7370       case ICmpInst::ICMP_SGT:
7371         // (float)int > 4.4    --> int > 4
7372         // (float)int > -4.4   --> int >= -4
7373         if (RHS.isNegative())
7374           Pred = ICmpInst::ICMP_SGE;
7375         break;
7376       case ICmpInst::ICMP_UGE:
7377         // (float)int >= -4.4   --> true
7378         // (float)int >= 4.4    --> int > 4
7379         if (RHS.isNegative())
7380           return replaceInstUsesWith(I, Builder.getTrue());
7381         Pred = ICmpInst::ICMP_UGT;
7382         break;
7383       case ICmpInst::ICMP_SGE:
7384         // (float)int >= -4.4   --> int >= -4
7385         // (float)int >= 4.4    --> int > 4
7386         if (!RHS.isNegative())
7387           Pred = ICmpInst::ICMP_SGT;
7388         break;
7389       }
7390     }
7391   }
7392 
7393   // Lower this FP comparison into an appropriate integer version of the
7394   // comparison.
7395   return new ICmpInst(Pred, LHSI->getOperand(0), Builder.getInt(RHSInt));
7396 }
7397 
7398 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
7399 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
7400                                               Constant *RHSC) {
7401   // When C is not 0.0 and infinities are not allowed:
7402   // (C / X) < 0.0 is a sign-bit test of X
7403   // (C / X) < 0.0 --> X < 0.0 (if C is positive)
7404   // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
7405   //
7406   // Proof:
7407   // Multiply (C / X) < 0.0 by X * X / C.
7408   // - X is non zero, if it is the flag 'ninf' is violated.
7409   // - C defines the sign of X * X * C. Thus it also defines whether to swap
7410   //   the predicate. C is also non zero by definition.
7411   //
7412   // Thus X * X / C is non zero and the transformation is valid. [qed]
7413 
7414   FCmpInst::Predicate Pred = I.getPredicate();
7415 
7416   // Check that predicates are valid.
7417   if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
7418       (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
7419     return nullptr;
7420 
7421   // Check that RHS operand is zero.
7422   if (!match(RHSC, m_AnyZeroFP()))
7423     return nullptr;
7424 
7425   // Check fastmath flags ('ninf').
7426   if (!LHSI->hasNoInfs() || !I.hasNoInfs())
7427     return nullptr;
7428 
7429   // Check the properties of the dividend. It must not be zero to avoid a
7430   // division by zero (see Proof).
7431   const APFloat *C;
7432   if (!match(LHSI->getOperand(0), m_APFloat(C)))
7433     return nullptr;
7434 
7435   if (C->isZero())
7436     return nullptr;
7437 
7438   // Get swapped predicate if necessary.
7439   if (C->isNegative())
7440     Pred = I.getSwappedPredicate();
7441 
7442   return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
7443 }
7444 
7445 /// Optimize fabs(X) compared with zero.
7446 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
7447   Value *X;
7448   if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
7449     return nullptr;
7450 
7451   const APFloat *C;
7452   if (!match(I.getOperand(1), m_APFloat(C)))
7453     return nullptr;
7454 
7455   if (!C->isPosZero()) {
7456     if (!C->isSmallestNormalized())
7457       return nullptr;
7458 
7459     const Function *F = I.getFunction();
7460     DenormalMode Mode = F->getDenormalMode(C->getSemantics());
7461     if (Mode.Input == DenormalMode::PreserveSign ||
7462         Mode.Input == DenormalMode::PositiveZero) {
7463 
7464       auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7465         Constant *Zero = ConstantFP::getZero(X->getType());
7466         return new FCmpInst(P, X, Zero, "", I);
7467       };
7468 
7469       switch (I.getPredicate()) {
7470       case FCmpInst::FCMP_OLT:
7471         // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
7472         return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
7473       case FCmpInst::FCMP_UGE:
7474         // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
7475         return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
7476       case FCmpInst::FCMP_OGE:
7477         // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
7478         return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
7479       case FCmpInst::FCMP_ULT:
7480         // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
7481         return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
7482       default:
7483         break;
7484       }
7485     }
7486 
7487     return nullptr;
7488   }
7489 
7490   auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7491     I->setPredicate(P);
7492     return IC.replaceOperand(*I, 0, X);
7493   };
7494 
7495   switch (I.getPredicate()) {
7496   case FCmpInst::FCMP_UGE:
7497   case FCmpInst::FCMP_OLT:
7498     // fabs(X) >= 0.0 --> true
7499     // fabs(X) <  0.0 --> false
7500     llvm_unreachable("fcmp should have simplified");
7501 
7502   case FCmpInst::FCMP_OGT:
7503     // fabs(X) > 0.0 --> X != 0.0
7504     return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
7505 
7506   case FCmpInst::FCMP_UGT:
7507     // fabs(X) u> 0.0 --> X u!= 0.0
7508     return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
7509 
7510   case FCmpInst::FCMP_OLE:
7511     // fabs(X) <= 0.0 --> X == 0.0
7512     return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
7513 
7514   case FCmpInst::FCMP_ULE:
7515     // fabs(X) u<= 0.0 --> X u== 0.0
7516     return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
7517 
7518   case FCmpInst::FCMP_OGE:
7519     // fabs(X) >= 0.0 --> !isnan(X)
7520     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7521     return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
7522 
7523   case FCmpInst::FCMP_ULT:
7524     // fabs(X) u< 0.0 --> isnan(X)
7525     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7526     return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
7527 
7528   case FCmpInst::FCMP_OEQ:
7529   case FCmpInst::FCMP_UEQ:
7530   case FCmpInst::FCMP_ONE:
7531   case FCmpInst::FCMP_UNE:
7532   case FCmpInst::FCMP_ORD:
7533   case FCmpInst::FCMP_UNO:
7534     // Look through the fabs() because it doesn't change anything but the sign.
7535     // fabs(X) == 0.0 --> X == 0.0,
7536     // fabs(X) != 0.0 --> X != 0.0
7537     // isnan(fabs(X)) --> isnan(X)
7538     // !isnan(fabs(X) --> !isnan(X)
7539     return replacePredAndOp0(&I, I.getPredicate(), X);
7540 
7541   default:
7542     return nullptr;
7543   }
7544 }
7545 
7546 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
7547   CmpInst::Predicate Pred = I.getPredicate();
7548   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7549 
7550   // Canonicalize fneg as Op1.
7551   if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
7552     std::swap(Op0, Op1);
7553     Pred = I.getSwappedPredicate();
7554   }
7555 
7556   if (!match(Op1, m_FNeg(m_Specific(Op0))))
7557     return nullptr;
7558 
7559   // Replace the negated operand with 0.0:
7560   // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
7561   Constant *Zero = ConstantFP::getZero(Op0->getType());
7562   return new FCmpInst(Pred, Op0, Zero, "", &I);
7563 }
7564 
7565 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
7566   bool Changed = false;
7567 
7568   /// Orders the operands of the compare so that they are listed from most
7569   /// complex to least complex.  This puts constants before unary operators,
7570   /// before binary operators.
7571   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
7572     I.swapOperands();
7573     Changed = true;
7574   }
7575 
7576   const CmpInst::Predicate Pred = I.getPredicate();
7577   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7578   if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
7579                                   SQ.getWithInstruction(&I)))
7580     return replaceInstUsesWith(I, V);
7581 
7582   // Simplify 'fcmp pred X, X'
7583   Type *OpType = Op0->getType();
7584   assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
7585   if (Op0 == Op1) {
7586     switch (Pred) {
7587       default: break;
7588     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
7589     case FCmpInst::FCMP_ULT:    // True if unordered or less than
7590     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
7591     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
7592       // Canonicalize these to be 'fcmp uno %X, 0.0'.
7593       I.setPredicate(FCmpInst::FCMP_UNO);
7594       I.setOperand(1, Constant::getNullValue(OpType));
7595       return &I;
7596 
7597     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
7598     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
7599     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
7600     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
7601       // Canonicalize these to be 'fcmp ord %X, 0.0'.
7602       I.setPredicate(FCmpInst::FCMP_ORD);
7603       I.setOperand(1, Constant::getNullValue(OpType));
7604       return &I;
7605     }
7606   }
7607 
7608   // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
7609   // then canonicalize the operand to 0.0.
7610   if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
7611     if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, DL, &TLI, 0,
7612                                                       &AC, &I, &DT))
7613       return replaceOperand(I, 0, ConstantFP::getZero(OpType));
7614 
7615     if (!match(Op1, m_PosZeroFP()) &&
7616         isKnownNeverNaN(Op1, DL, &TLI, 0, &AC, &I, &DT))
7617       return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7618   }
7619 
7620   // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
7621   Value *X, *Y;
7622   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
7623     return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
7624 
7625   if (Instruction *R = foldFCmpFNegCommonOp(I))
7626     return R;
7627 
7628   // Test if the FCmpInst instruction is used exclusively by a select as
7629   // part of a minimum or maximum operation. If so, refrain from doing
7630   // any other folding. This helps out other analyses which understand
7631   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7632   // and CodeGen. And in this case, at least one of the comparison
7633   // operands has at least one user besides the compare (the select),
7634   // which would often largely negate the benefit of folding anyway.
7635   if (I.hasOneUse())
7636     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7637       Value *A, *B;
7638       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
7639       if (SPR.Flavor != SPF_UNKNOWN)
7640         return nullptr;
7641     }
7642 
7643   // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
7644   // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
7645   if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
7646     return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7647 
7648   // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
7649   // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
7650   if (match(Op1, m_PosZeroFP()) &&
7651       match(Op0, m_OneUse(m_BitCast(m_Value(X)))) &&
7652       X->getType()->isVectorTy() == OpType->isVectorTy() &&
7653       X->getType()->getScalarSizeInBits() == OpType->getScalarSizeInBits()) {
7654     ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
7655     if (Pred == FCmpInst::FCMP_OEQ)
7656       IntPred = ICmpInst::ICMP_EQ;
7657     else if (Pred == FCmpInst::FCMP_UNE)
7658       IntPred = ICmpInst::ICMP_NE;
7659 
7660     if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
7661       Type *IntTy = X->getType();
7662       const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
7663       Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
7664       return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
7665     }
7666   }
7667 
7668   // Handle fcmp with instruction LHS and constant RHS.
7669   Instruction *LHSI;
7670   Constant *RHSC;
7671   if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
7672     switch (LHSI->getOpcode()) {
7673     case Instruction::PHI:
7674       if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
7675         return NV;
7676       break;
7677     case Instruction::SIToFP:
7678     case Instruction::UIToFP:
7679       if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
7680         return NV;
7681       break;
7682     case Instruction::FDiv:
7683       if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
7684         return NV;
7685       break;
7686     case Instruction::Load:
7687       if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
7688         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7689           if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
7690                   cast<LoadInst>(LHSI), GEP, GV, I))
7691             return Res;
7692       break;
7693   }
7694   }
7695 
7696   if (Instruction *R = foldFabsWithFcmpZero(I, *this))
7697     return R;
7698 
7699   if (match(Op0, m_FNeg(m_Value(X)))) {
7700     // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
7701     Constant *C;
7702     if (match(Op1, m_Constant(C)))
7703       if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
7704         return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
7705   }
7706 
7707   if (match(Op0, m_FPExt(m_Value(X)))) {
7708     // fcmp (fpext X), (fpext Y) -> fcmp X, Y
7709     if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
7710       return new FCmpInst(Pred, X, Y, "", &I);
7711 
7712     const APFloat *C;
7713     if (match(Op1, m_APFloat(C))) {
7714       const fltSemantics &FPSem =
7715           X->getType()->getScalarType()->getFltSemantics();
7716       bool Lossy;
7717       APFloat TruncC = *C;
7718       TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
7719 
7720       if (Lossy) {
7721         // X can't possibly equal the higher-precision constant, so reduce any
7722         // equality comparison.
7723         // TODO: Other predicates can be handled via getFCmpCode().
7724         switch (Pred) {
7725         case FCmpInst::FCMP_OEQ:
7726           // X is ordered and equal to an impossible constant --> false
7727           return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7728         case FCmpInst::FCMP_ONE:
7729           // X is ordered and not equal to an impossible constant --> ordered
7730           return new FCmpInst(FCmpInst::FCMP_ORD, X,
7731                               ConstantFP::getZero(X->getType()));
7732         case FCmpInst::FCMP_UEQ:
7733           // X is unordered or equal to an impossible constant --> unordered
7734           return new FCmpInst(FCmpInst::FCMP_UNO, X,
7735                               ConstantFP::getZero(X->getType()));
7736         case FCmpInst::FCMP_UNE:
7737           // X is unordered or not equal to an impossible constant --> true
7738           return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7739         default:
7740           break;
7741         }
7742       }
7743 
7744       // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
7745       // Avoid lossy conversions and denormals.
7746       // Zero is a special case that's OK to convert.
7747       APFloat Fabs = TruncC;
7748       Fabs.clearSign();
7749       if (!Lossy &&
7750           (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
7751         Constant *NewC = ConstantFP::get(X->getType(), TruncC);
7752         return new FCmpInst(Pred, X, NewC, "", &I);
7753       }
7754     }
7755   }
7756 
7757   // Convert a sign-bit test of an FP value into a cast and integer compare.
7758   // TODO: Simplify if the copysign constant is 0.0 or NaN.
7759   // TODO: Handle non-zero compare constants.
7760   // TODO: Handle other predicates.
7761   const APFloat *C;
7762   if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
7763                                                            m_Value(X)))) &&
7764       match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
7765     Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
7766     if (auto *VecTy = dyn_cast<VectorType>(OpType))
7767       IntType = VectorType::get(IntType, VecTy->getElementCount());
7768 
7769     // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
7770     if (Pred == FCmpInst::FCMP_OLT) {
7771       Value *IntX = Builder.CreateBitCast(X, IntType);
7772       return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
7773                           ConstantInt::getNullValue(IntType));
7774     }
7775   }
7776 
7777   {
7778     Value *CanonLHS = nullptr, *CanonRHS = nullptr;
7779     match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
7780     match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
7781 
7782     // (canonicalize(x) == x) => (x == x)
7783     if (CanonLHS == Op1)
7784       return new FCmpInst(Pred, Op1, Op1, "", &I);
7785 
7786     // (x == canonicalize(x)) => (x == x)
7787     if (CanonRHS == Op0)
7788       return new FCmpInst(Pred, Op0, Op0, "", &I);
7789 
7790     // (canonicalize(x) == canonicalize(y)) => (x == y)
7791     if (CanonLHS && CanonRHS)
7792       return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
7793   }
7794 
7795   if (I.getType()->isVectorTy())
7796     if (Instruction *Res = foldVectorCmp(I, Builder))
7797       return Res;
7798 
7799   return Changed ? &I : nullptr;
7800 }
7801