xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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() &&
4924       (BO0->hasOneUse() || BO1->hasOneUse()) &&
4925       BO0->getOperand(1) == BO1->getOperand(1)) {
4926     switch (BO0->getOpcode()) {
4927     default:
4928       break;
4929     case Instruction::Add:
4930     case Instruction::Sub:
4931     case Instruction::Xor: {
4932       if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4933         return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4934 
4935       const APInt *C;
4936       if (match(BO0->getOperand(1), m_APInt(C))) {
4937         // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
4938         if (C->isSignMask()) {
4939           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4940           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4941         }
4942 
4943         // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
4944         if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
4945           ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4946           NewPred = I.getSwappedPredicate(NewPred);
4947           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4948         }
4949       }
4950       break;
4951     }
4952     case Instruction::Mul: {
4953       if (!I.isEquality())
4954         break;
4955 
4956       const APInt *C;
4957       if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
4958           !C->isOne()) {
4959         // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
4960         // Mask = -1 >> count-trailing-zeros(C).
4961         if (unsigned TZs = C->countr_zero()) {
4962           Constant *Mask = ConstantInt::get(
4963               BO0->getType(),
4964               APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
4965           Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
4966           Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
4967           return new ICmpInst(Pred, And1, And2);
4968         }
4969       }
4970       break;
4971     }
4972     case Instruction::UDiv:
4973     case Instruction::LShr:
4974       if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
4975         break;
4976       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4977 
4978     case Instruction::SDiv:
4979       if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
4980           !BO0->isExact() || !BO1->isExact())
4981         break;
4982       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4983 
4984     case Instruction::AShr:
4985       if (!BO0->isExact() || !BO1->isExact())
4986         break;
4987       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4988 
4989     case Instruction::Shl: {
4990       bool NUW = Op0HasNUW && Op1HasNUW;
4991       bool NSW = Op0HasNSW && Op1HasNSW;
4992       if (!NUW && !NSW)
4993         break;
4994       if (!NSW && I.isSigned())
4995         break;
4996       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4997     }
4998     }
4999   }
5000 
5001   if (BO0) {
5002     // Transform  A & (L - 1) `ult` L --> L != 0
5003     auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5004     auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5005 
5006     if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5007       auto *Zero = Constant::getNullValue(BO0->getType());
5008       return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5009     }
5010   }
5011 
5012   // For unsigned predicates / eq / ne:
5013   // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5014   // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5015   if (!ICmpInst::isSigned(Pred)) {
5016     if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5017       return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5018                           Constant::getNullValue(Op1->getType()));
5019     else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5020       return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5021                           Constant::getNullValue(Op0->getType()), Op0);
5022   }
5023 
5024   if (Value *V = foldMultiplicationOverflowCheck(I))
5025     return replaceInstUsesWith(I, V);
5026 
5027   if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
5028     return replaceInstUsesWith(I, V);
5029 
5030   if (Instruction *R = foldICmpAndXX(I, Q, *this))
5031     return R;
5032 
5033   if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5034     return replaceInstUsesWith(I, V);
5035 
5036   if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5037     return replaceInstUsesWith(I, V);
5038 
5039   return nullptr;
5040 }
5041 
5042 /// Fold icmp Pred min|max(X, Y), Z.
5043 Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5044                                                   MinMaxIntrinsic *MinMax,
5045                                                   Value *Z,
5046                                                   ICmpInst::Predicate Pred) {
5047   Value *X = MinMax->getLHS();
5048   Value *Y = MinMax->getRHS();
5049   if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5050     return nullptr;
5051   if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5052     // Revert the transform signed pred -> unsigned pred
5053     // TODO: We can flip the signedness of predicate if both operands of icmp
5054     // are negative.
5055     if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5056         isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5057       Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5058     } else
5059       return nullptr;
5060   }
5061   SimplifyQuery Q = SQ.getWithInstruction(&I);
5062   auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5063     if (!Val)
5064       return std::nullopt;
5065     if (match(Val, m_One()))
5066       return true;
5067     if (match(Val, m_Zero()))
5068       return false;
5069     return std::nullopt;
5070   };
5071   auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5072   auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5073   if (!CmpXZ.has_value() && !CmpYZ.has_value())
5074     return nullptr;
5075   if (!CmpXZ.has_value()) {
5076     std::swap(X, Y);
5077     std::swap(CmpXZ, CmpYZ);
5078   }
5079 
5080   auto FoldIntoCmpYZ = [&]() -> Instruction * {
5081     if (CmpYZ.has_value())
5082       return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5083     return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5084   };
5085 
5086   switch (Pred) {
5087   case ICmpInst::ICMP_EQ:
5088   case ICmpInst::ICMP_NE: {
5089     // If X == Z:
5090     //     Expr       Result
5091     // min(X, Y) == Z X <= Y
5092     // max(X, Y) == Z X >= Y
5093     // min(X, Y) != Z X > Y
5094     // max(X, Y) != Z X < Y
5095     if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5096       ICmpInst::Predicate NewPred =
5097           ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5098       if (Pred == ICmpInst::ICMP_NE)
5099         NewPred = ICmpInst::getInversePredicate(NewPred);
5100       return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5101     }
5102     // Otherwise (X != Z):
5103     ICmpInst::Predicate NewPred = MinMax->getPredicate();
5104     auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5105     if (!MinMaxCmpXZ.has_value()) {
5106       std::swap(X, Y);
5107       std::swap(CmpXZ, CmpYZ);
5108       // Re-check pre-condition X != Z
5109       if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5110         break;
5111       MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5112     }
5113     if (!MinMaxCmpXZ.has_value())
5114       break;
5115     if (*MinMaxCmpXZ) {
5116       //    Expr         Fact    Result
5117       // min(X, Y) == Z  X < Z   false
5118       // max(X, Y) == Z  X > Z   false
5119       // min(X, Y) != Z  X < Z    true
5120       // max(X, Y) != Z  X > Z    true
5121       return replaceInstUsesWith(
5122           I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5123     } else {
5124       //    Expr         Fact    Result
5125       // min(X, Y) == Z  X > Z   Y == Z
5126       // max(X, Y) == Z  X < Z   Y == Z
5127       // min(X, Y) != Z  X > Z   Y != Z
5128       // max(X, Y) != Z  X < Z   Y != Z
5129       return FoldIntoCmpYZ();
5130     }
5131     break;
5132   }
5133   case ICmpInst::ICMP_SLT:
5134   case ICmpInst::ICMP_ULT:
5135   case ICmpInst::ICMP_SLE:
5136   case ICmpInst::ICMP_ULE:
5137   case ICmpInst::ICMP_SGT:
5138   case ICmpInst::ICMP_UGT:
5139   case ICmpInst::ICMP_SGE:
5140   case ICmpInst::ICMP_UGE: {
5141     bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5142     if (*CmpXZ) {
5143       if (IsSame) {
5144         //      Expr        Fact    Result
5145         // min(X, Y) < Z    X < Z   true
5146         // min(X, Y) <= Z   X <= Z  true
5147         // max(X, Y) > Z    X > Z   true
5148         // max(X, Y) >= Z   X >= Z  true
5149         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5150       } else {
5151         //      Expr        Fact    Result
5152         // max(X, Y) < Z    X < Z   Y < Z
5153         // max(X, Y) <= Z   X <= Z  Y <= Z
5154         // min(X, Y) > Z    X > Z   Y > Z
5155         // min(X, Y) >= Z   X >= Z  Y >= Z
5156         return FoldIntoCmpYZ();
5157       }
5158     } else {
5159       if (IsSame) {
5160         //      Expr        Fact    Result
5161         // min(X, Y) < Z    X >= Z  Y < Z
5162         // min(X, Y) <= Z   X > Z   Y <= Z
5163         // max(X, Y) > Z    X <= Z  Y > Z
5164         // max(X, Y) >= Z   X < Z   Y >= Z
5165         return FoldIntoCmpYZ();
5166       } else {
5167         //      Expr        Fact    Result
5168         // max(X, Y) < Z    X >= Z  false
5169         // max(X, Y) <= Z   X > Z   false
5170         // min(X, Y) > Z    X <= Z  false
5171         // min(X, Y) >= Z   X < Z   false
5172         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5173       }
5174     }
5175     break;
5176   }
5177   default:
5178     break;
5179   }
5180 
5181   return nullptr;
5182 }
5183 
5184 // Canonicalize checking for a power-of-2-or-zero value:
5185 static Instruction *foldICmpPow2Test(ICmpInst &I,
5186                                      InstCombiner::BuilderTy &Builder) {
5187   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5188   const CmpInst::Predicate Pred = I.getPredicate();
5189   Value *A = nullptr;
5190   bool CheckIs;
5191   if (I.isEquality()) {
5192     // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
5193     // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
5194     if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
5195                                      m_Deferred(A)))) ||
5196         !match(Op1, m_ZeroInt()))
5197       A = nullptr;
5198 
5199     // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
5200     // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
5201     if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
5202       A = Op1;
5203     else if (match(Op1,
5204                    m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
5205       A = Op0;
5206 
5207     CheckIs = Pred == ICmpInst::ICMP_EQ;
5208   } else if (ICmpInst::isUnsigned(Pred)) {
5209     // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
5210     // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
5211 
5212     if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5213         match(Op0, m_OneUse(m_c_Xor(m_Add(m_Specific(Op1), m_AllOnes()),
5214                                     m_Specific(Op1))))) {
5215       A = Op1;
5216       CheckIs = Pred == ICmpInst::ICMP_UGE;
5217     } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5218                match(Op1, m_OneUse(m_c_Xor(m_Add(m_Specific(Op0), m_AllOnes()),
5219                                            m_Specific(Op0))))) {
5220       A = Op0;
5221       CheckIs = Pred == ICmpInst::ICMP_ULE;
5222     }
5223   }
5224 
5225   if (A) {
5226     Type *Ty = A->getType();
5227     CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
5228     return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
5229                                   ConstantInt::get(Ty, 2))
5230                    : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
5231                                   ConstantInt::get(Ty, 1));
5232   }
5233 
5234   return nullptr;
5235 }
5236 
5237 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
5238   if (!I.isEquality())
5239     return nullptr;
5240 
5241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5242   const CmpInst::Predicate Pred = I.getPredicate();
5243   Value *A, *B, *C, *D;
5244   if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5245     if (A == Op1 || B == Op1) { // (A^B) == A  ->  B == 0
5246       Value *OtherVal = A == Op1 ? B : A;
5247       return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5248     }
5249 
5250     if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5251       // A^c1 == C^c2 --> A == C^(c1^c2)
5252       ConstantInt *C1, *C2;
5253       if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
5254           Op1->hasOneUse()) {
5255         Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
5256         Value *Xor = Builder.CreateXor(C, NC);
5257         return new ICmpInst(Pred, A, Xor);
5258       }
5259 
5260       // A^B == A^D -> B == D
5261       if (A == C)
5262         return new ICmpInst(Pred, B, D);
5263       if (A == D)
5264         return new ICmpInst(Pred, B, C);
5265       if (B == C)
5266         return new ICmpInst(Pred, A, D);
5267       if (B == D)
5268         return new ICmpInst(Pred, A, C);
5269     }
5270   }
5271 
5272   // canoncalize:
5273   // (icmp eq/ne (and X, C), X)
5274   //    -> (icmp eq/ne (and X, ~C), 0)
5275   {
5276     Constant *CMask;
5277     A = nullptr;
5278     if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_ImmConstant(CMask)))))
5279       A = Op1;
5280     else if (match(Op1, m_OneUse(m_And(m_Specific(Op0), m_ImmConstant(CMask)))))
5281       A = Op0;
5282     if (A)
5283       return new ICmpInst(Pred, Builder.CreateAnd(A, Builder.CreateNot(CMask)),
5284                           Constant::getNullValue(A->getType()));
5285   }
5286 
5287   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
5288     // A == (A^B)  ->  B == 0
5289     Value *OtherVal = A == Op0 ? B : A;
5290     return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
5291   }
5292 
5293   // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5294   if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
5295       match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
5296     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
5297 
5298     if (A == C) {
5299       X = B;
5300       Y = D;
5301       Z = A;
5302     } else if (A == D) {
5303       X = B;
5304       Y = C;
5305       Z = A;
5306     } else if (B == C) {
5307       X = A;
5308       Y = D;
5309       Z = B;
5310     } else if (B == D) {
5311       X = A;
5312       Y = C;
5313       Z = B;
5314     }
5315 
5316     if (X) { // Build (X^Y) & Z
5317       Op1 = Builder.CreateXor(X, Y);
5318       Op1 = Builder.CreateAnd(Op1, Z);
5319       return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
5320     }
5321   }
5322 
5323   {
5324     // Similar to above, but specialized for constant because invert is needed:
5325     // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
5326     Value *X, *Y;
5327     Constant *C;
5328     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
5329         match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
5330       Value *Xor = Builder.CreateXor(X, Y);
5331       Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
5332       return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
5333     }
5334   }
5335 
5336   if (match(Op1, m_ZExt(m_Value(A))) &&
5337       (Op0->hasOneUse() || Op1->hasOneUse())) {
5338     // (B & (Pow2C-1)) == zext A --> A == trunc B
5339     // (B & (Pow2C-1)) != zext A --> A != trunc B
5340     const APInt *MaskC;
5341     if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
5342         MaskC->countr_one() == A->getType()->getScalarSizeInBits())
5343       return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
5344   }
5345 
5346   // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
5347   // For lshr and ashr pairs.
5348   const APInt *AP1, *AP2;
5349   if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5350        match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) ||
5351       (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
5352        match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) {
5353     if (AP1 != AP2)
5354       return nullptr;
5355     unsigned TypeBits = AP1->getBitWidth();
5356     unsigned ShAmt = AP1->getLimitedValue(TypeBits);
5357     if (ShAmt < TypeBits && ShAmt != 0) {
5358       ICmpInst::Predicate NewPred =
5359           Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5360       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5361       APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
5362       return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
5363     }
5364   }
5365 
5366   // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
5367   ConstantInt *Cst1;
5368   if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
5369       match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
5370     unsigned TypeBits = Cst1->getBitWidth();
5371     unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
5372     if (ShAmt < TypeBits && ShAmt != 0) {
5373       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
5374       APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
5375       Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
5376                                       I.getName() + ".mask");
5377       return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
5378     }
5379   }
5380 
5381   // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
5382   // "icmp (and X, mask), cst"
5383   uint64_t ShAmt = 0;
5384   if (Op0->hasOneUse() &&
5385       match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
5386       match(Op1, m_ConstantInt(Cst1)) &&
5387       // Only do this when A has multiple uses.  This is most important to do
5388       // when it exposes other optimizations.
5389       !A->hasOneUse()) {
5390     unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
5391 
5392     if (ShAmt < ASize) {
5393       APInt MaskV =
5394           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
5395       MaskV <<= ShAmt;
5396 
5397       APInt CmpV = Cst1->getValue().zext(ASize);
5398       CmpV <<= ShAmt;
5399 
5400       Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
5401       return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
5402     }
5403   }
5404 
5405   if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I, Builder))
5406     return ICmp;
5407 
5408   // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the
5409   // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",
5410   // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps
5411   // of instcombine.
5412   unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5413   if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
5414       match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
5415       A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
5416       (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
5417     APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
5418     Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
5419     return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
5420                                                   : ICmpInst::ICMP_UGE,
5421                         Add, ConstantInt::get(A->getType(), C.shl(1)));
5422   }
5423 
5424   // Canonicalize:
5425   // Assume B_Pow2 != 0
5426   // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
5427   // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
5428   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
5429       isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
5430     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
5431                         ConstantInt::getNullValue(Op0->getType()));
5432 
5433   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
5434       isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
5435     return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
5436                         ConstantInt::getNullValue(Op1->getType()));
5437 
5438   // Canonicalize:
5439   // icmp eq/ne X, OneUse(rotate-right(X))
5440   //    -> icmp eq/ne X, rotate-left(X)
5441   // We generally try to convert rotate-right -> rotate-left, this just
5442   // canonicalizes another case.
5443   CmpInst::Predicate PredUnused = Pred;
5444   if (match(&I, m_c_ICmp(PredUnused, m_Value(A),
5445                          m_OneUse(m_Intrinsic<Intrinsic::fshr>(
5446                              m_Deferred(A), m_Deferred(A), m_Value(B))))))
5447     return new ICmpInst(
5448         Pred, A,
5449         Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
5450 
5451   // Canonicalize:
5452   // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
5453   Constant *Cst;
5454   if (match(&I, m_c_ICmp(PredUnused,
5455                          m_OneUse(m_Xor(m_Value(A), m_ImmConstant(Cst))),
5456                          m_CombineAnd(m_Value(B), m_Unless(m_ImmConstant())))))
5457     return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
5458 
5459   {
5460     // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
5461     auto m_Matcher =
5462         m_CombineOr(m_CombineOr(m_c_Add(m_Value(B), m_Deferred(A)),
5463                                 m_c_Xor(m_Value(B), m_Deferred(A))),
5464                     m_Sub(m_Value(B), m_Deferred(A)));
5465     std::optional<bool> IsZero = std::nullopt;
5466     if (match(&I, m_c_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),
5467                            m_Deferred(A))))
5468       IsZero = false;
5469     // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
5470     else if (match(&I,
5471                    m_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),
5472                           m_Zero())))
5473       IsZero = true;
5474 
5475     if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, /*Depth*/ 0, &I))
5476       // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
5477       //    -> (icmp eq/ne (and X, P2), 0)
5478       // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
5479       //    -> (icmp eq/ne (and X, P2), P2)
5480       return new ICmpInst(Pred, Builder.CreateAnd(B, A),
5481                           *IsZero ? A
5482                                   : ConstantInt::getNullValue(A->getType()));
5483   }
5484 
5485   return nullptr;
5486 }
5487 
5488 Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
5489   ICmpInst::Predicate Pred = ICmp.getPredicate();
5490   Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
5491 
5492   // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
5493   // The trunc masks high bits while the compare may effectively mask low bits.
5494   Value *X;
5495   const APInt *C;
5496   if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
5497     return nullptr;
5498 
5499   // This matches patterns corresponding to tests of the signbit as well as:
5500   // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)
5501   // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)
5502   APInt Mask;
5503   if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {
5504     Value *And = Builder.CreateAnd(X, Mask);
5505     Constant *Zero = ConstantInt::getNullValue(X->getType());
5506     return new ICmpInst(Pred, And, Zero);
5507   }
5508 
5509   unsigned SrcBits = X->getType()->getScalarSizeInBits();
5510   if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {
5511     // If C is a negative power-of-2 (high-bit mask):
5512     // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)
5513     Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));
5514     Value *And = Builder.CreateAnd(X, MaskC);
5515     return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);
5516   }
5517 
5518   if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {
5519     // If C is not-of-power-of-2 (one clear bit):
5520     // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)
5521     Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));
5522     Value *And = Builder.CreateAnd(X, MaskC);
5523     return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);
5524   }
5525 
5526   if (auto *II = dyn_cast<IntrinsicInst>(X)) {
5527     if (II->getIntrinsicID() == Intrinsic::cttz ||
5528         II->getIntrinsicID() == Intrinsic::ctlz) {
5529       unsigned MaxRet = SrcBits;
5530       // If the "is_zero_poison" argument is set, then we know at least
5531       // one bit is set in the input, so the result is always at least one
5532       // less than the full bitwidth of that input.
5533       if (match(II->getArgOperand(1), m_One()))
5534         MaxRet--;
5535 
5536       // Make sure the destination is wide enough to hold the largest output of
5537       // the intrinsic.
5538       if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
5539         if (Instruction *I =
5540                 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
5541           return I;
5542     }
5543   }
5544 
5545   return nullptr;
5546 }
5547 
5548 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
5549   assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
5550   auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
5551   Value *X;
5552   if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
5553     return nullptr;
5554 
5555   bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
5556   bool IsSignedCmp = ICmp.isSigned();
5557 
5558   // icmp Pred (ext X), (ext Y)
5559   Value *Y;
5560   if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
5561     bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
5562     bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
5563 
5564     if (IsZext0 != IsZext1) {
5565         // If X and Y and both i1
5566         // (icmp eq/ne (zext X) (sext Y))
5567         //      eq -> (icmp eq (or X, Y), 0)
5568         //      ne -> (icmp ne (or X, Y), 0)
5569       if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
5570           Y->getType()->isIntOrIntVectorTy(1))
5571         return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
5572                             Constant::getNullValue(X->getType()));
5573 
5574       // If we have mismatched casts and zext has the nneg flag, we can
5575       //  treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
5576 
5577       auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
5578       auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
5579 
5580       bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
5581       bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
5582 
5583       if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
5584         IsSignedExt = true;
5585       else
5586         return nullptr;
5587     }
5588 
5589     // Not an extension from the same type?
5590     Type *XTy = X->getType(), *YTy = Y->getType();
5591     if (XTy != YTy) {
5592       // One of the casts must have one use because we are creating a new cast.
5593       if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
5594         return nullptr;
5595       // Extend the narrower operand to the type of the wider operand.
5596       CastInst::CastOps CastOpcode =
5597           IsSignedExt ? Instruction::SExt : Instruction::ZExt;
5598       if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
5599         X = Builder.CreateCast(CastOpcode, X, YTy);
5600       else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
5601         Y = Builder.CreateCast(CastOpcode, Y, XTy);
5602       else
5603         return nullptr;
5604     }
5605 
5606     // (zext X) == (zext Y) --> X == Y
5607     // (sext X) == (sext Y) --> X == Y
5608     if (ICmp.isEquality())
5609       return new ICmpInst(ICmp.getPredicate(), X, Y);
5610 
5611     // A signed comparison of sign extended values simplifies into a
5612     // signed comparison.
5613     if (IsSignedCmp && IsSignedExt)
5614       return new ICmpInst(ICmp.getPredicate(), X, Y);
5615 
5616     // The other three cases all fold into an unsigned comparison.
5617     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
5618   }
5619 
5620   // Below here, we are only folding a compare with constant.
5621   auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
5622   if (!C)
5623     return nullptr;
5624 
5625   // If a lossless truncate is possible...
5626   Type *SrcTy = CastOp0->getSrcTy();
5627   Constant *Res = getLosslessTrunc(C, SrcTy, CastOp0->getOpcode());
5628   if (Res) {
5629     if (ICmp.isEquality())
5630       return new ICmpInst(ICmp.getPredicate(), X, Res);
5631 
5632     // A signed comparison of sign extended values simplifies into a
5633     // signed comparison.
5634     if (IsSignedExt && IsSignedCmp)
5635       return new ICmpInst(ICmp.getPredicate(), X, Res);
5636 
5637     // The other three cases all fold into an unsigned comparison.
5638     return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
5639   }
5640 
5641   // The re-extended constant changed, partly changed (in the case of a vector),
5642   // or could not be determined to be equal (in the case of a constant
5643   // expression), so the constant cannot be represented in the shorter type.
5644   // All the cases that fold to true or false will have already been handled
5645   // by simplifyICmpInst, so only deal with the tricky case.
5646   if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
5647     return nullptr;
5648 
5649   // Is source op positive?
5650   // icmp ult (sext X), C --> icmp sgt X, -1
5651   if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
5652     return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
5653 
5654   // Is source op negative?
5655   // icmp ugt (sext X), C --> icmp slt X, 0
5656   assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
5657   return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
5658 }
5659 
5660 /// Handle icmp (cast x), (cast or constant).
5661 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
5662   // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
5663   // icmp compares only pointer's value.
5664   // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
5665   Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
5666   Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
5667   if (SimplifiedOp0 || SimplifiedOp1)
5668     return new ICmpInst(ICmp.getPredicate(),
5669                         SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
5670                         SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
5671 
5672   auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
5673   if (!CastOp0)
5674     return nullptr;
5675   if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
5676     return nullptr;
5677 
5678   Value *Op0Src = CastOp0->getOperand(0);
5679   Type *SrcTy = CastOp0->getSrcTy();
5680   Type *DestTy = CastOp0->getDestTy();
5681 
5682   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5683   // integer type is the same size as the pointer type.
5684   auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
5685     if (isa<VectorType>(SrcTy)) {
5686       SrcTy = cast<VectorType>(SrcTy)->getElementType();
5687       DestTy = cast<VectorType>(DestTy)->getElementType();
5688     }
5689     return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
5690   };
5691   if (CastOp0->getOpcode() == Instruction::PtrToInt &&
5692       CompatibleSizes(SrcTy, DestTy)) {
5693     Value *NewOp1 = nullptr;
5694     if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
5695       Value *PtrSrc = PtrToIntOp1->getOperand(0);
5696       if (PtrSrc->getType() == Op0Src->getType())
5697         NewOp1 = PtrToIntOp1->getOperand(0);
5698     } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
5699       NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5700     }
5701 
5702     if (NewOp1)
5703       return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
5704   }
5705 
5706   if (Instruction *R = foldICmpWithTrunc(ICmp))
5707     return R;
5708 
5709   return foldICmpWithZextOrSext(ICmp);
5710 }
5711 
5712 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {
5713   switch (BinaryOp) {
5714     default:
5715       llvm_unreachable("Unsupported binary op");
5716     case Instruction::Add:
5717     case Instruction::Sub:
5718       return match(RHS, m_Zero());
5719     case Instruction::Mul:
5720       return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
5721              match(RHS, m_One());
5722   }
5723 }
5724 
5725 OverflowResult
5726 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
5727                                   bool IsSigned, Value *LHS, Value *RHS,
5728                                   Instruction *CxtI) const {
5729   switch (BinaryOp) {
5730     default:
5731       llvm_unreachable("Unsupported binary op");
5732     case Instruction::Add:
5733       if (IsSigned)
5734         return computeOverflowForSignedAdd(LHS, RHS, CxtI);
5735       else
5736         return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
5737     case Instruction::Sub:
5738       if (IsSigned)
5739         return computeOverflowForSignedSub(LHS, RHS, CxtI);
5740       else
5741         return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
5742     case Instruction::Mul:
5743       if (IsSigned)
5744         return computeOverflowForSignedMul(LHS, RHS, CxtI);
5745       else
5746         return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
5747   }
5748 }
5749 
5750 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
5751                                              bool IsSigned, Value *LHS,
5752                                              Value *RHS, Instruction &OrigI,
5753                                              Value *&Result,
5754                                              Constant *&Overflow) {
5755   if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
5756     std::swap(LHS, RHS);
5757 
5758   // If the overflow check was an add followed by a compare, the insertion point
5759   // may be pointing to the compare.  We want to insert the new instructions
5760   // before the add in case there are uses of the add between the add and the
5761   // compare.
5762   Builder.SetInsertPoint(&OrigI);
5763 
5764   Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
5765   if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
5766     OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
5767 
5768   if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
5769     Result = LHS;
5770     Overflow = ConstantInt::getFalse(OverflowTy);
5771     return true;
5772   }
5773 
5774   switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
5775     case OverflowResult::MayOverflow:
5776       return false;
5777     case OverflowResult::AlwaysOverflowsLow:
5778     case OverflowResult::AlwaysOverflowsHigh:
5779       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5780       Result->takeName(&OrigI);
5781       Overflow = ConstantInt::getTrue(OverflowTy);
5782       return true;
5783     case OverflowResult::NeverOverflows:
5784       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5785       Result->takeName(&OrigI);
5786       Overflow = ConstantInt::getFalse(OverflowTy);
5787       if (auto *Inst = dyn_cast<Instruction>(Result)) {
5788         if (IsSigned)
5789           Inst->setHasNoSignedWrap();
5790         else
5791           Inst->setHasNoUnsignedWrap();
5792       }
5793       return true;
5794   }
5795 
5796   llvm_unreachable("Unexpected overflow result");
5797 }
5798 
5799 /// Recognize and process idiom involving test for multiplication
5800 /// overflow.
5801 ///
5802 /// The caller has matched a pattern of the form:
5803 ///   I = cmp u (mul(zext A, zext B), V
5804 /// The function checks if this is a test for overflow and if so replaces
5805 /// multiplication with call to 'mul.with.overflow' intrinsic.
5806 ///
5807 /// \param I Compare instruction.
5808 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
5809 ///               the compare instruction.  Must be of integer type.
5810 /// \param OtherVal The other argument of compare instruction.
5811 /// \returns Instruction which must replace the compare instruction, NULL if no
5812 ///          replacement required.
5813 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
5814                                          const APInt *OtherVal,
5815                                          InstCombinerImpl &IC) {
5816   // Don't bother doing this transformation for pointers, don't do it for
5817   // vectors.
5818   if (!isa<IntegerType>(MulVal->getType()))
5819     return nullptr;
5820 
5821   auto *MulInstr = dyn_cast<Instruction>(MulVal);
5822   if (!MulInstr)
5823     return nullptr;
5824   assert(MulInstr->getOpcode() == Instruction::Mul);
5825 
5826   auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
5827        *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
5828   assert(LHS->getOpcode() == Instruction::ZExt);
5829   assert(RHS->getOpcode() == Instruction::ZExt);
5830   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
5831 
5832   // Calculate type and width of the result produced by mul.with.overflow.
5833   Type *TyA = A->getType(), *TyB = B->getType();
5834   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
5835            WidthB = TyB->getPrimitiveSizeInBits();
5836   unsigned MulWidth;
5837   Type *MulType;
5838   if (WidthB > WidthA) {
5839     MulWidth = WidthB;
5840     MulType = TyB;
5841   } else {
5842     MulWidth = WidthA;
5843     MulType = TyA;
5844   }
5845 
5846   // In order to replace the original mul with a narrower mul.with.overflow,
5847   // all uses must ignore upper bits of the product.  The number of used low
5848   // bits must be not greater than the width of mul.with.overflow.
5849   if (MulVal->hasNUsesOrMore(2))
5850     for (User *U : MulVal->users()) {
5851       if (U == &I)
5852         continue;
5853       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5854         // Check if truncation ignores bits above MulWidth.
5855         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
5856         if (TruncWidth > MulWidth)
5857           return nullptr;
5858       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5859         // Check if AND ignores bits above MulWidth.
5860         if (BO->getOpcode() != Instruction::And)
5861           return nullptr;
5862         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5863           const APInt &CVal = CI->getValue();
5864           if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
5865             return nullptr;
5866         } else {
5867           // In this case we could have the operand of the binary operation
5868           // being defined in another block, and performing the replacement
5869           // could break the dominance relation.
5870           return nullptr;
5871         }
5872       } else {
5873         // Other uses prohibit this transformation.
5874         return nullptr;
5875       }
5876     }
5877 
5878   // Recognize patterns
5879   switch (I.getPredicate()) {
5880   case ICmpInst::ICMP_UGT: {
5881     // Recognize pattern:
5882     //   mulval = mul(zext A, zext B)
5883     //   cmp ugt mulval, max
5884     APInt MaxVal = APInt::getMaxValue(MulWidth);
5885     MaxVal = MaxVal.zext(OtherVal->getBitWidth());
5886     if (MaxVal.eq(*OtherVal))
5887       break; // Recognized
5888     return nullptr;
5889   }
5890 
5891   case ICmpInst::ICMP_ULT: {
5892     // Recognize pattern:
5893     //   mulval = mul(zext A, zext B)
5894     //   cmp ule mulval, max + 1
5895     APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
5896     if (MaxVal.eq(*OtherVal))
5897       break; // Recognized
5898     return nullptr;
5899   }
5900 
5901   default:
5902     return nullptr;
5903   }
5904 
5905   InstCombiner::BuilderTy &Builder = IC.Builder;
5906   Builder.SetInsertPoint(MulInstr);
5907 
5908   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
5909   Value *MulA = A, *MulB = B;
5910   if (WidthA < MulWidth)
5911     MulA = Builder.CreateZExt(A, MulType);
5912   if (WidthB < MulWidth)
5913     MulB = Builder.CreateZExt(B, MulType);
5914   Function *F = Intrinsic::getDeclaration(
5915       I.getModule(), Intrinsic::umul_with_overflow, MulType);
5916   CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
5917   IC.addToWorklist(MulInstr);
5918 
5919   // If there are uses of mul result other than the comparison, we know that
5920   // they are truncation or binary AND. Change them to use result of
5921   // mul.with.overflow and adjust properly mask/size.
5922   if (MulVal->hasNUsesOrMore(2)) {
5923     Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
5924     for (User *U : make_early_inc_range(MulVal->users())) {
5925       if (U == &I)
5926         continue;
5927       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5928         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
5929           IC.replaceInstUsesWith(*TI, Mul);
5930         else
5931           TI->setOperand(0, Mul);
5932       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5933         assert(BO->getOpcode() == Instruction::And);
5934         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
5935         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
5936         APInt ShortMask = CI->getValue().trunc(MulWidth);
5937         Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
5938         Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
5939         IC.replaceInstUsesWith(*BO, Zext);
5940       } else {
5941         llvm_unreachable("Unexpected Binary operation");
5942       }
5943       IC.addToWorklist(cast<Instruction>(U));
5944     }
5945   }
5946 
5947   // The original icmp gets replaced with the overflow value, maybe inverted
5948   // depending on predicate.
5949   if (I.getPredicate() == ICmpInst::ICMP_ULT) {
5950     Value *Res = Builder.CreateExtractValue(Call, 1);
5951     return BinaryOperator::CreateNot(Res);
5952   }
5953 
5954   return ExtractValueInst::Create(Call, 1);
5955 }
5956 
5957 /// When performing a comparison against a constant, it is possible that not all
5958 /// the bits in the LHS are demanded. This helper method computes the mask that
5959 /// IS demanded.
5960 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
5961   const APInt *RHS;
5962   if (!match(I.getOperand(1), m_APInt(RHS)))
5963     return APInt::getAllOnes(BitWidth);
5964 
5965   // If this is a normal comparison, it demands all bits. If it is a sign bit
5966   // comparison, it only demands the sign bit.
5967   bool UnusedBit;
5968   if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
5969     return APInt::getSignMask(BitWidth);
5970 
5971   switch (I.getPredicate()) {
5972   // For a UGT comparison, we don't care about any bits that
5973   // correspond to the trailing ones of the comparand.  The value of these
5974   // bits doesn't impact the outcome of the comparison, because any value
5975   // greater than the RHS must differ in a bit higher than these due to carry.
5976   case ICmpInst::ICMP_UGT:
5977     return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
5978 
5979   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
5980   // Any value less than the RHS must differ in a higher bit because of carries.
5981   case ICmpInst::ICMP_ULT:
5982     return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
5983 
5984   default:
5985     return APInt::getAllOnes(BitWidth);
5986   }
5987 }
5988 
5989 /// Check that one use is in the same block as the definition and all
5990 /// other uses are in blocks dominated by a given block.
5991 ///
5992 /// \param DI Definition
5993 /// \param UI Use
5994 /// \param DB Block that must dominate all uses of \p DI outside
5995 ///           the parent block
5996 /// \return true when \p UI is the only use of \p DI in the parent block
5997 /// and all other uses of \p DI are in blocks dominated by \p DB.
5998 ///
5999 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
6000                                         const Instruction *UI,
6001                                         const BasicBlock *DB) const {
6002   assert(DI && UI && "Instruction not defined\n");
6003   // Ignore incomplete definitions.
6004   if (!DI->getParent())
6005     return false;
6006   // DI and UI must be in the same block.
6007   if (DI->getParent() != UI->getParent())
6008     return false;
6009   // Protect from self-referencing blocks.
6010   if (DI->getParent() == DB)
6011     return false;
6012   for (const User *U : DI->users()) {
6013     auto *Usr = cast<Instruction>(U);
6014     if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6015       return false;
6016   }
6017   return true;
6018 }
6019 
6020 /// Return true when the instruction sequence within a block is select-cmp-br.
6021 static bool isChainSelectCmpBranch(const SelectInst *SI) {
6022   const BasicBlock *BB = SI->getParent();
6023   if (!BB)
6024     return false;
6025   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
6026   if (!BI || BI->getNumSuccessors() != 2)
6027     return false;
6028   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
6029   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
6030     return false;
6031   return true;
6032 }
6033 
6034 /// True when a select result is replaced by one of its operands
6035 /// in select-icmp sequence. This will eventually result in the elimination
6036 /// of the select.
6037 ///
6038 /// \param SI    Select instruction
6039 /// \param Icmp  Compare instruction
6040 /// \param SIOpd Operand that replaces the select
6041 ///
6042 /// Notes:
6043 /// - The replacement is global and requires dominator information
6044 /// - The caller is responsible for the actual replacement
6045 ///
6046 /// Example:
6047 ///
6048 /// entry:
6049 ///  %4 = select i1 %3, %C* %0, %C* null
6050 ///  %5 = icmp eq %C* %4, null
6051 ///  br i1 %5, label %9, label %7
6052 ///  ...
6053 ///  ; <label>:7                                       ; preds = %entry
6054 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
6055 ///  ...
6056 ///
6057 /// can be transformed to
6058 ///
6059 ///  %5 = icmp eq %C* %0, null
6060 ///  %6 = select i1 %3, i1 %5, i1 true
6061 ///  br i1 %6, label %9, label %7
6062 ///  ...
6063 ///  ; <label>:7                                       ; preds = %entry
6064 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
6065 ///
6066 /// Similar when the first operand of the select is a constant or/and
6067 /// the compare is for not equal rather than equal.
6068 ///
6069 /// NOTE: The function is only called when the select and compare constants
6070 /// are equal, the optimization can work only for EQ predicates. This is not a
6071 /// major restriction since a NE compare should be 'normalized' to an equal
6072 /// compare, which usually happens in the combiner and test case
6073 /// select-cmp-br.ll checks for it.
6074 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
6075                                                  const ICmpInst *Icmp,
6076                                                  const unsigned SIOpd) {
6077   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
6078   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
6079     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
6080     // The check for the single predecessor is not the best that can be
6081     // done. But it protects efficiently against cases like when SI's
6082     // home block has two successors, Succ and Succ1, and Succ1 predecessor
6083     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
6084     // replaced can be reached on either path. So the uniqueness check
6085     // guarantees that the path all uses of SI (outside SI's parent) are on
6086     // is disjoint from all other paths out of SI. But that information
6087     // is more expensive to compute, and the trade-off here is in favor
6088     // of compile-time. It should also be noticed that we check for a single
6089     // predecessor and not only uniqueness. This to handle the situation when
6090     // Succ and Succ1 points to the same basic block.
6091     if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
6092       NumSel++;
6093       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
6094       return true;
6095     }
6096   }
6097   return false;
6098 }
6099 
6100 /// Try to fold the comparison based on range information we can get by checking
6101 /// whether bits are known to be zero or one in the inputs.
6102 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
6103   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6104   Type *Ty = Op0->getType();
6105   ICmpInst::Predicate Pred = I.getPredicate();
6106 
6107   // Get scalar or pointer size.
6108   unsigned BitWidth = Ty->isIntOrIntVectorTy()
6109                           ? Ty->getScalarSizeInBits()
6110                           : DL.getPointerTypeSizeInBits(Ty->getScalarType());
6111 
6112   if (!BitWidth)
6113     return nullptr;
6114 
6115   KnownBits Op0Known(BitWidth);
6116   KnownBits Op1Known(BitWidth);
6117 
6118   {
6119     // Don't use dominating conditions when folding icmp using known bits. This
6120     // may convert signed into unsigned predicates in ways that other passes
6121     // (especially IndVarSimplify) may not be able to reliably undo.
6122     SQ.DC = nullptr;
6123     auto _ = make_scope_exit([&]() { SQ.DC = &DC; });
6124     if (SimplifyDemandedBits(&I, 0, getDemandedBitsLHSMask(I, BitWidth),
6125                              Op0Known, 0))
6126       return &I;
6127 
6128     if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0))
6129       return &I;
6130   }
6131 
6132   // Given the known and unknown bits, compute a range that the LHS could be
6133   // in.  Compute the Min, Max and RHS values based on the known bits. For the
6134   // EQ and NE we use unsigned values.
6135   APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6136   APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6137   if (I.isSigned()) {
6138     Op0Min = Op0Known.getSignedMinValue();
6139     Op0Max = Op0Known.getSignedMaxValue();
6140     Op1Min = Op1Known.getSignedMinValue();
6141     Op1Max = Op1Known.getSignedMaxValue();
6142   } else {
6143     Op0Min = Op0Known.getMinValue();
6144     Op0Max = Op0Known.getMaxValue();
6145     Op1Min = Op1Known.getMinValue();
6146     Op1Max = Op1Known.getMaxValue();
6147   }
6148 
6149   // If Min and Max are known to be the same, then SimplifyDemandedBits figured
6150   // out that the LHS or RHS is a constant. Constant fold this now, so that
6151   // code below can assume that Min != Max.
6152   if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6153     return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
6154   if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6155     return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
6156 
6157   // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
6158   // min/max canonical compare with some other compare. That could lead to
6159   // conflict with select canonicalization and infinite looping.
6160   // FIXME: This constraint may go away if min/max intrinsics are canonical.
6161   auto isMinMaxCmp = [&](Instruction &Cmp) {
6162     if (!Cmp.hasOneUse())
6163       return false;
6164     Value *A, *B;
6165     SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
6166     if (!SelectPatternResult::isMinOrMax(SPF))
6167       return false;
6168     return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
6169            match(Op1, m_MaxOrMin(m_Value(), m_Value()));
6170   };
6171   if (!isMinMaxCmp(I)) {
6172     switch (Pred) {
6173     default:
6174       break;
6175     case ICmpInst::ICMP_ULT: {
6176       if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6177         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6178       const APInt *CmpC;
6179       if (match(Op1, m_APInt(CmpC))) {
6180         // A <u C -> A == C-1 if min(A)+1 == C
6181         if (*CmpC == Op0Min + 1)
6182           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6183                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6184         // X <u C --> X == 0, if the number of zero bits in the bottom of X
6185         // exceeds the log2 of C.
6186         if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
6187           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6188                               Constant::getNullValue(Op1->getType()));
6189       }
6190       break;
6191     }
6192     case ICmpInst::ICMP_UGT: {
6193       if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6194         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6195       const APInt *CmpC;
6196       if (match(Op1, m_APInt(CmpC))) {
6197         // A >u C -> A == C+1 if max(a)-1 == C
6198         if (*CmpC == Op0Max - 1)
6199           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6200                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6201         // X >u C --> X != 0, if the number of zero bits in the bottom of X
6202         // exceeds the log2 of C.
6203         if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
6204           return new ICmpInst(ICmpInst::ICMP_NE, Op0,
6205                               Constant::getNullValue(Op1->getType()));
6206       }
6207       break;
6208     }
6209     case ICmpInst::ICMP_SLT: {
6210       if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6211         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6212       const APInt *CmpC;
6213       if (match(Op1, m_APInt(CmpC))) {
6214         if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
6215           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6216                               ConstantInt::get(Op1->getType(), *CmpC - 1));
6217       }
6218       break;
6219     }
6220     case ICmpInst::ICMP_SGT: {
6221       if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6222         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6223       const APInt *CmpC;
6224       if (match(Op1, m_APInt(CmpC))) {
6225         if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
6226           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6227                               ConstantInt::get(Op1->getType(), *CmpC + 1));
6228       }
6229       break;
6230     }
6231     }
6232   }
6233 
6234   // Based on the range information we know about the LHS, see if we can
6235   // simplify this comparison.  For example, (x&4) < 8 is always true.
6236   switch (Pred) {
6237   default:
6238     llvm_unreachable("Unknown icmp opcode!");
6239   case ICmpInst::ICMP_EQ:
6240   case ICmpInst::ICMP_NE: {
6241     if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6242       return replaceInstUsesWith(
6243           I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));
6244 
6245     // If all bits are known zero except for one, then we know at most one bit
6246     // is set. If the comparison is against zero, then this is a check to see if
6247     // *that* bit is set.
6248     APInt Op0KnownZeroInverted = ~Op0Known.Zero;
6249     if (Op1Known.isZero()) {
6250       // If the LHS is an AND with the same constant, look through it.
6251       Value *LHS = nullptr;
6252       const APInt *LHSC;
6253       if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
6254           *LHSC != Op0KnownZeroInverted)
6255         LHS = Op0;
6256 
6257       Value *X;
6258       const APInt *C1;
6259       if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
6260         Type *XTy = X->getType();
6261         unsigned Log2C1 = C1->countr_zero();
6262         APInt C2 = Op0KnownZeroInverted;
6263         APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
6264         if (C2Pow2.isPowerOf2()) {
6265           // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
6266           // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
6267           // ((C1 << X) & C2) != 0 -> X  < (Log2(C2+C1) - Log2(C1))
6268           unsigned Log2C2 = C2Pow2.countr_zero();
6269           auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
6270           auto NewPred =
6271               Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
6272           return new ICmpInst(NewPred, X, CmpC);
6273         }
6274       }
6275     }
6276 
6277     // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
6278     if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
6279         (Op0Known & Op1Known) == Op0Known)
6280       return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6281                           ConstantInt::getNullValue(Op1->getType()));
6282     break;
6283   }
6284   case ICmpInst::ICMP_ULT: {
6285     if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6286       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6287     if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6288       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6289     break;
6290   }
6291   case ICmpInst::ICMP_UGT: {
6292     if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6293       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6294     if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6295       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6296     break;
6297   }
6298   case ICmpInst::ICMP_SLT: {
6299     if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6300       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6301     if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6302       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6303     break;
6304   }
6305   case ICmpInst::ICMP_SGT: {
6306     if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6307       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6308     if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6309       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6310     break;
6311   }
6312   case ICmpInst::ICMP_SGE:
6313     assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6314     if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6315       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6316     if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6317       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6318     if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
6319       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6320     break;
6321   case ICmpInst::ICMP_SLE:
6322     assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6323     if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6324       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6325     if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6326       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6327     if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
6328       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6329     break;
6330   case ICmpInst::ICMP_UGE:
6331     assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6332     if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6333       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6334     if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6335       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6336     if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
6337       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6338     break;
6339   case ICmpInst::ICMP_ULE:
6340     assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6341     if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6342       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6343     if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6344       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6345     if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
6346       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
6347     break;
6348   }
6349 
6350   // Turn a signed comparison into an unsigned one if both operands are known to
6351   // have the same sign.
6352   if (I.isSigned() &&
6353       ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
6354        (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
6355     return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6356 
6357   return nullptr;
6358 }
6359 
6360 /// If one operand of an icmp is effectively a bool (value range of {0,1}),
6361 /// then try to reduce patterns based on that limit.
6362 Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
6363   Value *X, *Y;
6364   ICmpInst::Predicate Pred;
6365 
6366   // X must be 0 and bool must be true for "ULT":
6367   // X <u (zext i1 Y) --> (X == 0) & Y
6368   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
6369       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
6370     return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
6371 
6372   // X must be 0 or bool must be true for "ULE":
6373   // X <=u (sext i1 Y) --> (X == 0) | Y
6374   if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
6375       Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
6376     return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
6377 
6378   // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
6379   ICmpInst::Predicate Pred1, Pred2;
6380   const APInt *C;
6381   Instruction *ExtI;
6382   if (match(&I, m_c_ICmp(Pred1, m_Value(X),
6383                          m_CombineAnd(m_Instruction(ExtI),
6384                                       m_ZExtOrSExt(m_ICmp(Pred2, m_Deferred(X),
6385                                                           m_APInt(C)))))) &&
6386       ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
6387     bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
6388     bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
6389     auto CreateRangeCheck = [&] {
6390       Value *CmpV1 =
6391           Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
6392       Value *CmpV2 = Builder.CreateICmp(
6393           Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
6394       return BinaryOperator::Create(
6395           Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
6396           CmpV1, CmpV2);
6397     };
6398     if (C->isZero()) {
6399       if (Pred2 == ICmpInst::ICMP_EQ) {
6400         // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
6401         // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
6402         return replaceInstUsesWith(
6403             I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6404       } else if (!IsSExt || HasOneUse) {
6405         // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
6406         // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
6407         // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
6408         // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X == -1
6409         return CreateRangeCheck();
6410       }
6411     } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
6412       if (Pred2 == ICmpInst::ICMP_NE) {
6413         // icmp eq X, (zext (icmp ne X, 1)) --> false
6414         // icmp ne X, (zext (icmp ne X, 1)) --> true
6415         // icmp eq X, (sext (icmp ne X, -1)) --> false
6416         // icmp ne X, (sext (icmp ne X, -1)) --> true
6417         return replaceInstUsesWith(
6418             I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
6419       } else if (!IsSExt || HasOneUse) {
6420         // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
6421         // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
6422         // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
6423         // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
6424         return CreateRangeCheck();
6425       }
6426     } else {
6427       // when C != 0 && C != 1:
6428       //   icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
6429       //   icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
6430       //   icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
6431       //   icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
6432       // when C != 0 && C != -1:
6433       //   icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
6434       //   icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
6435       //   icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
6436       //   icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
6437       return ICmpInst::Create(
6438           Instruction::ICmp, Pred1, X,
6439           ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
6440                                                    ? (IsSExt ? -1 : 1)
6441                                                    : 0));
6442     }
6443   }
6444 
6445   return nullptr;
6446 }
6447 
6448 std::optional<std::pair<CmpInst::Predicate, Constant *>>
6449 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
6450                                                        Constant *C) {
6451   assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
6452          "Only for relational integer predicates.");
6453 
6454   Type *Type = C->getType();
6455   bool IsSigned = ICmpInst::isSigned(Pred);
6456 
6457   CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
6458   bool WillIncrement =
6459       UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
6460 
6461   // Check if the constant operand can be safely incremented/decremented
6462   // without overflowing/underflowing.
6463   auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
6464     return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
6465   };
6466 
6467   Constant *SafeReplacementConstant = nullptr;
6468   if (auto *CI = dyn_cast<ConstantInt>(C)) {
6469     // Bail out if the constant can't be safely incremented/decremented.
6470     if (!ConstantIsOk(CI))
6471       return std::nullopt;
6472   } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
6473     unsigned NumElts = FVTy->getNumElements();
6474     for (unsigned i = 0; i != NumElts; ++i) {
6475       Constant *Elt = C->getAggregateElement(i);
6476       if (!Elt)
6477         return std::nullopt;
6478 
6479       if (isa<UndefValue>(Elt))
6480         continue;
6481 
6482       // Bail out if we can't determine if this constant is min/max or if we
6483       // know that this constant is min/max.
6484       auto *CI = dyn_cast<ConstantInt>(Elt);
6485       if (!CI || !ConstantIsOk(CI))
6486         return std::nullopt;
6487 
6488       if (!SafeReplacementConstant)
6489         SafeReplacementConstant = CI;
6490     }
6491   } else {
6492     // ConstantExpr?
6493     return std::nullopt;
6494   }
6495 
6496   // It may not be safe to change a compare predicate in the presence of
6497   // undefined elements, so replace those elements with the first safe constant
6498   // that we found.
6499   // TODO: in case of poison, it is safe; let's replace undefs only.
6500   if (C->containsUndefOrPoisonElement()) {
6501     assert(SafeReplacementConstant && "Replacement constant not set");
6502     C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
6503   }
6504 
6505   CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
6506 
6507   // Increment or decrement the constant.
6508   Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
6509   Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
6510 
6511   return std::make_pair(NewPred, NewC);
6512 }
6513 
6514 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
6515 /// it into the appropriate icmp lt or icmp gt instruction. This transform
6516 /// allows them to be folded in visitICmpInst.
6517 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
6518   ICmpInst::Predicate Pred = I.getPredicate();
6519   if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
6520       InstCombiner::isCanonicalPredicate(Pred))
6521     return nullptr;
6522 
6523   Value *Op0 = I.getOperand(0);
6524   Value *Op1 = I.getOperand(1);
6525   auto *Op1C = dyn_cast<Constant>(Op1);
6526   if (!Op1C)
6527     return nullptr;
6528 
6529   auto FlippedStrictness =
6530       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
6531   if (!FlippedStrictness)
6532     return nullptr;
6533 
6534   return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
6535 }
6536 
6537 /// If we have a comparison with a non-canonical predicate, if we can update
6538 /// all the users, invert the predicate and adjust all the users.
6539 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
6540   // Is the predicate already canonical?
6541   CmpInst::Predicate Pred = I.getPredicate();
6542   if (InstCombiner::isCanonicalPredicate(Pred))
6543     return nullptr;
6544 
6545   // Can all users be adjusted to predicate inversion?
6546   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
6547     return nullptr;
6548 
6549   // Ok, we can canonicalize comparison!
6550   // Let's first invert the comparison's predicate.
6551   I.setPredicate(CmpInst::getInversePredicate(Pred));
6552   I.setName(I.getName() + ".not");
6553 
6554   // And, adapt users.
6555   freelyInvertAllUsersOf(&I);
6556 
6557   return &I;
6558 }
6559 
6560 /// Integer compare with boolean values can always be turned into bitwise ops.
6561 static Instruction *canonicalizeICmpBool(ICmpInst &I,
6562                                          InstCombiner::BuilderTy &Builder) {
6563   Value *A = I.getOperand(0), *B = I.getOperand(1);
6564   assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
6565 
6566   // A boolean compared to true/false can be simplified to Op0/true/false in
6567   // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
6568   // Cases not handled by InstSimplify are always 'not' of Op0.
6569   if (match(B, m_Zero())) {
6570     switch (I.getPredicate()) {
6571       case CmpInst::ICMP_EQ:  // A ==   0 -> !A
6572       case CmpInst::ICMP_ULE: // A <=u  0 -> !A
6573       case CmpInst::ICMP_SGE: // A >=s  0 -> !A
6574         return BinaryOperator::CreateNot(A);
6575       default:
6576         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6577     }
6578   } else if (match(B, m_One())) {
6579     switch (I.getPredicate()) {
6580       case CmpInst::ICMP_NE:  // A !=  1 -> !A
6581       case CmpInst::ICMP_ULT: // A <u  1 -> !A
6582       case CmpInst::ICMP_SGT: // A >s -1 -> !A
6583         return BinaryOperator::CreateNot(A);
6584       default:
6585         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
6586     }
6587   }
6588 
6589   switch (I.getPredicate()) {
6590   default:
6591     llvm_unreachable("Invalid icmp instruction!");
6592   case ICmpInst::ICMP_EQ:
6593     // icmp eq i1 A, B -> ~(A ^ B)
6594     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
6595 
6596   case ICmpInst::ICMP_NE:
6597     // icmp ne i1 A, B -> A ^ B
6598     return BinaryOperator::CreateXor(A, B);
6599 
6600   case ICmpInst::ICMP_UGT:
6601     // icmp ugt -> icmp ult
6602     std::swap(A, B);
6603     [[fallthrough]];
6604   case ICmpInst::ICMP_ULT:
6605     // icmp ult i1 A, B -> ~A & B
6606     return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
6607 
6608   case ICmpInst::ICMP_SGT:
6609     // icmp sgt -> icmp slt
6610     std::swap(A, B);
6611     [[fallthrough]];
6612   case ICmpInst::ICMP_SLT:
6613     // icmp slt i1 A, B -> A & ~B
6614     return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
6615 
6616   case ICmpInst::ICMP_UGE:
6617     // icmp uge -> icmp ule
6618     std::swap(A, B);
6619     [[fallthrough]];
6620   case ICmpInst::ICMP_ULE:
6621     // icmp ule i1 A, B -> ~A | B
6622     return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
6623 
6624   case ICmpInst::ICMP_SGE:
6625     // icmp sge -> icmp sle
6626     std::swap(A, B);
6627     [[fallthrough]];
6628   case ICmpInst::ICMP_SLE:
6629     // icmp sle i1 A, B -> A | ~B
6630     return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
6631   }
6632 }
6633 
6634 // Transform pattern like:
6635 //   (1 << Y) u<= X  or  ~(-1 << Y) u<  X  or  ((1 << Y)+(-1)) u<  X
6636 //   (1 << Y) u>  X  or  ~(-1 << Y) u>= X  or  ((1 << Y)+(-1)) u>= X
6637 // Into:
6638 //   (X l>> Y) != 0
6639 //   (X l>> Y) == 0
6640 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
6641                                             InstCombiner::BuilderTy &Builder) {
6642   ICmpInst::Predicate Pred, NewPred;
6643   Value *X, *Y;
6644   if (match(&Cmp,
6645             m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
6646     switch (Pred) {
6647     case ICmpInst::ICMP_ULE:
6648       NewPred = ICmpInst::ICMP_NE;
6649       break;
6650     case ICmpInst::ICMP_UGT:
6651       NewPred = ICmpInst::ICMP_EQ;
6652       break;
6653     default:
6654       return nullptr;
6655     }
6656   } else if (match(&Cmp, m_c_ICmp(Pred,
6657                                   m_OneUse(m_CombineOr(
6658                                       m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
6659                                       m_Add(m_Shl(m_One(), m_Value(Y)),
6660                                             m_AllOnes()))),
6661                                   m_Value(X)))) {
6662     // The variant with 'add' is not canonical, (the variant with 'not' is)
6663     // we only get it because it has extra uses, and can't be canonicalized,
6664 
6665     switch (Pred) {
6666     case ICmpInst::ICMP_ULT:
6667       NewPred = ICmpInst::ICMP_NE;
6668       break;
6669     case ICmpInst::ICMP_UGE:
6670       NewPred = ICmpInst::ICMP_EQ;
6671       break;
6672     default:
6673       return nullptr;
6674     }
6675   } else
6676     return nullptr;
6677 
6678   Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
6679   Constant *Zero = Constant::getNullValue(NewX->getType());
6680   return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
6681 }
6682 
6683 static Instruction *foldVectorCmp(CmpInst &Cmp,
6684                                   InstCombiner::BuilderTy &Builder) {
6685   const CmpInst::Predicate Pred = Cmp.getPredicate();
6686   Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
6687   Value *V1, *V2;
6688 
6689   auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
6690     Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
6691     if (auto *I = dyn_cast<Instruction>(V))
6692       I->copyIRFlags(&Cmp);
6693     Module *M = Cmp.getModule();
6694     Function *F = Intrinsic::getDeclaration(
6695         M, Intrinsic::experimental_vector_reverse, V->getType());
6696     return CallInst::Create(F, V);
6697   };
6698 
6699   if (match(LHS, m_VecReverse(m_Value(V1)))) {
6700     // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
6701     if (match(RHS, m_VecReverse(m_Value(V2))) &&
6702         (LHS->hasOneUse() || RHS->hasOneUse()))
6703       return createCmpReverse(Pred, V1, V2);
6704 
6705     // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
6706     if (LHS->hasOneUse() && isSplatValue(RHS))
6707       return createCmpReverse(Pred, V1, RHS);
6708   }
6709   // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
6710   else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
6711     return createCmpReverse(Pred, LHS, V2);
6712 
6713   ArrayRef<int> M;
6714   if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
6715     return nullptr;
6716 
6717   // If both arguments of the cmp are shuffles that use the same mask and
6718   // shuffle within a single vector, move the shuffle after the cmp:
6719   // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
6720   Type *V1Ty = V1->getType();
6721   if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
6722       V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
6723     Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
6724     return new ShuffleVectorInst(NewCmp, M);
6725   }
6726 
6727   // Try to canonicalize compare with splatted operand and splat constant.
6728   // TODO: We could generalize this for more than splats. See/use the code in
6729   //       InstCombiner::foldVectorBinop().
6730   Constant *C;
6731   if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
6732     return nullptr;
6733 
6734   // Length-changing splats are ok, so adjust the constants as needed:
6735   // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
6736   Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true);
6737   int MaskSplatIndex;
6738   if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) {
6739     // We allow undefs in matching, but this transform removes those for safety.
6740     // Demanded elements analysis should be able to recover some/all of that.
6741     C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
6742                                  ScalarC);
6743     SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
6744     Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
6745     return new ShuffleVectorInst(NewCmp, NewM);
6746   }
6747 
6748   return nullptr;
6749 }
6750 
6751 // extract(uadd.with.overflow(A, B), 0) ult A
6752 //  -> extract(uadd.with.overflow(A, B), 1)
6753 static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
6754   CmpInst::Predicate Pred = I.getPredicate();
6755   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6756 
6757   Value *UAddOv;
6758   Value *A, *B;
6759   auto UAddOvResultPat = m_ExtractValue<0>(
6760       m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
6761   if (match(Op0, UAddOvResultPat) &&
6762       ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
6763        (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
6764         (match(A, m_One()) || match(B, m_One()))) ||
6765        (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
6766         (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
6767     // extract(uadd.with.overflow(A, B), 0) < A
6768     // extract(uadd.with.overflow(A, 1), 0) == 0
6769     // extract(uadd.with.overflow(A, -1), 0) != -1
6770     UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
6771   else if (match(Op1, UAddOvResultPat) &&
6772            Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))
6773     // A > extract(uadd.with.overflow(A, B), 0)
6774     UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
6775   else
6776     return nullptr;
6777 
6778   return ExtractValueInst::Create(UAddOv, 1);
6779 }
6780 
6781 static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
6782   if (!I.getOperand(0)->getType()->isPointerTy() ||
6783       NullPointerIsDefined(
6784           I.getParent()->getParent(),
6785           I.getOperand(0)->getType()->getPointerAddressSpace())) {
6786     return nullptr;
6787   }
6788   Instruction *Op;
6789   if (match(I.getOperand(0), m_Instruction(Op)) &&
6790       match(I.getOperand(1), m_Zero()) &&
6791       Op->isLaunderOrStripInvariantGroup()) {
6792     return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
6793                             Op->getOperand(0), I.getOperand(1));
6794   }
6795   return nullptr;
6796 }
6797 
6798 /// This function folds patterns produced by lowering of reduce idioms, such as
6799 /// llvm.vector.reduce.and which are lowered into instruction chains. This code
6800 /// attempts to generate fewer number of scalar comparisons instead of vector
6801 /// comparisons when possible.
6802 static Instruction *foldReductionIdiom(ICmpInst &I,
6803                                        InstCombiner::BuilderTy &Builder,
6804                                        const DataLayout &DL) {
6805   if (I.getType()->isVectorTy())
6806     return nullptr;
6807   ICmpInst::Predicate OuterPred, InnerPred;
6808   Value *LHS, *RHS;
6809 
6810   // Match lowering of @llvm.vector.reduce.and. Turn
6811   ///   %vec_ne = icmp ne <8 x i8> %lhs, %rhs
6812   ///   %scalar_ne = bitcast <8 x i1> %vec_ne to i8
6813   ///   %res = icmp <pred> i8 %scalar_ne, 0
6814   ///
6815   /// into
6816   ///
6817   ///   %lhs.scalar = bitcast <8 x i8> %lhs to i64
6818   ///   %rhs.scalar = bitcast <8 x i8> %rhs to i64
6819   ///   %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
6820   ///
6821   /// for <pred> in {ne, eq}.
6822   if (!match(&I, m_ICmp(OuterPred,
6823                         m_OneUse(m_BitCast(m_OneUse(
6824                             m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
6825                         m_Zero())))
6826     return nullptr;
6827   auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
6828   if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
6829     return nullptr;
6830   unsigned NumBits =
6831       LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
6832   // TODO: Relax this to "not wider than max legal integer type"?
6833   if (!DL.isLegalInteger(NumBits))
6834     return nullptr;
6835 
6836   if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
6837     auto *ScalarTy = Builder.getIntNTy(NumBits);
6838     LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
6839     RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
6840     return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
6841                             I.getName());
6842   }
6843 
6844   return nullptr;
6845 }
6846 
6847 // This helper will be called with icmp operands in both orders.
6848 Instruction *InstCombinerImpl::foldICmpCommutative(ICmpInst::Predicate Pred,
6849                                                    Value *Op0, Value *Op1,
6850                                                    ICmpInst &CxtI) {
6851   // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
6852   if (auto *GEP = dyn_cast<GEPOperator>(Op0))
6853     if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
6854       return NI;
6855 
6856   if (auto *SI = dyn_cast<SelectInst>(Op0))
6857     if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
6858       return NI;
6859 
6860   if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0))
6861     if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
6862       return Res;
6863 
6864   {
6865     Value *X;
6866     const APInt *C;
6867     // icmp X+Cst, X
6868     if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
6869       return foldICmpAddOpConst(X, *C, Pred);
6870   }
6871 
6872   // abs(X) >=  X --> true
6873   // abs(X) u<= X --> true
6874   // abs(X) <   X --> false
6875   // abs(X) u>  X --> false
6876   // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
6877   // abs(X) <=  X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
6878   // abs(X) ==  X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
6879   // abs(X) u<  X --> IsIntMinPosion ? `X < 0` : `X >   INTMIN`
6880   // abs(X) >   X --> IsIntMinPosion ? `X < 0` : `X >   INTMIN`
6881   // abs(X) !=  X --> IsIntMinPosion ? `X < 0` : `X >   INTMIN`
6882   {
6883     Value *X;
6884     Constant *C;
6885     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X), m_Constant(C))) &&
6886         match(Op1, m_Specific(X))) {
6887       Value *NullValue = Constant::getNullValue(X->getType());
6888       Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
6889       const APInt SMin =
6890           APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
6891       bool IsIntMinPosion = C->isAllOnesValue();
6892       switch (Pred) {
6893       case CmpInst::ICMP_ULE:
6894       case CmpInst::ICMP_SGE:
6895         return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
6896       case CmpInst::ICMP_UGT:
6897       case CmpInst::ICMP_SLT:
6898         return replaceInstUsesWith(CxtI, ConstantInt::getFalse(CxtI.getType()));
6899       case CmpInst::ICMP_UGE:
6900       case CmpInst::ICMP_SLE:
6901       case CmpInst::ICMP_EQ: {
6902         return replaceInstUsesWith(
6903             CxtI, IsIntMinPosion
6904                       ? Builder.CreateICmpSGT(X, AllOnesValue)
6905                       : Builder.CreateICmpULT(
6906                             X, ConstantInt::get(X->getType(), SMin + 1)));
6907       }
6908       case CmpInst::ICMP_ULT:
6909       case CmpInst::ICMP_SGT:
6910       case CmpInst::ICMP_NE: {
6911         return replaceInstUsesWith(
6912             CxtI, IsIntMinPosion
6913                       ? Builder.CreateICmpSLT(X, NullValue)
6914                       : Builder.CreateICmpUGT(
6915                             X, ConstantInt::get(X->getType(), SMin)));
6916       }
6917       default:
6918         llvm_unreachable("Invalid predicate!");
6919       }
6920     }
6921   }
6922 
6923   return nullptr;
6924 }
6925 
6926 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
6927   bool Changed = false;
6928   const SimplifyQuery Q = SQ.getWithInstruction(&I);
6929   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6930   unsigned Op0Cplxity = getComplexity(Op0);
6931   unsigned Op1Cplxity = getComplexity(Op1);
6932 
6933   /// Orders the operands of the compare so that they are listed from most
6934   /// complex to least complex.  This puts constants before unary operators,
6935   /// before binary operators.
6936   if (Op0Cplxity < Op1Cplxity) {
6937     I.swapOperands();
6938     std::swap(Op0, Op1);
6939     Changed = true;
6940   }
6941 
6942   if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
6943     return replaceInstUsesWith(I, V);
6944 
6945   // Comparing -val or val with non-zero is the same as just comparing val
6946   // ie, abs(val) != 0 -> val != 0
6947   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
6948     Value *Cond, *SelectTrue, *SelectFalse;
6949     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
6950                             m_Value(SelectFalse)))) {
6951       if (Value *V = dyn_castNegVal(SelectTrue)) {
6952         if (V == SelectFalse)
6953           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6954       }
6955       else if (Value *V = dyn_castNegVal(SelectFalse)) {
6956         if (V == SelectTrue)
6957           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6958       }
6959     }
6960   }
6961 
6962   if (Op0->getType()->isIntOrIntVectorTy(1))
6963     if (Instruction *Res = canonicalizeICmpBool(I, Builder))
6964       return Res;
6965 
6966   if (Instruction *Res = canonicalizeCmpWithConstant(I))
6967     return Res;
6968 
6969   if (Instruction *Res = canonicalizeICmpPredicate(I))
6970     return Res;
6971 
6972   if (Instruction *Res = foldICmpWithConstant(I))
6973     return Res;
6974 
6975   if (Instruction *Res = foldICmpWithDominatingICmp(I))
6976     return Res;
6977 
6978   if (Instruction *Res = foldICmpUsingBoolRange(I))
6979     return Res;
6980 
6981   if (Instruction *Res = foldICmpUsingKnownBits(I))
6982     return Res;
6983 
6984   if (Instruction *Res = foldICmpTruncWithTruncOrExt(I, Q))
6985     return Res;
6986 
6987   // Test if the ICmpInst instruction is used exclusively by a select as
6988   // part of a minimum or maximum operation. If so, refrain from doing
6989   // any other folding. This helps out other analyses which understand
6990   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6991   // and CodeGen. And in this case, at least one of the comparison
6992   // operands has at least one user besides the compare (the select),
6993   // which would often largely negate the benefit of folding anyway.
6994   //
6995   // Do the same for the other patterns recognized by matchSelectPattern.
6996   if (I.hasOneUse())
6997     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
6998       Value *A, *B;
6999       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
7000       if (SPR.Flavor != SPF_UNKNOWN)
7001         return nullptr;
7002     }
7003 
7004   // Do this after checking for min/max to prevent infinite looping.
7005   if (Instruction *Res = foldICmpWithZero(I))
7006     return Res;
7007 
7008   // FIXME: We only do this after checking for min/max to prevent infinite
7009   // looping caused by a reverse canonicalization of these patterns for min/max.
7010   // FIXME: The organization of folds is a mess. These would naturally go into
7011   // canonicalizeCmpWithConstant(), but we can't move all of the above folds
7012   // down here after the min/max restriction.
7013   ICmpInst::Predicate Pred = I.getPredicate();
7014   const APInt *C;
7015   if (match(Op1, m_APInt(C))) {
7016     // For i32: x >u 2147483647 -> x <s 0  -> true if sign bit set
7017     if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
7018       Constant *Zero = Constant::getNullValue(Op0->getType());
7019       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
7020     }
7021 
7022     // For i32: x <u 2147483648 -> x >s -1  -> true if sign bit clear
7023     if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
7024       Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
7025       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
7026     }
7027   }
7028 
7029   // The folds in here may rely on wrapping flags and special constants, so
7030   // they can break up min/max idioms in some cases but not seemingly similar
7031   // patterns.
7032   // FIXME: It may be possible to enhance select folding to make this
7033   //        unnecessary. It may also be moot if we canonicalize to min/max
7034   //        intrinsics.
7035   if (Instruction *Res = foldICmpBinOp(I, Q))
7036     return Res;
7037 
7038   if (Instruction *Res = foldICmpInstWithConstant(I))
7039     return Res;
7040 
7041   // Try to match comparison as a sign bit test. Intentionally do this after
7042   // foldICmpInstWithConstant() to potentially let other folds to happen first.
7043   if (Instruction *New = foldSignBitTest(I))
7044     return New;
7045 
7046   if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
7047     return Res;
7048 
7049   if (Instruction *Res = foldICmpCommutative(I.getPredicate(), Op0, Op1, I))
7050     return Res;
7051   if (Instruction *Res =
7052           foldICmpCommutative(I.getSwappedPredicate(), Op1, Op0, I))
7053     return Res;
7054 
7055   // In case of a comparison with two select instructions having the same
7056   // condition, check whether one of the resulting branches can be simplified.
7057   // If so, just compare the other branch and select the appropriate result.
7058   // For example:
7059   //   %tmp1 = select i1 %cmp, i32 %y, i32 %x
7060   //   %tmp2 = select i1 %cmp, i32 %z, i32 %x
7061   //   %cmp2 = icmp slt i32 %tmp2, %tmp1
7062   // The icmp will result false for the false value of selects and the result
7063   // will depend upon the comparison of true values of selects if %cmp is
7064   // true. Thus, transform this into:
7065   //   %cmp = icmp slt i32 %y, %z
7066   //   %sel = select i1 %cond, i1 %cmp, i1 false
7067   // This handles similar cases to transform.
7068   {
7069     Value *Cond, *A, *B, *C, *D;
7070     if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
7071         match(Op1, m_Select(m_Specific(Cond), m_Value(C), m_Value(D))) &&
7072         (Op0->hasOneUse() || Op1->hasOneUse())) {
7073       // Check whether comparison of TrueValues can be simplified
7074       if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
7075         Value *NewICMP = Builder.CreateICmp(Pred, B, D);
7076         return SelectInst::Create(Cond, Res, NewICMP);
7077       }
7078       // Check whether comparison of FalseValues can be simplified
7079       if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
7080         Value *NewICMP = Builder.CreateICmp(Pred, A, C);
7081         return SelectInst::Create(Cond, NewICMP, Res);
7082       }
7083     }
7084   }
7085 
7086   // Try to optimize equality comparisons against alloca-based pointers.
7087   if (Op0->getType()->isPointerTy() && I.isEquality()) {
7088     assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
7089     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
7090       if (foldAllocaCmp(Alloca))
7091         return nullptr;
7092     if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
7093       if (foldAllocaCmp(Alloca))
7094         return nullptr;
7095   }
7096 
7097   if (Instruction *Res = foldICmpBitCast(I))
7098     return Res;
7099 
7100   // TODO: Hoist this above the min/max bailout.
7101   if (Instruction *R = foldICmpWithCastOp(I))
7102     return R;
7103 
7104   {
7105     Value *X, *Y;
7106     // Transform (X & ~Y) == 0 --> (X & Y) != 0
7107     // and       (X & ~Y) != 0 --> (X & Y) == 0
7108     // if A is a power of 2.
7109     if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
7110         match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, 0, &I) &&
7111         I.isEquality())
7112       return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
7113                           Op1);
7114 
7115     // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
7116     if (Op0->getType()->isIntOrIntVectorTy()) {
7117       bool ConsumesOp0, ConsumesOp1;
7118       if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
7119           isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
7120           (ConsumesOp0 || ConsumesOp1)) {
7121         Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
7122         Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
7123         assert(InvOp0 && InvOp1 &&
7124                "Mismatch between isFreeToInvert and getFreelyInverted");
7125         return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
7126       }
7127     }
7128 
7129     Instruction *AddI = nullptr;
7130     if (match(&I, m_UAddWithOverflow(m_Value(X), m_Value(Y),
7131                                      m_Instruction(AddI))) &&
7132         isa<IntegerType>(X->getType())) {
7133       Value *Result;
7134       Constant *Overflow;
7135       // m_UAddWithOverflow can match patterns that do not include  an explicit
7136       // "add" instruction, so check the opcode of the matched op.
7137       if (AddI->getOpcode() == Instruction::Add &&
7138           OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
7139                                 Result, Overflow)) {
7140         replaceInstUsesWith(*AddI, Result);
7141         eraseInstFromFunction(*AddI);
7142         return replaceInstUsesWith(I, Overflow);
7143       }
7144     }
7145 
7146     // (zext X) * (zext Y)  --> llvm.umul.with.overflow.
7147     if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
7148         match(Op1, m_APInt(C))) {
7149       if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
7150         return R;
7151     }
7152 
7153     // Signbit test folds
7154     // Fold (X u>> BitWidth - 1 Pred ZExt(i1))  -->  X s< 0 Pred i1
7155     // Fold (X s>> BitWidth - 1 Pred SExt(i1))  -->  X s< 0 Pred i1
7156     Instruction *ExtI;
7157     if ((I.isUnsigned() || I.isEquality()) &&
7158         match(Op1,
7159               m_CombineAnd(m_Instruction(ExtI), m_ZExtOrSExt(m_Value(Y)))) &&
7160         Y->getType()->getScalarSizeInBits() == 1 &&
7161         (Op0->hasOneUse() || Op1->hasOneUse())) {
7162       unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
7163       Instruction *ShiftI;
7164       if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
7165                                   m_Shr(m_Value(X), m_SpecificIntAllowUndef(
7166                                                         OpWidth - 1))))) {
7167         unsigned ExtOpc = ExtI->getOpcode();
7168         unsigned ShiftOpc = ShiftI->getOpcode();
7169         if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
7170             (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
7171           Value *SLTZero =
7172               Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
7173           Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
7174           return replaceInstUsesWith(I, Cmp);
7175         }
7176       }
7177     }
7178   }
7179 
7180   if (Instruction *Res = foldICmpEquality(I))
7181     return Res;
7182 
7183   if (Instruction *Res = foldICmpPow2Test(I, Builder))
7184     return Res;
7185 
7186   if (Instruction *Res = foldICmpOfUAddOv(I))
7187     return Res;
7188 
7189   // The 'cmpxchg' instruction returns an aggregate containing the old value and
7190   // an i1 which indicates whether or not we successfully did the swap.
7191   //
7192   // Replace comparisons between the old value and the expected value with the
7193   // indicator that 'cmpxchg' returns.
7194   //
7195   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
7196   // spuriously fail.  In those cases, the old value may equal the expected
7197   // value but it is possible for the swap to not occur.
7198   if (I.getPredicate() == ICmpInst::ICMP_EQ)
7199     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
7200       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
7201         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
7202             !ACXI->isWeak())
7203           return ExtractValueInst::Create(ACXI, 1);
7204 
7205   if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
7206     return Res;
7207 
7208   if (I.getType()->isVectorTy())
7209     if (Instruction *Res = foldVectorCmp(I, Builder))
7210       return Res;
7211 
7212   if (Instruction *Res = foldICmpInvariantGroup(I))
7213     return Res;
7214 
7215   if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
7216     return Res;
7217 
7218   return Changed ? &I : nullptr;
7219 }
7220 
7221 /// Fold fcmp ([us]itofp x, cst) if possible.
7222 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
7223                                                     Instruction *LHSI,
7224                                                     Constant *RHSC) {
7225   if (!isa<ConstantFP>(RHSC)) return nullptr;
7226   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
7227 
7228   // Get the width of the mantissa.  We don't want to hack on conversions that
7229   // might lose information from the integer, e.g. "i64 -> float"
7230   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
7231   if (MantissaWidth == -1) return nullptr;  // Unknown.
7232 
7233   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
7234 
7235   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
7236 
7237   if (I.isEquality()) {
7238     FCmpInst::Predicate P = I.getPredicate();
7239     bool IsExact = false;
7240     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
7241     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
7242 
7243     // If the floating point constant isn't an integer value, we know if we will
7244     // ever compare equal / not equal to it.
7245     if (!IsExact) {
7246       // TODO: Can never be -0.0 and other non-representable values
7247       APFloat RHSRoundInt(RHS);
7248       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
7249       if (RHS != RHSRoundInt) {
7250         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
7251           return replaceInstUsesWith(I, Builder.getFalse());
7252 
7253         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
7254         return replaceInstUsesWith(I, Builder.getTrue());
7255       }
7256     }
7257 
7258     // TODO: If the constant is exactly representable, is it always OK to do
7259     // equality compares as integer?
7260   }
7261 
7262   // Check to see that the input is converted from an integer type that is small
7263   // enough that preserves all bits.  TODO: check here for "known" sign bits.
7264   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
7265   unsigned InputSize = IntTy->getScalarSizeInBits();
7266 
7267   // Following test does NOT adjust InputSize downwards for signed inputs,
7268   // because the most negative value still requires all the mantissa bits
7269   // to distinguish it from one less than that value.
7270   if ((int)InputSize > MantissaWidth) {
7271     // Conversion would lose accuracy. Check if loss can impact comparison.
7272     int Exp = ilogb(RHS);
7273     if (Exp == APFloat::IEK_Inf) {
7274       int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
7275       if (MaxExponent < (int)InputSize - !LHSUnsigned)
7276         // Conversion could create infinity.
7277         return nullptr;
7278     } else {
7279       // Note that if RHS is zero or NaN, then Exp is negative
7280       // and first condition is trivially false.
7281       if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
7282         // Conversion could affect comparison.
7283         return nullptr;
7284     }
7285   }
7286 
7287   // Otherwise, we can potentially simplify the comparison.  We know that it
7288   // will always come through as an integer value and we know the constant is
7289   // not a NAN (it would have been previously simplified).
7290   assert(!RHS.isNaN() && "NaN comparison not already folded!");
7291 
7292   ICmpInst::Predicate Pred;
7293   switch (I.getPredicate()) {
7294   default: llvm_unreachable("Unexpected predicate!");
7295   case FCmpInst::FCMP_UEQ:
7296   case FCmpInst::FCMP_OEQ:
7297     Pred = ICmpInst::ICMP_EQ;
7298     break;
7299   case FCmpInst::FCMP_UGT:
7300   case FCmpInst::FCMP_OGT:
7301     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
7302     break;
7303   case FCmpInst::FCMP_UGE:
7304   case FCmpInst::FCMP_OGE:
7305     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
7306     break;
7307   case FCmpInst::FCMP_ULT:
7308   case FCmpInst::FCMP_OLT:
7309     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
7310     break;
7311   case FCmpInst::FCMP_ULE:
7312   case FCmpInst::FCMP_OLE:
7313     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
7314     break;
7315   case FCmpInst::FCMP_UNE:
7316   case FCmpInst::FCMP_ONE:
7317     Pred = ICmpInst::ICMP_NE;
7318     break;
7319   case FCmpInst::FCMP_ORD:
7320     return replaceInstUsesWith(I, Builder.getTrue());
7321   case FCmpInst::FCMP_UNO:
7322     return replaceInstUsesWith(I, Builder.getFalse());
7323   }
7324 
7325   // Now we know that the APFloat is a normal number, zero or inf.
7326 
7327   // See if the FP constant is too large for the integer.  For example,
7328   // comparing an i8 to 300.0.
7329   unsigned IntWidth = IntTy->getScalarSizeInBits();
7330 
7331   if (!LHSUnsigned) {
7332     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
7333     // and large values.
7334     APFloat SMax(RHS.getSemantics());
7335     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
7336                           APFloat::rmNearestTiesToEven);
7337     if (SMax < RHS) { // smax < 13123.0
7338       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
7339           Pred == ICmpInst::ICMP_SLE)
7340         return replaceInstUsesWith(I, Builder.getTrue());
7341       return replaceInstUsesWith(I, Builder.getFalse());
7342     }
7343   } else {
7344     // If the RHS value is > UnsignedMax, fold the comparison. This handles
7345     // +INF and large values.
7346     APFloat UMax(RHS.getSemantics());
7347     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
7348                           APFloat::rmNearestTiesToEven);
7349     if (UMax < RHS) { // umax < 13123.0
7350       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
7351           Pred == ICmpInst::ICMP_ULE)
7352         return replaceInstUsesWith(I, Builder.getTrue());
7353       return replaceInstUsesWith(I, Builder.getFalse());
7354     }
7355   }
7356 
7357   if (!LHSUnsigned) {
7358     // See if the RHS value is < SignedMin.
7359     APFloat SMin(RHS.getSemantics());
7360     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
7361                           APFloat::rmNearestTiesToEven);
7362     if (SMin > RHS) { // smin > 12312.0
7363       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
7364           Pred == ICmpInst::ICMP_SGE)
7365         return replaceInstUsesWith(I, Builder.getTrue());
7366       return replaceInstUsesWith(I, Builder.getFalse());
7367     }
7368   } else {
7369     // See if the RHS value is < UnsignedMin.
7370     APFloat UMin(RHS.getSemantics());
7371     UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
7372                           APFloat::rmNearestTiesToEven);
7373     if (UMin > RHS) { // umin > 12312.0
7374       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
7375           Pred == ICmpInst::ICMP_UGE)
7376         return replaceInstUsesWith(I, Builder.getTrue());
7377       return replaceInstUsesWith(I, Builder.getFalse());
7378     }
7379   }
7380 
7381   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
7382   // [0, UMAX], but it may still be fractional. Check whether this is the case
7383   // using the IsExact flag.
7384   // Don't do this for zero, because -0.0 is not fractional.
7385   APSInt RHSInt(IntWidth, LHSUnsigned);
7386   bool IsExact;
7387   RHS.convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
7388   if (!RHS.isZero()) {
7389     if (!IsExact) {
7390       // If we had a comparison against a fractional value, we have to adjust
7391       // the compare predicate and sometimes the value.  RHSC is rounded towards
7392       // zero at this point.
7393       switch (Pred) {
7394       default: llvm_unreachable("Unexpected integer comparison!");
7395       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
7396         return replaceInstUsesWith(I, Builder.getTrue());
7397       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
7398         return replaceInstUsesWith(I, Builder.getFalse());
7399       case ICmpInst::ICMP_ULE:
7400         // (float)int <= 4.4   --> int <= 4
7401         // (float)int <= -4.4  --> false
7402         if (RHS.isNegative())
7403           return replaceInstUsesWith(I, Builder.getFalse());
7404         break;
7405       case ICmpInst::ICMP_SLE:
7406         // (float)int <= 4.4   --> int <= 4
7407         // (float)int <= -4.4  --> int < -4
7408         if (RHS.isNegative())
7409           Pred = ICmpInst::ICMP_SLT;
7410         break;
7411       case ICmpInst::ICMP_ULT:
7412         // (float)int < -4.4   --> false
7413         // (float)int < 4.4    --> int <= 4
7414         if (RHS.isNegative())
7415           return replaceInstUsesWith(I, Builder.getFalse());
7416         Pred = ICmpInst::ICMP_ULE;
7417         break;
7418       case ICmpInst::ICMP_SLT:
7419         // (float)int < -4.4   --> int < -4
7420         // (float)int < 4.4    --> int <= 4
7421         if (!RHS.isNegative())
7422           Pred = ICmpInst::ICMP_SLE;
7423         break;
7424       case ICmpInst::ICMP_UGT:
7425         // (float)int > 4.4    --> int > 4
7426         // (float)int > -4.4   --> true
7427         if (RHS.isNegative())
7428           return replaceInstUsesWith(I, Builder.getTrue());
7429         break;
7430       case ICmpInst::ICMP_SGT:
7431         // (float)int > 4.4    --> int > 4
7432         // (float)int > -4.4   --> int >= -4
7433         if (RHS.isNegative())
7434           Pred = ICmpInst::ICMP_SGE;
7435         break;
7436       case ICmpInst::ICMP_UGE:
7437         // (float)int >= -4.4   --> true
7438         // (float)int >= 4.4    --> int > 4
7439         if (RHS.isNegative())
7440           return replaceInstUsesWith(I, Builder.getTrue());
7441         Pred = ICmpInst::ICMP_UGT;
7442         break;
7443       case ICmpInst::ICMP_SGE:
7444         // (float)int >= -4.4   --> int >= -4
7445         // (float)int >= 4.4    --> int > 4
7446         if (!RHS.isNegative())
7447           Pred = ICmpInst::ICMP_SGT;
7448         break;
7449       }
7450     }
7451   }
7452 
7453   // Lower this FP comparison into an appropriate integer version of the
7454   // comparison.
7455   return new ICmpInst(Pred, LHSI->getOperand(0), Builder.getInt(RHSInt));
7456 }
7457 
7458 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
7459 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
7460                                               Constant *RHSC) {
7461   // When C is not 0.0 and infinities are not allowed:
7462   // (C / X) < 0.0 is a sign-bit test of X
7463   // (C / X) < 0.0 --> X < 0.0 (if C is positive)
7464   // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
7465   //
7466   // Proof:
7467   // Multiply (C / X) < 0.0 by X * X / C.
7468   // - X is non zero, if it is the flag 'ninf' is violated.
7469   // - C defines the sign of X * X * C. Thus it also defines whether to swap
7470   //   the predicate. C is also non zero by definition.
7471   //
7472   // Thus X * X / C is non zero and the transformation is valid. [qed]
7473 
7474   FCmpInst::Predicate Pred = I.getPredicate();
7475 
7476   // Check that predicates are valid.
7477   if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
7478       (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
7479     return nullptr;
7480 
7481   // Check that RHS operand is zero.
7482   if (!match(RHSC, m_AnyZeroFP()))
7483     return nullptr;
7484 
7485   // Check fastmath flags ('ninf').
7486   if (!LHSI->hasNoInfs() || !I.hasNoInfs())
7487     return nullptr;
7488 
7489   // Check the properties of the dividend. It must not be zero to avoid a
7490   // division by zero (see Proof).
7491   const APFloat *C;
7492   if (!match(LHSI->getOperand(0), m_APFloat(C)))
7493     return nullptr;
7494 
7495   if (C->isZero())
7496     return nullptr;
7497 
7498   // Get swapped predicate if necessary.
7499   if (C->isNegative())
7500     Pred = I.getSwappedPredicate();
7501 
7502   return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
7503 }
7504 
7505 /// Optimize fabs(X) compared with zero.
7506 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
7507   Value *X;
7508   if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
7509     return nullptr;
7510 
7511   const APFloat *C;
7512   if (!match(I.getOperand(1), m_APFloat(C)))
7513     return nullptr;
7514 
7515   if (!C->isPosZero()) {
7516     if (!C->isSmallestNormalized())
7517       return nullptr;
7518 
7519     const Function *F = I.getFunction();
7520     DenormalMode Mode = F->getDenormalMode(C->getSemantics());
7521     if (Mode.Input == DenormalMode::PreserveSign ||
7522         Mode.Input == DenormalMode::PositiveZero) {
7523 
7524       auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7525         Constant *Zero = ConstantFP::getZero(X->getType());
7526         return new FCmpInst(P, X, Zero, "", I);
7527       };
7528 
7529       switch (I.getPredicate()) {
7530       case FCmpInst::FCMP_OLT:
7531         // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
7532         return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
7533       case FCmpInst::FCMP_UGE:
7534         // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
7535         return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
7536       case FCmpInst::FCMP_OGE:
7537         // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
7538         return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
7539       case FCmpInst::FCMP_ULT:
7540         // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
7541         return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
7542       default:
7543         break;
7544       }
7545     }
7546 
7547     return nullptr;
7548   }
7549 
7550   auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
7551     I->setPredicate(P);
7552     return IC.replaceOperand(*I, 0, X);
7553   };
7554 
7555   switch (I.getPredicate()) {
7556   case FCmpInst::FCMP_UGE:
7557   case FCmpInst::FCMP_OLT:
7558     // fabs(X) >= 0.0 --> true
7559     // fabs(X) <  0.0 --> false
7560     llvm_unreachable("fcmp should have simplified");
7561 
7562   case FCmpInst::FCMP_OGT:
7563     // fabs(X) > 0.0 --> X != 0.0
7564     return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
7565 
7566   case FCmpInst::FCMP_UGT:
7567     // fabs(X) u> 0.0 --> X u!= 0.0
7568     return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
7569 
7570   case FCmpInst::FCMP_OLE:
7571     // fabs(X) <= 0.0 --> X == 0.0
7572     return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
7573 
7574   case FCmpInst::FCMP_ULE:
7575     // fabs(X) u<= 0.0 --> X u== 0.0
7576     return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
7577 
7578   case FCmpInst::FCMP_OGE:
7579     // fabs(X) >= 0.0 --> !isnan(X)
7580     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7581     return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
7582 
7583   case FCmpInst::FCMP_ULT:
7584     // fabs(X) u< 0.0 --> isnan(X)
7585     assert(!I.hasNoNaNs() && "fcmp should have simplified");
7586     return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
7587 
7588   case FCmpInst::FCMP_OEQ:
7589   case FCmpInst::FCMP_UEQ:
7590   case FCmpInst::FCMP_ONE:
7591   case FCmpInst::FCMP_UNE:
7592   case FCmpInst::FCMP_ORD:
7593   case FCmpInst::FCMP_UNO:
7594     // Look through the fabs() because it doesn't change anything but the sign.
7595     // fabs(X) == 0.0 --> X == 0.0,
7596     // fabs(X) != 0.0 --> X != 0.0
7597     // isnan(fabs(X)) --> isnan(X)
7598     // !isnan(fabs(X) --> !isnan(X)
7599     return replacePredAndOp0(&I, I.getPredicate(), X);
7600 
7601   default:
7602     return nullptr;
7603   }
7604 }
7605 
7606 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
7607   CmpInst::Predicate Pred = I.getPredicate();
7608   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7609 
7610   // Canonicalize fneg as Op1.
7611   if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
7612     std::swap(Op0, Op1);
7613     Pred = I.getSwappedPredicate();
7614   }
7615 
7616   if (!match(Op1, m_FNeg(m_Specific(Op0))))
7617     return nullptr;
7618 
7619   // Replace the negated operand with 0.0:
7620   // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
7621   Constant *Zero = ConstantFP::getZero(Op0->getType());
7622   return new FCmpInst(Pred, Op0, Zero, "", &I);
7623 }
7624 
7625 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
7626   bool Changed = false;
7627 
7628   /// Orders the operands of the compare so that they are listed from most
7629   /// complex to least complex.  This puts constants before unary operators,
7630   /// before binary operators.
7631   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
7632     I.swapOperands();
7633     Changed = true;
7634   }
7635 
7636   const CmpInst::Predicate Pred = I.getPredicate();
7637   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7638   if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
7639                                   SQ.getWithInstruction(&I)))
7640     return replaceInstUsesWith(I, V);
7641 
7642   // Simplify 'fcmp pred X, X'
7643   Type *OpType = Op0->getType();
7644   assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
7645   if (Op0 == Op1) {
7646     switch (Pred) {
7647       default: break;
7648     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
7649     case FCmpInst::FCMP_ULT:    // True if unordered or less than
7650     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
7651     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
7652       // Canonicalize these to be 'fcmp uno %X, 0.0'.
7653       I.setPredicate(FCmpInst::FCMP_UNO);
7654       I.setOperand(1, Constant::getNullValue(OpType));
7655       return &I;
7656 
7657     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
7658     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
7659     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
7660     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
7661       // Canonicalize these to be 'fcmp ord %X, 0.0'.
7662       I.setPredicate(FCmpInst::FCMP_ORD);
7663       I.setOperand(1, Constant::getNullValue(OpType));
7664       return &I;
7665     }
7666   }
7667 
7668   // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
7669   // then canonicalize the operand to 0.0.
7670   if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
7671     if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, DL, &TLI, 0,
7672                                                       &AC, &I, &DT))
7673       return replaceOperand(I, 0, ConstantFP::getZero(OpType));
7674 
7675     if (!match(Op1, m_PosZeroFP()) &&
7676         isKnownNeverNaN(Op1, DL, &TLI, 0, &AC, &I, &DT))
7677       return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7678   }
7679 
7680   // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
7681   Value *X, *Y;
7682   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
7683     return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
7684 
7685   if (Instruction *R = foldFCmpFNegCommonOp(I))
7686     return R;
7687 
7688   // Test if the FCmpInst instruction is used exclusively by a select as
7689   // part of a minimum or maximum operation. If so, refrain from doing
7690   // any other folding. This helps out other analyses which understand
7691   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7692   // and CodeGen. And in this case, at least one of the comparison
7693   // operands has at least one user besides the compare (the select),
7694   // which would often largely negate the benefit of folding anyway.
7695   if (I.hasOneUse())
7696     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7697       Value *A, *B;
7698       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
7699       if (SPR.Flavor != SPF_UNKNOWN)
7700         return nullptr;
7701     }
7702 
7703   // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
7704   // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
7705   if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
7706     return replaceOperand(I, 1, ConstantFP::getZero(OpType));
7707 
7708   // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
7709   // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
7710   if (match(Op1, m_PosZeroFP()) &&
7711       match(Op0, m_OneUse(m_BitCast(m_Value(X)))) &&
7712       X->getType()->isVectorTy() == OpType->isVectorTy() &&
7713       X->getType()->getScalarSizeInBits() == OpType->getScalarSizeInBits()) {
7714     ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
7715     if (Pred == FCmpInst::FCMP_OEQ)
7716       IntPred = ICmpInst::ICMP_EQ;
7717     else if (Pred == FCmpInst::FCMP_UNE)
7718       IntPred = ICmpInst::ICMP_NE;
7719 
7720     if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
7721       Type *IntTy = X->getType();
7722       const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
7723       Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
7724       return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
7725     }
7726   }
7727 
7728   // Handle fcmp with instruction LHS and constant RHS.
7729   Instruction *LHSI;
7730   Constant *RHSC;
7731   if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
7732     switch (LHSI->getOpcode()) {
7733     case Instruction::PHI:
7734       if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
7735         return NV;
7736       break;
7737     case Instruction::SIToFP:
7738     case Instruction::UIToFP:
7739       if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
7740         return NV;
7741       break;
7742     case Instruction::FDiv:
7743       if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
7744         return NV;
7745       break;
7746     case Instruction::Load:
7747       if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
7748         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7749           if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
7750                   cast<LoadInst>(LHSI), GEP, GV, I))
7751             return Res;
7752       break;
7753   }
7754   }
7755 
7756   if (Instruction *R = foldFabsWithFcmpZero(I, *this))
7757     return R;
7758 
7759   if (match(Op0, m_FNeg(m_Value(X)))) {
7760     // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
7761     Constant *C;
7762     if (match(Op1, m_Constant(C)))
7763       if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
7764         return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
7765   }
7766 
7767   if (match(Op0, m_FPExt(m_Value(X)))) {
7768     // fcmp (fpext X), (fpext Y) -> fcmp X, Y
7769     if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
7770       return new FCmpInst(Pred, X, Y, "", &I);
7771 
7772     const APFloat *C;
7773     if (match(Op1, m_APFloat(C))) {
7774       const fltSemantics &FPSem =
7775           X->getType()->getScalarType()->getFltSemantics();
7776       bool Lossy;
7777       APFloat TruncC = *C;
7778       TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
7779 
7780       if (Lossy) {
7781         // X can't possibly equal the higher-precision constant, so reduce any
7782         // equality comparison.
7783         // TODO: Other predicates can be handled via getFCmpCode().
7784         switch (Pred) {
7785         case FCmpInst::FCMP_OEQ:
7786           // X is ordered and equal to an impossible constant --> false
7787           return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
7788         case FCmpInst::FCMP_ONE:
7789           // X is ordered and not equal to an impossible constant --> ordered
7790           return new FCmpInst(FCmpInst::FCMP_ORD, X,
7791                               ConstantFP::getZero(X->getType()));
7792         case FCmpInst::FCMP_UEQ:
7793           // X is unordered or equal to an impossible constant --> unordered
7794           return new FCmpInst(FCmpInst::FCMP_UNO, X,
7795                               ConstantFP::getZero(X->getType()));
7796         case FCmpInst::FCMP_UNE:
7797           // X is unordered or not equal to an impossible constant --> true
7798           return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
7799         default:
7800           break;
7801         }
7802       }
7803 
7804       // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
7805       // Avoid lossy conversions and denormals.
7806       // Zero is a special case that's OK to convert.
7807       APFloat Fabs = TruncC;
7808       Fabs.clearSign();
7809       if (!Lossy &&
7810           (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
7811         Constant *NewC = ConstantFP::get(X->getType(), TruncC);
7812         return new FCmpInst(Pred, X, NewC, "", &I);
7813       }
7814     }
7815   }
7816 
7817   // Convert a sign-bit test of an FP value into a cast and integer compare.
7818   // TODO: Simplify if the copysign constant is 0.0 or NaN.
7819   // TODO: Handle non-zero compare constants.
7820   // TODO: Handle other predicates.
7821   const APFloat *C;
7822   if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
7823                                                            m_Value(X)))) &&
7824       match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
7825     Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
7826     if (auto *VecTy = dyn_cast<VectorType>(OpType))
7827       IntType = VectorType::get(IntType, VecTy->getElementCount());
7828 
7829     // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
7830     if (Pred == FCmpInst::FCMP_OLT) {
7831       Value *IntX = Builder.CreateBitCast(X, IntType);
7832       return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
7833                           ConstantInt::getNullValue(IntType));
7834     }
7835   }
7836 
7837   {
7838     Value *CanonLHS = nullptr, *CanonRHS = nullptr;
7839     match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
7840     match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
7841 
7842     // (canonicalize(x) == x) => (x == x)
7843     if (CanonLHS == Op1)
7844       return new FCmpInst(Pred, Op1, Op1, "", &I);
7845 
7846     // (x == canonicalize(x)) => (x == x)
7847     if (CanonRHS == Op0)
7848       return new FCmpInst(Pred, Op0, Op0, "", &I);
7849 
7850     // (canonicalize(x) == canonicalize(y)) => (x == y)
7851     if (CanonLHS && CanonRHS)
7852       return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
7853   }
7854 
7855   if (I.getType()->isVectorTy())
7856     if (Instruction *Res = foldVectorCmp(I, Builder))
7857       return Res;
7858 
7859   return Changed ? &I : nullptr;
7860 }
7861