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/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/ConstantFolding.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/KnownBits.h"
27 
28 using namespace llvm;
29 using namespace PatternMatch;
30 
31 #define DEBUG_TYPE "instcombine"
32 
33 // How many times is a select replaced by one of its operands?
34 STATISTIC(NumSel, "Number of select opts");
35 
36 
37 /// Compute Result = In1+In2, returning true if the result overflowed for this
38 /// type.
39 static bool addWithOverflow(APInt &Result, const APInt &In1,
40                             const APInt &In2, bool IsSigned = false) {
41   bool Overflow;
42   if (IsSigned)
43     Result = In1.sadd_ov(In2, Overflow);
44   else
45     Result = In1.uadd_ov(In2, Overflow);
46 
47   return Overflow;
48 }
49 
50 /// Compute Result = In1-In2, returning true if the result overflowed for this
51 /// type.
52 static bool subWithOverflow(APInt &Result, const APInt &In1,
53                             const APInt &In2, bool IsSigned = false) {
54   bool Overflow;
55   if (IsSigned)
56     Result = In1.ssub_ov(In2, Overflow);
57   else
58     Result = In1.usub_ov(In2, Overflow);
59 
60   return Overflow;
61 }
62 
63 /// Given an icmp instruction, return true if any use of this comparison is a
64 /// branch on sign bit comparison.
65 static bool hasBranchUse(ICmpInst &I) {
66   for (auto *U : I.users())
67     if (isa<BranchInst>(U))
68       return true;
69   return false;
70 }
71 
72 /// Given an exploded icmp instruction, return true if the comparison only
73 /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
74 /// result of the comparison is true when the input value is signed.
75 static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
76                            bool &TrueIfSigned) {
77   switch (Pred) {
78   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
79     TrueIfSigned = true;
80     return RHS.isNullValue();
81   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
82     TrueIfSigned = true;
83     return RHS.isAllOnesValue();
84   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
85     TrueIfSigned = false;
86     return RHS.isAllOnesValue();
87   case ICmpInst::ICMP_UGT:
88     // True if LHS u> RHS and RHS == high-bit-mask - 1
89     TrueIfSigned = true;
90     return RHS.isMaxSignedValue();
91   case ICmpInst::ICMP_UGE:
92     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
93     TrueIfSigned = true;
94     return RHS.isSignMask();
95   default:
96     return false;
97   }
98 }
99 
100 /// Returns true if the exploded icmp can be expressed as a signed comparison
101 /// to zero and updates the predicate accordingly.
102 /// The signedness of the comparison is preserved.
103 /// TODO: Refactor with decomposeBitTestICmp()?
104 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
105   if (!ICmpInst::isSigned(Pred))
106     return false;
107 
108   if (C.isNullValue())
109     return ICmpInst::isRelational(Pred);
110 
111   if (C.isOneValue()) {
112     if (Pred == ICmpInst::ICMP_SLT) {
113       Pred = ICmpInst::ICMP_SLE;
114       return true;
115     }
116   } else if (C.isAllOnesValue()) {
117     if (Pred == ICmpInst::ICMP_SGT) {
118       Pred = ICmpInst::ICMP_SGE;
119       return true;
120     }
121   }
122 
123   return false;
124 }
125 
126 /// Given a signed integer type and a set of known zero and one bits, compute
127 /// the maximum and minimum values that could have the specified known zero and
128 /// known one bits, returning them in Min/Max.
129 /// TODO: Move to method on KnownBits struct?
130 static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known,
131                                                    APInt &Min, APInt &Max) {
132   assert(Known.getBitWidth() == Min.getBitWidth() &&
133          Known.getBitWidth() == Max.getBitWidth() &&
134          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
135   APInt UnknownBits = ~(Known.Zero|Known.One);
136 
137   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
138   // bit if it is unknown.
139   Min = Known.One;
140   Max = Known.One|UnknownBits;
141 
142   if (UnknownBits.isNegative()) { // Sign bit is unknown
143     Min.setSignBit();
144     Max.clearSignBit();
145   }
146 }
147 
148 /// Given an unsigned integer type and a set of known zero and one bits, compute
149 /// the maximum and minimum values that could have the specified known zero and
150 /// known one bits, returning them in Min/Max.
151 /// TODO: Move to method on KnownBits struct?
152 static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known,
153                                                      APInt &Min, APInt &Max) {
154   assert(Known.getBitWidth() == Min.getBitWidth() &&
155          Known.getBitWidth() == Max.getBitWidth() &&
156          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
157   APInt UnknownBits = ~(Known.Zero|Known.One);
158 
159   // The minimum value is when the unknown bits are all zeros.
160   Min = Known.One;
161   // The maximum value is when the unknown bits are all ones.
162   Max = Known.One|UnknownBits;
163 }
164 
165 /// This is called when we see this pattern:
166 ///   cmp pred (load (gep GV, ...)), cmpcst
167 /// where GV is a global variable with a constant initializer. Try to simplify
168 /// this into some simple computation that does not need the load. For example
169 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
170 ///
171 /// If AndCst is non-null, then the loaded value is masked with that constant
172 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
173 Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
174                                                         GlobalVariable *GV,
175                                                         CmpInst &ICI,
176                                                         ConstantInt *AndCst) {
177   Constant *Init = GV->getInitializer();
178   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
179     return nullptr;
180 
181   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
182   // Don't blow up on huge arrays.
183   if (ArrayElementCount > MaxArraySizeForCombine)
184     return nullptr;
185 
186   // There are many forms of this optimization we can handle, for now, just do
187   // the simple index into a single-dimensional array.
188   //
189   // Require: GEP GV, 0, i {{, constant indices}}
190   if (GEP->getNumOperands() < 3 ||
191       !isa<ConstantInt>(GEP->getOperand(1)) ||
192       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
193       isa<Constant>(GEP->getOperand(2)))
194     return nullptr;
195 
196   // Check that indices after the variable are constants and in-range for the
197   // type they index.  Collect the indices.  This is typically for arrays of
198   // structs.
199   SmallVector<unsigned, 4> LaterIndices;
200 
201   Type *EltTy = Init->getType()->getArrayElementType();
202   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
203     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
204     if (!Idx) return nullptr;  // Variable index.
205 
206     uint64_t IdxVal = Idx->getZExtValue();
207     if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
208 
209     if (StructType *STy = dyn_cast<StructType>(EltTy))
210       EltTy = STy->getElementType(IdxVal);
211     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
212       if (IdxVal >= ATy->getNumElements()) return nullptr;
213       EltTy = ATy->getElementType();
214     } else {
215       return nullptr; // Unknown type.
216     }
217 
218     LaterIndices.push_back(IdxVal);
219   }
220 
221   enum { Overdefined = -3, Undefined = -2 };
222 
223   // Variables for our state machines.
224 
225   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
226   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
227   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
228   // undefined, otherwise set to the first true element.  SecondTrueElement is
229   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
230   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
231 
232   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
233   // form "i != 47 & i != 87".  Same state transitions as for true elements.
234   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
235 
236   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
237   /// define a state machine that triggers for ranges of values that the index
238   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
239   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
240   /// index in the range (inclusive).  We use -2 for undefined here because we
241   /// use relative comparisons and don't want 0-1 to match -1.
242   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
243 
244   // MagicBitvector - This is a magic bitvector where we set a bit if the
245   // comparison is true for element 'i'.  If there are 64 elements or less in
246   // the array, this will fully represent all the comparison results.
247   uint64_t MagicBitvector = 0;
248 
249   // Scan the array and see if one of our patterns matches.
250   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
251   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
252     Constant *Elt = Init->getAggregateElement(i);
253     if (!Elt) return nullptr;
254 
255     // If this is indexing an array of structures, get the structure element.
256     if (!LaterIndices.empty())
257       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
258 
259     // If the element is masked, handle it.
260     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
261 
262     // Find out if the comparison would be true or false for the i'th element.
263     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
264                                                   CompareRHS, DL, &TLI);
265     // If the result is undef for this element, ignore it.
266     if (isa<UndefValue>(C)) {
267       // Extend range state machines to cover this element in case there is an
268       // undef in the middle of the range.
269       if (TrueRangeEnd == (int)i-1)
270         TrueRangeEnd = i;
271       if (FalseRangeEnd == (int)i-1)
272         FalseRangeEnd = i;
273       continue;
274     }
275 
276     // If we can't compute the result for any of the elements, we have to give
277     // up evaluating the entire conditional.
278     if (!isa<ConstantInt>(C)) return nullptr;
279 
280     // Otherwise, we know if the comparison is true or false for this element,
281     // update our state machines.
282     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
283 
284     // State machine for single/double/range index comparison.
285     if (IsTrueForElt) {
286       // Update the TrueElement state machine.
287       if (FirstTrueElement == Undefined)
288         FirstTrueElement = TrueRangeEnd = i;  // First true element.
289       else {
290         // Update double-compare state machine.
291         if (SecondTrueElement == Undefined)
292           SecondTrueElement = i;
293         else
294           SecondTrueElement = Overdefined;
295 
296         // Update range state machine.
297         if (TrueRangeEnd == (int)i-1)
298           TrueRangeEnd = i;
299         else
300           TrueRangeEnd = Overdefined;
301       }
302     } else {
303       // Update the FalseElement state machine.
304       if (FirstFalseElement == Undefined)
305         FirstFalseElement = FalseRangeEnd = i; // First false element.
306       else {
307         // Update double-compare state machine.
308         if (SecondFalseElement == Undefined)
309           SecondFalseElement = i;
310         else
311           SecondFalseElement = Overdefined;
312 
313         // Update range state machine.
314         if (FalseRangeEnd == (int)i-1)
315           FalseRangeEnd = i;
316         else
317           FalseRangeEnd = Overdefined;
318       }
319     }
320 
321     // If this element is in range, update our magic bitvector.
322     if (i < 64 && IsTrueForElt)
323       MagicBitvector |= 1ULL << i;
324 
325     // If all of our states become overdefined, bail out early.  Since the
326     // predicate is expensive, only check it every 8 elements.  This is only
327     // really useful for really huge arrays.
328     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
329         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
330         FalseRangeEnd == Overdefined)
331       return nullptr;
332   }
333 
334   // Now that we've scanned the entire array, emit our new comparison(s).  We
335   // order the state machines in complexity of the generated code.
336   Value *Idx = GEP->getOperand(2);
337 
338   // If the index is larger than the pointer size of the target, truncate the
339   // index down like the GEP would do implicitly.  We don't have to do this for
340   // an inbounds GEP because the index can't be out of range.
341   if (!GEP->isInBounds()) {
342     Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
343     unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
344     if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
345       Idx = Builder.CreateTrunc(Idx, IntPtrTy);
346   }
347 
348   // If the comparison is only true for one or two elements, emit direct
349   // comparisons.
350   if (SecondTrueElement != Overdefined) {
351     // None true -> false.
352     if (FirstTrueElement == Undefined)
353       return replaceInstUsesWith(ICI, Builder.getFalse());
354 
355     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
356 
357     // True for one element -> 'i == 47'.
358     if (SecondTrueElement == Undefined)
359       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
360 
361     // True for two elements -> 'i == 47 | i == 72'.
362     Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
363     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
364     Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
365     return BinaryOperator::CreateOr(C1, C2);
366   }
367 
368   // If the comparison is only false for one or two elements, emit direct
369   // comparisons.
370   if (SecondFalseElement != Overdefined) {
371     // None false -> true.
372     if (FirstFalseElement == Undefined)
373       return replaceInstUsesWith(ICI, Builder.getTrue());
374 
375     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
376 
377     // False for one element -> 'i != 47'.
378     if (SecondFalseElement == Undefined)
379       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
380 
381     // False for two elements -> 'i != 47 & i != 72'.
382     Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
383     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
384     Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
385     return BinaryOperator::CreateAnd(C1, C2);
386   }
387 
388   // If the comparison can be replaced with a range comparison for the elements
389   // where it is true, emit the range check.
390   if (TrueRangeEnd != Overdefined) {
391     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
392 
393     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
394     if (FirstTrueElement) {
395       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
396       Idx = Builder.CreateAdd(Idx, Offs);
397     }
398 
399     Value *End = ConstantInt::get(Idx->getType(),
400                                   TrueRangeEnd-FirstTrueElement+1);
401     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
402   }
403 
404   // False range check.
405   if (FalseRangeEnd != Overdefined) {
406     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
407     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
408     if (FirstFalseElement) {
409       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
410       Idx = Builder.CreateAdd(Idx, Offs);
411     }
412 
413     Value *End = ConstantInt::get(Idx->getType(),
414                                   FalseRangeEnd-FirstFalseElement);
415     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
416   }
417 
418   // If a magic bitvector captures the entire comparison state
419   // of this load, replace it with computation that does:
420   //   ((magic_cst >> i) & 1) != 0
421   {
422     Type *Ty = nullptr;
423 
424     // Look for an appropriate type:
425     // - The type of Idx if the magic fits
426     // - The smallest fitting legal type
427     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
428       Ty = Idx->getType();
429     else
430       Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
431 
432     if (Ty) {
433       Value *V = Builder.CreateIntCast(Idx, Ty, false);
434       V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
435       V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
436       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
437     }
438   }
439 
440   return nullptr;
441 }
442 
443 /// Return a value that can be used to compare the *offset* implied by a GEP to
444 /// zero. For example, if we have &A[i], we want to return 'i' for
445 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
446 /// are involved. The above expression would also be legal to codegen as
447 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
448 /// This latter form is less amenable to optimization though, and we are allowed
449 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
450 ///
451 /// If we can't emit an optimized form for this expression, this returns null.
452 ///
453 static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
454                                           const DataLayout &DL) {
455   gep_type_iterator GTI = gep_type_begin(GEP);
456 
457   // Check to see if this gep only has a single variable index.  If so, and if
458   // any constant indices are a multiple of its scale, then we can compute this
459   // in terms of the scale of the variable index.  For example, if the GEP
460   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
461   // because the expression will cross zero at the same point.
462   unsigned i, e = GEP->getNumOperands();
463   int64_t Offset = 0;
464   for (i = 1; i != e; ++i, ++GTI) {
465     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
466       // Compute the aggregate offset of constant indices.
467       if (CI->isZero()) continue;
468 
469       // Handle a struct index, which adds its field offset to the pointer.
470       if (StructType *STy = GTI.getStructTypeOrNull()) {
471         Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
472       } else {
473         uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
474         Offset += Size*CI->getSExtValue();
475       }
476     } else {
477       // Found our variable index.
478       break;
479     }
480   }
481 
482   // If there are no variable indices, we must have a constant offset, just
483   // evaluate it the general way.
484   if (i == e) return nullptr;
485 
486   Value *VariableIdx = GEP->getOperand(i);
487   // Determine the scale factor of the variable element.  For example, this is
488   // 4 if the variable index is into an array of i32.
489   uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
490 
491   // Verify that there are no other variable indices.  If so, emit the hard way.
492   for (++i, ++GTI; i != e; ++i, ++GTI) {
493     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
494     if (!CI) return nullptr;
495 
496     // Compute the aggregate offset of constant indices.
497     if (CI->isZero()) continue;
498 
499     // Handle a struct index, which adds its field offset to the pointer.
500     if (StructType *STy = GTI.getStructTypeOrNull()) {
501       Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
502     } else {
503       uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
504       Offset += Size*CI->getSExtValue();
505     }
506   }
507 
508   // Okay, we know we have a single variable index, which must be a
509   // pointer/array/vector index.  If there is no offset, life is simple, return
510   // the index.
511   Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
512   unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
513   if (Offset == 0) {
514     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
515     // we don't need to bother extending: the extension won't affect where the
516     // computation crosses zero.
517     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
518       VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy);
519     }
520     return VariableIdx;
521   }
522 
523   // Otherwise, there is an index.  The computation we will do will be modulo
524   // the pointer size.
525   Offset = SignExtend64(Offset, IntPtrWidth);
526   VariableScale = SignExtend64(VariableScale, IntPtrWidth);
527 
528   // To do this transformation, any constant index must be a multiple of the
529   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
530   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
531   // multiple of the variable scale.
532   int64_t NewOffs = Offset / (int64_t)VariableScale;
533   if (Offset != NewOffs*(int64_t)VariableScale)
534     return nullptr;
535 
536   // Okay, we can do this evaluation.  Start by converting the index to intptr.
537   if (VariableIdx->getType() != IntPtrTy)
538     VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy,
539                                             true /*Signed*/);
540   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
541   return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset");
542 }
543 
544 /// Returns true if we can rewrite Start as a GEP with pointer Base
545 /// and some integer offset. The nodes that need to be re-written
546 /// for this transformation will be added to Explored.
547 static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
548                                   const DataLayout &DL,
549                                   SetVector<Value *> &Explored) {
550   SmallVector<Value *, 16> WorkList(1, Start);
551   Explored.insert(Base);
552 
553   // The following traversal gives us an order which can be used
554   // when doing the final transformation. Since in the final
555   // transformation we create the PHI replacement instructions first,
556   // we don't have to get them in any particular order.
557   //
558   // However, for other instructions we will have to traverse the
559   // operands of an instruction first, which means that we have to
560   // do a post-order traversal.
561   while (!WorkList.empty()) {
562     SetVector<PHINode *> PHIs;
563 
564     while (!WorkList.empty()) {
565       if (Explored.size() >= 100)
566         return false;
567 
568       Value *V = WorkList.back();
569 
570       if (Explored.count(V) != 0) {
571         WorkList.pop_back();
572         continue;
573       }
574 
575       if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
576           !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
577         // We've found some value that we can't explore which is different from
578         // the base. Therefore we can't do this transformation.
579         return false;
580 
581       if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
582         auto *CI = dyn_cast<CastInst>(V);
583         if (!CI->isNoopCast(DL))
584           return false;
585 
586         if (Explored.count(CI->getOperand(0)) == 0)
587           WorkList.push_back(CI->getOperand(0));
588       }
589 
590       if (auto *GEP = dyn_cast<GEPOperator>(V)) {
591         // We're limiting the GEP to having one index. This will preserve
592         // the original pointer type. We could handle more cases in the
593         // future.
594         if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
595             GEP->getType() != Start->getType())
596           return false;
597 
598         if (Explored.count(GEP->getOperand(0)) == 0)
599           WorkList.push_back(GEP->getOperand(0));
600       }
601 
602       if (WorkList.back() == V) {
603         WorkList.pop_back();
604         // We've finished visiting this node, mark it as such.
605         Explored.insert(V);
606       }
607 
608       if (auto *PN = dyn_cast<PHINode>(V)) {
609         // We cannot transform PHIs on unsplittable basic blocks.
610         if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
611           return false;
612         Explored.insert(PN);
613         PHIs.insert(PN);
614       }
615     }
616 
617     // Explore the PHI nodes further.
618     for (auto *PN : PHIs)
619       for (Value *Op : PN->incoming_values())
620         if (Explored.count(Op) == 0)
621           WorkList.push_back(Op);
622   }
623 
624   // Make sure that we can do this. Since we can't insert GEPs in a basic
625   // block before a PHI node, we can't easily do this transformation if
626   // we have PHI node users of transformed instructions.
627   for (Value *Val : Explored) {
628     for (Value *Use : Val->uses()) {
629 
630       auto *PHI = dyn_cast<PHINode>(Use);
631       auto *Inst = dyn_cast<Instruction>(Val);
632 
633       if (Inst == Base || Inst == PHI || !Inst || !PHI ||
634           Explored.count(PHI) == 0)
635         continue;
636 
637       if (PHI->getParent() == Inst->getParent())
638         return false;
639     }
640   }
641   return true;
642 }
643 
644 // Sets the appropriate insert point on Builder where we can add
645 // a replacement Instruction for V (if that is possible).
646 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
647                               bool Before = true) {
648   if (auto *PHI = dyn_cast<PHINode>(V)) {
649     Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
650     return;
651   }
652   if (auto *I = dyn_cast<Instruction>(V)) {
653     if (!Before)
654       I = &*std::next(I->getIterator());
655     Builder.SetInsertPoint(I);
656     return;
657   }
658   if (auto *A = dyn_cast<Argument>(V)) {
659     // Set the insertion point in the entry block.
660     BasicBlock &Entry = A->getParent()->getEntryBlock();
661     Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
662     return;
663   }
664   // Otherwise, this is a constant and we don't need to set a new
665   // insertion point.
666   assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
667 }
668 
669 /// Returns a re-written value of Start as an indexed GEP using Base as a
670 /// pointer.
671 static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
672                                  const DataLayout &DL,
673                                  SetVector<Value *> &Explored) {
674   // Perform all the substitutions. This is a bit tricky because we can
675   // have cycles in our use-def chains.
676   // 1. Create the PHI nodes without any incoming values.
677   // 2. Create all the other values.
678   // 3. Add the edges for the PHI nodes.
679   // 4. Emit GEPs to get the original pointers.
680   // 5. Remove the original instructions.
681   Type *IndexType = IntegerType::get(
682       Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
683 
684   DenseMap<Value *, Value *> NewInsts;
685   NewInsts[Base] = ConstantInt::getNullValue(IndexType);
686 
687   // Create the new PHI nodes, without adding any incoming values.
688   for (Value *Val : Explored) {
689     if (Val == Base)
690       continue;
691     // Create empty phi nodes. This avoids cyclic dependencies when creating
692     // the remaining instructions.
693     if (auto *PHI = dyn_cast<PHINode>(Val))
694       NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
695                                       PHI->getName() + ".idx", PHI);
696   }
697   IRBuilder<> Builder(Base->getContext());
698 
699   // Create all the other instructions.
700   for (Value *Val : Explored) {
701 
702     if (NewInsts.find(Val) != NewInsts.end())
703       continue;
704 
705     if (auto *CI = dyn_cast<CastInst>(Val)) {
706       // Don't get rid of the intermediate variable here; the store can grow
707       // the map which will invalidate the reference to the input value.
708       Value *V = NewInsts[CI->getOperand(0)];
709       NewInsts[CI] = V;
710       continue;
711     }
712     if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
713       Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
714                                                   : GEP->getOperand(1);
715       setInsertionPoint(Builder, GEP);
716       // Indices might need to be sign extended. GEPs will magically do
717       // this, but we need to do it ourselves here.
718       if (Index->getType()->getScalarSizeInBits() !=
719           NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
720         Index = Builder.CreateSExtOrTrunc(
721             Index, NewInsts[GEP->getOperand(0)]->getType(),
722             GEP->getOperand(0)->getName() + ".sext");
723       }
724 
725       auto *Op = NewInsts[GEP->getOperand(0)];
726       if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
727         NewInsts[GEP] = Index;
728       else
729         NewInsts[GEP] = Builder.CreateNSWAdd(
730             Op, Index, GEP->getOperand(0)->getName() + ".add");
731       continue;
732     }
733     if (isa<PHINode>(Val))
734       continue;
735 
736     llvm_unreachable("Unexpected instruction type");
737   }
738 
739   // Add the incoming values to the PHI nodes.
740   for (Value *Val : Explored) {
741     if (Val == Base)
742       continue;
743     // All the instructions have been created, we can now add edges to the
744     // phi nodes.
745     if (auto *PHI = dyn_cast<PHINode>(Val)) {
746       PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
747       for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
748         Value *NewIncoming = PHI->getIncomingValue(I);
749 
750         if (NewInsts.find(NewIncoming) != NewInsts.end())
751           NewIncoming = NewInsts[NewIncoming];
752 
753         NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
754       }
755     }
756   }
757 
758   for (Value *Val : Explored) {
759     if (Val == Base)
760       continue;
761 
762     // Depending on the type, for external users we have to emit
763     // a GEP or a GEP + ptrtoint.
764     setInsertionPoint(Builder, Val, false);
765 
766     // If required, create an inttoptr instruction for Base.
767     Value *NewBase = Base;
768     if (!Base->getType()->isPointerTy())
769       NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
770                                                Start->getName() + "to.ptr");
771 
772     Value *GEP = Builder.CreateInBoundsGEP(
773         Start->getType()->getPointerElementType(), NewBase,
774         makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
775 
776     if (!Val->getType()->isPointerTy()) {
777       Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
778                                               Val->getName() + ".conv");
779       GEP = Cast;
780     }
781     Val->replaceAllUsesWith(GEP);
782   }
783 
784   return NewInsts[Start];
785 }
786 
787 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
788 /// the input Value as a constant indexed GEP. Returns a pair containing
789 /// the GEPs Pointer and Index.
790 static std::pair<Value *, Value *>
791 getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
792   Type *IndexType = IntegerType::get(V->getContext(),
793                                      DL.getIndexTypeSizeInBits(V->getType()));
794 
795   Constant *Index = ConstantInt::getNullValue(IndexType);
796   while (true) {
797     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
798       // We accept only inbouds GEPs here to exclude the possibility of
799       // overflow.
800       if (!GEP->isInBounds())
801         break;
802       if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
803           GEP->getType() == V->getType()) {
804         V = GEP->getOperand(0);
805         Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
806         Index = ConstantExpr::getAdd(
807             Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
808         continue;
809       }
810       break;
811     }
812     if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
813       if (!CI->isNoopCast(DL))
814         break;
815       V = CI->getOperand(0);
816       continue;
817     }
818     if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
819       if (!CI->isNoopCast(DL))
820         break;
821       V = CI->getOperand(0);
822       continue;
823     }
824     break;
825   }
826   return {V, Index};
827 }
828 
829 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
830 /// We can look through PHIs, GEPs and casts in order to determine a common base
831 /// between GEPLHS and RHS.
832 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
833                                               ICmpInst::Predicate Cond,
834                                               const DataLayout &DL) {
835   if (!GEPLHS->hasAllConstantIndices())
836     return nullptr;
837 
838   // Make sure the pointers have the same type.
839   if (GEPLHS->getType() != RHS->getType())
840     return nullptr;
841 
842   Value *PtrBase, *Index;
843   std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
844 
845   // The set of nodes that will take part in this transformation.
846   SetVector<Value *> Nodes;
847 
848   if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
849     return nullptr;
850 
851   // We know we can re-write this as
852   //  ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
853   // Since we've only looked through inbouds GEPs we know that we
854   // can't have overflow on either side. We can therefore re-write
855   // this as:
856   //   OFFSET1 cmp OFFSET2
857   Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
858 
859   // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
860   // GEP having PtrBase as the pointer base, and has returned in NewRHS the
861   // offset. Since Index is the offset of LHS to the base pointer, we will now
862   // compare the offsets instead of comparing the pointers.
863   return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
864 }
865 
866 /// Fold comparisons between a GEP instruction and something else. At this point
867 /// we know that the GEP is on the LHS of the comparison.
868 Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
869                                        ICmpInst::Predicate Cond,
870                                        Instruction &I) {
871   // Don't transform signed compares of GEPs into index compares. Even if the
872   // GEP is inbounds, the final add of the base pointer can have signed overflow
873   // and would change the result of the icmp.
874   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
875   // the maximum signed value for the pointer type.
876   if (ICmpInst::isSigned(Cond))
877     return nullptr;
878 
879   // Look through bitcasts and addrspacecasts. We do not however want to remove
880   // 0 GEPs.
881   if (!isa<GetElementPtrInst>(RHS))
882     RHS = RHS->stripPointerCasts();
883 
884   Value *PtrBase = GEPLHS->getOperand(0);
885   if (PtrBase == RHS && GEPLHS->isInBounds()) {
886     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
887     // This transformation (ignoring the base and scales) is valid because we
888     // know pointers can't overflow since the gep is inbounds.  See if we can
889     // output an optimized form.
890     Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
891 
892     // If not, synthesize the offset the hard way.
893     if (!Offset)
894       Offset = EmitGEPOffset(GEPLHS);
895     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
896                         Constant::getNullValue(Offset->getType()));
897   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
898     // If the base pointers are different, but the indices are the same, just
899     // compare the base pointer.
900     if (PtrBase != GEPRHS->getOperand(0)) {
901       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
902       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
903                         GEPRHS->getOperand(0)->getType();
904       if (IndicesTheSame)
905         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
906           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
907             IndicesTheSame = false;
908             break;
909           }
910 
911       // If all indices are the same, just compare the base pointers.
912       Type *BaseType = GEPLHS->getOperand(0)->getType();
913       if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
914         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
915 
916       // If we're comparing GEPs with two base pointers that only differ in type
917       // and both GEPs have only constant indices or just one use, then fold
918       // the compare with the adjusted indices.
919       if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
920           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
921           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
922           PtrBase->stripPointerCasts() ==
923               GEPRHS->getOperand(0)->stripPointerCasts()) {
924         Value *LOffset = EmitGEPOffset(GEPLHS);
925         Value *ROffset = EmitGEPOffset(GEPRHS);
926 
927         // If we looked through an addrspacecast between different sized address
928         // spaces, the LHS and RHS pointers are different sized
929         // integers. Truncate to the smaller one.
930         Type *LHSIndexTy = LOffset->getType();
931         Type *RHSIndexTy = ROffset->getType();
932         if (LHSIndexTy != RHSIndexTy) {
933           if (LHSIndexTy->getPrimitiveSizeInBits() <
934               RHSIndexTy->getPrimitiveSizeInBits()) {
935             ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
936           } else
937             LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
938         }
939 
940         Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
941                                         LOffset, ROffset);
942         return replaceInstUsesWith(I, Cmp);
943       }
944 
945       // Otherwise, the base pointers are different and the indices are
946       // different. Try convert this to an indexed compare by looking through
947       // PHIs/casts.
948       return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
949     }
950 
951     // If one of the GEPs has all zero indices, recurse.
952     if (GEPLHS->hasAllZeroIndices())
953       return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
954                          ICmpInst::getSwappedPredicate(Cond), I);
955 
956     // If the other GEP has all zero indices, recurse.
957     if (GEPRHS->hasAllZeroIndices())
958       return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
959 
960     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
961     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
962       // If the GEPs only differ by one index, compare it.
963       unsigned NumDifferences = 0;  // Keep track of # differences.
964       unsigned DiffOperand = 0;     // The operand that differs.
965       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
966         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
967           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
968                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
969             // Irreconcilable differences.
970             NumDifferences = 2;
971             break;
972           } else {
973             if (NumDifferences++) break;
974             DiffOperand = i;
975           }
976         }
977 
978       if (NumDifferences == 0)   // SAME GEP?
979         return replaceInstUsesWith(I, // No comparison is needed here.
980           ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
981 
982       else if (NumDifferences == 1 && GEPsInBounds) {
983         Value *LHSV = GEPLHS->getOperand(DiffOperand);
984         Value *RHSV = GEPRHS->getOperand(DiffOperand);
985         // Make sure we do a signed comparison here.
986         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
987       }
988     }
989 
990     // Only lower this if the icmp is the only user of the GEP or if we expect
991     // the result to fold to a constant!
992     if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
993         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
994       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
995       Value *L = EmitGEPOffset(GEPLHS);
996       Value *R = EmitGEPOffset(GEPRHS);
997       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
998     }
999   }
1000 
1001   // Try convert this to an indexed compare by looking through PHIs/casts as a
1002   // last resort.
1003   return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1004 }
1005 
1006 Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1007                                          const AllocaInst *Alloca,
1008                                          const Value *Other) {
1009   assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1010 
1011   // It would be tempting to fold away comparisons between allocas and any
1012   // pointer not based on that alloca (e.g. an argument). However, even
1013   // though such pointers cannot alias, they can still compare equal.
1014   //
1015   // But LLVM doesn't specify where allocas get their memory, so if the alloca
1016   // doesn't escape we can argue that it's impossible to guess its value, and we
1017   // can therefore act as if any such guesses are wrong.
1018   //
1019   // The code below checks that the alloca doesn't escape, and that it's only
1020   // used in a comparison once (the current instruction). The
1021   // single-comparison-use condition ensures that we're trivially folding all
1022   // comparisons against the alloca consistently, and avoids the risk of
1023   // erroneously folding a comparison of the pointer with itself.
1024 
1025   unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1026 
1027   SmallVector<const Use *, 32> Worklist;
1028   for (const Use &U : Alloca->uses()) {
1029     if (Worklist.size() >= MaxIter)
1030       return nullptr;
1031     Worklist.push_back(&U);
1032   }
1033 
1034   unsigned NumCmps = 0;
1035   while (!Worklist.empty()) {
1036     assert(Worklist.size() <= MaxIter);
1037     const Use *U = Worklist.pop_back_val();
1038     const Value *V = U->getUser();
1039     --MaxIter;
1040 
1041     if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1042         isa<SelectInst>(V)) {
1043       // Track the uses.
1044     } else if (isa<LoadInst>(V)) {
1045       // Loading from the pointer doesn't escape it.
1046       continue;
1047     } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
1048       // Storing *to* the pointer is fine, but storing the pointer escapes it.
1049       if (SI->getValueOperand() == U->get())
1050         return nullptr;
1051       continue;
1052     } else if (isa<ICmpInst>(V)) {
1053       if (NumCmps++)
1054         return nullptr; // Found more than one cmp.
1055       continue;
1056     } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1057       switch (Intrin->getIntrinsicID()) {
1058         // These intrinsics don't escape or compare the pointer. Memset is safe
1059         // because we don't allow ptrtoint. Memcpy and memmove are safe because
1060         // we don't allow stores, so src cannot point to V.
1061         case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1062         case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1063           continue;
1064         default:
1065           return nullptr;
1066       }
1067     } else {
1068       return nullptr;
1069     }
1070     for (const Use &U : V->uses()) {
1071       if (Worklist.size() >= MaxIter)
1072         return nullptr;
1073       Worklist.push_back(&U);
1074     }
1075   }
1076 
1077   Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
1078   return replaceInstUsesWith(
1079       ICI,
1080       ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1081 }
1082 
1083 /// Fold "icmp pred (X+C), X".
1084 Instruction *InstCombiner::foldICmpAddOpConst(Value *X, const APInt &C,
1085                                               ICmpInst::Predicate Pred) {
1086   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
1087   // so the values can never be equal.  Similarly for all other "or equals"
1088   // operators.
1089   assert(!!C && "C should not be zero!");
1090 
1091   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
1092   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
1093   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
1094   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1095     Constant *R = ConstantInt::get(X->getType(),
1096                                    APInt::getMaxValue(C.getBitWidth()) - C);
1097     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1098   }
1099 
1100   // (X+1) >u X        --> X <u (0-1)        --> X != 255
1101   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
1102   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
1103   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1104     return new ICmpInst(ICmpInst::ICMP_ULT, X,
1105                         ConstantInt::get(X->getType(), -C));
1106 
1107   APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1108 
1109   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
1110   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
1111   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
1112   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
1113   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
1114   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
1115   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1116     return new ICmpInst(ICmpInst::ICMP_SGT, X,
1117                         ConstantInt::get(X->getType(), SMax - C));
1118 
1119   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
1120   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
1121   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1122   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1123   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
1124   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
1125 
1126   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1127   return new ICmpInst(ICmpInst::ICMP_SLT, X,
1128                       ConstantInt::get(X->getType(), SMax - (C - 1)));
1129 }
1130 
1131 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1132 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
1133 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1134 Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A,
1135                                                  const APInt &AP1,
1136                                                  const APInt &AP2) {
1137   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1138 
1139   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1140     if (I.getPredicate() == I.ICMP_NE)
1141       Pred = CmpInst::getInversePredicate(Pred);
1142     return new ICmpInst(Pred, LHS, RHS);
1143   };
1144 
1145   // Don't bother doing any work for cases which InstSimplify handles.
1146   if (AP2.isNullValue())
1147     return nullptr;
1148 
1149   bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1150   if (IsAShr) {
1151     if (AP2.isAllOnesValue())
1152       return nullptr;
1153     if (AP2.isNegative() != AP1.isNegative())
1154       return nullptr;
1155     if (AP2.sgt(AP1))
1156       return nullptr;
1157   }
1158 
1159   if (!AP1)
1160     // 'A' must be large enough to shift out the highest set bit.
1161     return getICmp(I.ICMP_UGT, A,
1162                    ConstantInt::get(A->getType(), AP2.logBase2()));
1163 
1164   if (AP1 == AP2)
1165     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1166 
1167   int Shift;
1168   if (IsAShr && AP1.isNegative())
1169     Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1170   else
1171     Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1172 
1173   if (Shift > 0) {
1174     if (IsAShr && AP1 == AP2.ashr(Shift)) {
1175       // There are multiple solutions if we are comparing against -1 and the LHS
1176       // of the ashr is not a power of two.
1177       if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1178         return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1179       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1180     } else if (AP1 == AP2.lshr(Shift)) {
1181       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1182     }
1183   }
1184 
1185   // Shifting const2 will never be equal to const1.
1186   // FIXME: This should always be handled by InstSimplify?
1187   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1188   return replaceInstUsesWith(I, TorF);
1189 }
1190 
1191 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1192 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1193 Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A,
1194                                                  const APInt &AP1,
1195                                                  const APInt &AP2) {
1196   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1197 
1198   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1199     if (I.getPredicate() == I.ICMP_NE)
1200       Pred = CmpInst::getInversePredicate(Pred);
1201     return new ICmpInst(Pred, LHS, RHS);
1202   };
1203 
1204   // Don't bother doing any work for cases which InstSimplify handles.
1205   if (AP2.isNullValue())
1206     return nullptr;
1207 
1208   unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1209 
1210   if (!AP1 && AP2TrailingZeros != 0)
1211     return getICmp(
1212         I.ICMP_UGE, A,
1213         ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1214 
1215   if (AP1 == AP2)
1216     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1217 
1218   // Get the distance between the lowest bits that are set.
1219   int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1220 
1221   if (Shift > 0 && AP2.shl(Shift) == AP1)
1222     return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1223 
1224   // Shifting const2 will never be equal to const1.
1225   // FIXME: This should always be handled by InstSimplify?
1226   auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1227   return replaceInstUsesWith(I, TorF);
1228 }
1229 
1230 /// The caller has matched a pattern of the form:
1231 ///   I = icmp ugt (add (add A, B), CI2), CI1
1232 /// If this is of the form:
1233 ///   sum = a + b
1234 ///   if (sum+128 >u 255)
1235 /// Then replace it with llvm.sadd.with.overflow.i8.
1236 ///
1237 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1238                                           ConstantInt *CI2, ConstantInt *CI1,
1239                                           InstCombiner &IC) {
1240   // The transformation we're trying to do here is to transform this into an
1241   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1242   // with a narrower add, and discard the add-with-constant that is part of the
1243   // range check (if we can't eliminate it, this isn't profitable).
1244 
1245   // In order to eliminate the add-with-constant, the compare can be its only
1246   // use.
1247   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1248   if (!AddWithCst->hasOneUse())
1249     return nullptr;
1250 
1251   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1252   if (!CI2->getValue().isPowerOf2())
1253     return nullptr;
1254   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1255   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1256     return nullptr;
1257 
1258   // The width of the new add formed is 1 more than the bias.
1259   ++NewWidth;
1260 
1261   // Check to see that CI1 is an all-ones value with NewWidth bits.
1262   if (CI1->getBitWidth() == NewWidth ||
1263       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1264     return nullptr;
1265 
1266   // This is only really a signed overflow check if the inputs have been
1267   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1268   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1269   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1270   if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1271       IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1272     return nullptr;
1273 
1274   // In order to replace the original add with a narrower
1275   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1276   // and truncates that discard the high bits of the add.  Verify that this is
1277   // the case.
1278   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1279   for (User *U : OrigAdd->users()) {
1280     if (U == AddWithCst)
1281       continue;
1282 
1283     // Only accept truncates for now.  We would really like a nice recursive
1284     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1285     // chain to see which bits of a value are actually demanded.  If the
1286     // original add had another add which was then immediately truncated, we
1287     // could still do the transformation.
1288     TruncInst *TI = dyn_cast<TruncInst>(U);
1289     if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1290       return nullptr;
1291   }
1292 
1293   // If the pattern matches, truncate the inputs to the narrower type and
1294   // use the sadd_with_overflow intrinsic to efficiently compute both the
1295   // result and the overflow bit.
1296   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1297   Function *F = Intrinsic::getDeclaration(
1298       I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1299 
1300   InstCombiner::BuilderTy &Builder = IC.Builder;
1301 
1302   // Put the new code above the original add, in case there are any uses of the
1303   // add between the add and the compare.
1304   Builder.SetInsertPoint(OrigAdd);
1305 
1306   Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1307   Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1308   CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1309   Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1310   Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1311 
1312   // The inner add was the result of the narrow add, zero extended to the
1313   // wider type.  Replace it with the result computed by the intrinsic.
1314   IC.replaceInstUsesWith(*OrigAdd, ZExt);
1315 
1316   // The original icmp gets replaced with the overflow value.
1317   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1318 }
1319 
1320 // Handle (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1321 Instruction *InstCombiner::foldICmpWithZero(ICmpInst &Cmp) {
1322   CmpInst::Predicate Pred = Cmp.getPredicate();
1323   Value *X = Cmp.getOperand(0);
1324 
1325   if (match(Cmp.getOperand(1), m_Zero()) && Pred == ICmpInst::ICMP_SGT) {
1326     Value *A, *B;
1327     SelectPatternResult SPR = matchSelectPattern(X, A, B);
1328     if (SPR.Flavor == SPF_SMIN) {
1329       if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1330         return new ICmpInst(Pred, B, Cmp.getOperand(1));
1331       if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1332         return new ICmpInst(Pred, A, Cmp.getOperand(1));
1333     }
1334   }
1335   return nullptr;
1336 }
1337 
1338 /// Fold icmp Pred X, C.
1339 /// TODO: This code structure does not make sense. The saturating add fold
1340 /// should be moved to some other helper and extended as noted below (it is also
1341 /// possible that code has been made unnecessary - do we canonicalize IR to
1342 /// overflow/saturating intrinsics or not?).
1343 Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1344   // Match the following pattern, which is a common idiom when writing
1345   // overflow-safe integer arithmetic functions. The source performs an addition
1346   // in wider type and explicitly checks for overflow using comparisons against
1347   // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1348   //
1349   // TODO: This could probably be generalized to handle other overflow-safe
1350   // operations if we worked out the formulas to compute the appropriate magic
1351   // constants.
1352   //
1353   // sum = a + b
1354   // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1355   CmpInst::Predicate Pred = Cmp.getPredicate();
1356   Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1357   Value *A, *B;
1358   ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1359   if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1360       match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1361     if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1362       return Res;
1363 
1364   return nullptr;
1365 }
1366 
1367 /// Canonicalize icmp instructions based on dominating conditions.
1368 Instruction *InstCombiner::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1369   // This is a cheap/incomplete check for dominance - just match a single
1370   // predecessor with a conditional branch.
1371   BasicBlock *CmpBB = Cmp.getParent();
1372   BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1373   if (!DomBB)
1374     return nullptr;
1375 
1376   Value *DomCond;
1377   BasicBlock *TrueBB, *FalseBB;
1378   if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1379     return nullptr;
1380 
1381   assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1382          "Predecessor block does not point to successor?");
1383 
1384   // The branch should get simplified. Don't bother simplifying this condition.
1385   if (TrueBB == FalseBB)
1386     return nullptr;
1387 
1388   // Try to simplify this compare to T/F based on the dominating condition.
1389   Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1390   if (Imp)
1391     return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1392 
1393   CmpInst::Predicate Pred = Cmp.getPredicate();
1394   Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1395   ICmpInst::Predicate DomPred;
1396   const APInt *C, *DomC;
1397   if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1398       match(Y, m_APInt(C))) {
1399     // We have 2 compares of a variable with constants. Calculate the constant
1400     // ranges of those compares to see if we can transform the 2nd compare:
1401     // DomBB:
1402     //   DomCond = icmp DomPred X, DomC
1403     //   br DomCond, CmpBB, FalseBB
1404     // CmpBB:
1405     //   Cmp = icmp Pred X, C
1406     ConstantRange CR = ConstantRange::makeAllowedICmpRegion(Pred, *C);
1407     ConstantRange DominatingCR =
1408         (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1409                           : ConstantRange::makeExactICmpRegion(
1410                                 CmpInst::getInversePredicate(DomPred), *DomC);
1411     ConstantRange Intersection = DominatingCR.intersectWith(CR);
1412     ConstantRange Difference = DominatingCR.difference(CR);
1413     if (Intersection.isEmptySet())
1414       return replaceInstUsesWith(Cmp, Builder.getFalse());
1415     if (Difference.isEmptySet())
1416       return replaceInstUsesWith(Cmp, Builder.getTrue());
1417 
1418     // Canonicalizing a sign bit comparison that gets used in a branch,
1419     // pessimizes codegen by generating branch on zero instruction instead
1420     // of a test and branch. So we avoid canonicalizing in such situations
1421     // because test and branch instruction has better branch displacement
1422     // than compare and branch instruction.
1423     bool UnusedBit;
1424     bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1425     if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1426       return nullptr;
1427 
1428     if (const APInt *EqC = Intersection.getSingleElement())
1429       return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1430     if (const APInt *NeC = Difference.getSingleElement())
1431       return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1432   }
1433 
1434   return nullptr;
1435 }
1436 
1437 /// Fold icmp (trunc X, Y), C.
1438 Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1439                                                  TruncInst *Trunc,
1440                                                  const APInt &C) {
1441   ICmpInst::Predicate Pred = Cmp.getPredicate();
1442   Value *X = Trunc->getOperand(0);
1443   if (C.isOneValue() && C.getBitWidth() > 1) {
1444     // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1445     Value *V = nullptr;
1446     if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1447       return new ICmpInst(ICmpInst::ICMP_SLT, V,
1448                           ConstantInt::get(V->getType(), 1));
1449   }
1450 
1451   if (Cmp.isEquality() && Trunc->hasOneUse()) {
1452     // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1453     // of the high bits truncated out of x are known.
1454     unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1455              SrcBits = X->getType()->getScalarSizeInBits();
1456     KnownBits Known = computeKnownBits(X, 0, &Cmp);
1457 
1458     // If all the high bits are known, we can do this xform.
1459     if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1460       // Pull in the high bits from known-ones set.
1461       APInt NewRHS = C.zext(SrcBits);
1462       NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1463       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
1464     }
1465   }
1466 
1467   return nullptr;
1468 }
1469 
1470 /// Fold icmp (xor X, Y), C.
1471 Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1472                                                BinaryOperator *Xor,
1473                                                const APInt &C) {
1474   Value *X = Xor->getOperand(0);
1475   Value *Y = Xor->getOperand(1);
1476   const APInt *XorC;
1477   if (!match(Y, m_APInt(XorC)))
1478     return nullptr;
1479 
1480   // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1481   // fold the xor.
1482   ICmpInst::Predicate Pred = Cmp.getPredicate();
1483   bool TrueIfSigned = false;
1484   if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1485 
1486     // If the sign bit of the XorCst is not set, there is no change to
1487     // the operation, just stop using the Xor.
1488     if (!XorC->isNegative()) {
1489       Cmp.setOperand(0, X);
1490       Worklist.Add(Xor);
1491       return &Cmp;
1492     }
1493 
1494     // Emit the opposite comparison.
1495     if (TrueIfSigned)
1496       return new ICmpInst(ICmpInst::ICMP_SGT, X,
1497                           ConstantInt::getAllOnesValue(X->getType()));
1498     else
1499       return new ICmpInst(ICmpInst::ICMP_SLT, X,
1500                           ConstantInt::getNullValue(X->getType()));
1501   }
1502 
1503   if (Xor->hasOneUse()) {
1504     // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1505     if (!Cmp.isEquality() && XorC->isSignMask()) {
1506       Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1507                             : Cmp.getSignedPredicate();
1508       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1509     }
1510 
1511     // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1512     if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1513       Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1514                             : Cmp.getSignedPredicate();
1515       Pred = Cmp.getSwappedPredicate(Pred);
1516       return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1517     }
1518   }
1519 
1520   // Mask constant magic can eliminate an 'xor' with unsigned compares.
1521   if (Pred == ICmpInst::ICMP_UGT) {
1522     // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1523     if (*XorC == ~C && (C + 1).isPowerOf2())
1524       return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1525     // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1526     if (*XorC == C && (C + 1).isPowerOf2())
1527       return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1528   }
1529   if (Pred == ICmpInst::ICMP_ULT) {
1530     // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1531     if (*XorC == -C && C.isPowerOf2())
1532       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1533                           ConstantInt::get(X->getType(), ~C));
1534     // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1535     if (*XorC == C && (-C).isPowerOf2())
1536       return new ICmpInst(ICmpInst::ICMP_UGT, X,
1537                           ConstantInt::get(X->getType(), ~C));
1538   }
1539   return nullptr;
1540 }
1541 
1542 /// Fold icmp (and (sh X, Y), C2), C1.
1543 Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
1544                                             const APInt &C1, const APInt &C2) {
1545   BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1546   if (!Shift || !Shift->isShift())
1547     return nullptr;
1548 
1549   // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1550   // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1551   // code produced by the clang front-end, for bitfield access.
1552   // This seemingly simple opportunity to fold away a shift turns out to be
1553   // rather complicated. See PR17827 for details.
1554   unsigned ShiftOpcode = Shift->getOpcode();
1555   bool IsShl = ShiftOpcode == Instruction::Shl;
1556   const APInt *C3;
1557   if (match(Shift->getOperand(1), m_APInt(C3))) {
1558     bool CanFold = false;
1559     if (ShiftOpcode == Instruction::Shl) {
1560       // For a left shift, we can fold if the comparison is not signed. We can
1561       // also fold a signed comparison if the mask value and comparison value
1562       // are not negative. These constraints may not be obvious, but we can
1563       // prove that they are correct using an SMT solver.
1564       if (!Cmp.isSigned() || (!C2.isNegative() && !C1.isNegative()))
1565         CanFold = true;
1566     } else {
1567       bool IsAshr = ShiftOpcode == Instruction::AShr;
1568       // For a logical right shift, we can fold if the comparison is not signed.
1569       // We can also fold a signed comparison if the shifted mask value and the
1570       // shifted comparison value are not negative. These constraints may not be
1571       // obvious, but we can prove that they are correct using an SMT solver.
1572       // For an arithmetic shift right we can do the same, if we ensure
1573       // the And doesn't use any bits being shifted in. Normally these would
1574       // be turned into lshr by SimplifyDemandedBits, but not if there is an
1575       // additional user.
1576       if (!IsAshr || (C2.shl(*C3).lshr(*C3) == C2)) {
1577         if (!Cmp.isSigned() ||
1578             (!C2.shl(*C3).isNegative() && !C1.shl(*C3).isNegative()))
1579           CanFold = true;
1580       }
1581     }
1582 
1583     if (CanFold) {
1584       APInt NewCst = IsShl ? C1.lshr(*C3) : C1.shl(*C3);
1585       APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
1586       // Check to see if we are shifting out any of the bits being compared.
1587       if (SameAsC1 != C1) {
1588         // If we shifted bits out, the fold is not going to work out. As a
1589         // special case, check to see if this means that the result is always
1590         // true or false now.
1591         if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1592           return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1593         if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1594           return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1595       } else {
1596         Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1597         APInt NewAndCst = IsShl ? C2.lshr(*C3) : C2.shl(*C3);
1598         And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
1599         And->setOperand(0, Shift->getOperand(0));
1600         Worklist.Add(Shift); // Shift is dead.
1601         return &Cmp;
1602       }
1603     }
1604   }
1605 
1606   // Turn ((X >> Y) & C2) == 0  into  (X & (C2 << Y)) == 0.  The latter is
1607   // preferable because it allows the C2 << Y expression to be hoisted out of a
1608   // loop if Y is invariant and X is not.
1609   if (Shift->hasOneUse() && C1.isNullValue() && Cmp.isEquality() &&
1610       !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1611     // Compute C2 << Y.
1612     Value *NewShift =
1613         IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1614               : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1615 
1616     // Compute X & (C2 << Y).
1617     Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1618     Cmp.setOperand(0, NewAnd);
1619     return &Cmp;
1620   }
1621 
1622   return nullptr;
1623 }
1624 
1625 /// Fold icmp (and X, C2), C1.
1626 Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1627                                                  BinaryOperator *And,
1628                                                  const APInt &C1) {
1629   bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1630 
1631   // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1632   // TODO: We canonicalize to the longer form for scalars because we have
1633   // better analysis/folds for icmp, and codegen may be better with icmp.
1634   if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isNullValue() &&
1635       match(And->getOperand(1), m_One()))
1636     return new TruncInst(And->getOperand(0), Cmp.getType());
1637 
1638   const APInt *C2;
1639   Value *X;
1640   if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1641     return nullptr;
1642 
1643   // Don't perform the following transforms if the AND has multiple uses
1644   if (!And->hasOneUse())
1645     return nullptr;
1646 
1647   if (Cmp.isEquality() && C1.isNullValue()) {
1648     // Restrict this fold to single-use 'and' (PR10267).
1649     // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1650     if (C2->isSignMask()) {
1651       Constant *Zero = Constant::getNullValue(X->getType());
1652       auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1653       return new ICmpInst(NewPred, X, Zero);
1654     }
1655 
1656     // Restrict this fold only for single-use 'and' (PR10267).
1657     // ((%x & C) == 0) --> %x u< (-C)  iff (-C) is power of two.
1658     if ((~(*C2) + 1).isPowerOf2()) {
1659       Constant *NegBOC =
1660           ConstantExpr::getNeg(cast<Constant>(And->getOperand(1)));
1661       auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1662       return new ICmpInst(NewPred, X, NegBOC);
1663     }
1664   }
1665 
1666   // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1667   // the input width without changing the value produced, eliminate the cast:
1668   //
1669   // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1670   //
1671   // We can do this transformation if the constants do not have their sign bits
1672   // set or if it is an equality comparison. Extending a relational comparison
1673   // when we're checking the sign bit would not work.
1674   Value *W;
1675   if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1676       (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1677     // TODO: Is this a good transform for vectors? Wider types may reduce
1678     // throughput. Should this transform be limited (even for scalars) by using
1679     // shouldChangeType()?
1680     if (!Cmp.getType()->isVectorTy()) {
1681       Type *WideType = W->getType();
1682       unsigned WideScalarBits = WideType->getScalarSizeInBits();
1683       Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1684       Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1685       Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1686       return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1687     }
1688   }
1689 
1690   if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1691     return I;
1692 
1693   // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1694   // (icmp pred (and A, (or (shl 1, B), 1), 0))
1695   //
1696   // iff pred isn't signed
1697   if (!Cmp.isSigned() && C1.isNullValue() && And->getOperand(0)->hasOneUse() &&
1698       match(And->getOperand(1), m_One())) {
1699     Constant *One = cast<Constant>(And->getOperand(1));
1700     Value *Or = And->getOperand(0);
1701     Value *A, *B, *LShr;
1702     if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1703         match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1704       unsigned UsesRemoved = 0;
1705       if (And->hasOneUse())
1706         ++UsesRemoved;
1707       if (Or->hasOneUse())
1708         ++UsesRemoved;
1709       if (LShr->hasOneUse())
1710         ++UsesRemoved;
1711 
1712       // Compute A & ((1 << B) | 1)
1713       Value *NewOr = nullptr;
1714       if (auto *C = dyn_cast<Constant>(B)) {
1715         if (UsesRemoved >= 1)
1716           NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1717       } else {
1718         if (UsesRemoved >= 3)
1719           NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1720                                                      /*HasNUW=*/true),
1721                                    One, Or->getName());
1722       }
1723       if (NewOr) {
1724         Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1725         Cmp.setOperand(0, NewAnd);
1726         return &Cmp;
1727       }
1728     }
1729   }
1730 
1731   return nullptr;
1732 }
1733 
1734 /// Fold icmp (and X, Y), C.
1735 Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1736                                                BinaryOperator *And,
1737                                                const APInt &C) {
1738   if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1739     return I;
1740 
1741   // TODO: These all require that Y is constant too, so refactor with the above.
1742 
1743   // Try to optimize things like "A[i] & 42 == 0" to index computations.
1744   Value *X = And->getOperand(0);
1745   Value *Y = And->getOperand(1);
1746   if (auto *LI = dyn_cast<LoadInst>(X))
1747     if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1748       if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1749         if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1750             !LI->isVolatile() && isa<ConstantInt>(Y)) {
1751           ConstantInt *C2 = cast<ConstantInt>(Y);
1752           if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1753             return Res;
1754         }
1755 
1756   if (!Cmp.isEquality())
1757     return nullptr;
1758 
1759   // X & -C == -C -> X >  u ~C
1760   // X & -C != -C -> X <= u ~C
1761   //   iff C is a power of 2
1762   if (Cmp.getOperand(1) == Y && (-C).isPowerOf2()) {
1763     auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1764                                                           : CmpInst::ICMP_ULE;
1765     return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1766   }
1767 
1768   // (X & C2) == 0 -> (trunc X) >= 0
1769   // (X & C2) != 0 -> (trunc X) <  0
1770   //   iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1771   const APInt *C2;
1772   if (And->hasOneUse() && C.isNullValue() && match(Y, m_APInt(C2))) {
1773     int32_t ExactLogBase2 = C2->exactLogBase2();
1774     if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1775       Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1776       if (And->getType()->isVectorTy())
1777         NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1778       Value *Trunc = Builder.CreateTrunc(X, NTy);
1779       auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1780                                                             : CmpInst::ICMP_SLT;
1781       return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
1782     }
1783   }
1784 
1785   return nullptr;
1786 }
1787 
1788 /// Fold icmp (or X, Y), C.
1789 Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
1790                                               const APInt &C) {
1791   ICmpInst::Predicate Pred = Cmp.getPredicate();
1792   if (C.isOneValue()) {
1793     // icmp slt signum(V) 1 --> icmp slt V, 1
1794     Value *V = nullptr;
1795     if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1796       return new ICmpInst(ICmpInst::ICMP_SLT, V,
1797                           ConstantInt::get(V->getType(), 1));
1798   }
1799 
1800   Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1801   if (Cmp.isEquality() && Cmp.getOperand(1) == OrOp1) {
1802     // X | C == C --> X <=u C
1803     // X | C != C --> X  >u C
1804     //   iff C+1 is a power of 2 (C is a bitmask of the low bits)
1805     if ((C + 1).isPowerOf2()) {
1806       Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
1807       return new ICmpInst(Pred, OrOp0, OrOp1);
1808     }
1809     // More general: are all bits outside of a mask constant set or not set?
1810     // X | C == C --> (X & ~C) == 0
1811     // X | C != C --> (X & ~C) != 0
1812     if (Or->hasOneUse()) {
1813       Value *A = Builder.CreateAnd(OrOp0, ~C);
1814       return new ICmpInst(Pred, A, ConstantInt::getNullValue(OrOp0->getType()));
1815     }
1816   }
1817 
1818   if (!Cmp.isEquality() || !C.isNullValue() || !Or->hasOneUse())
1819     return nullptr;
1820 
1821   Value *P, *Q;
1822   if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1823     // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1824     // -> and (icmp eq P, null), (icmp eq Q, null).
1825     Value *CmpP =
1826         Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1827     Value *CmpQ =
1828         Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
1829     auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1830     return BinaryOperator::Create(BOpc, CmpP, CmpQ);
1831   }
1832 
1833   // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
1834   // a shorter form that has more potential to be folded even further.
1835   Value *X1, *X2, *X3, *X4;
1836   if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
1837       match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
1838     // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1839     // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
1840     Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1841     Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1842     auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1843     return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
1844   }
1845 
1846   return nullptr;
1847 }
1848 
1849 /// Fold icmp (mul X, Y), C.
1850 Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1851                                                BinaryOperator *Mul,
1852                                                const APInt &C) {
1853   const APInt *MulC;
1854   if (!match(Mul->getOperand(1), m_APInt(MulC)))
1855     return nullptr;
1856 
1857   // If this is a test of the sign bit and the multiply is sign-preserving with
1858   // a constant operand, use the multiply LHS operand instead.
1859   ICmpInst::Predicate Pred = Cmp.getPredicate();
1860   if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
1861     if (MulC->isNegative())
1862       Pred = ICmpInst::getSwappedPredicate(Pred);
1863     return new ICmpInst(Pred, Mul->getOperand(0),
1864                         Constant::getNullValue(Mul->getType()));
1865   }
1866 
1867   return nullptr;
1868 }
1869 
1870 /// Fold icmp (shl 1, Y), C.
1871 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1872                                    const APInt &C) {
1873   Value *Y;
1874   if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1875     return nullptr;
1876 
1877   Type *ShiftType = Shl->getType();
1878   unsigned TypeBits = C.getBitWidth();
1879   bool CIsPowerOf2 = C.isPowerOf2();
1880   ICmpInst::Predicate Pred = Cmp.getPredicate();
1881   if (Cmp.isUnsigned()) {
1882     // (1 << Y) pred C -> Y pred Log2(C)
1883     if (!CIsPowerOf2) {
1884       // (1 << Y) <  30 -> Y <= 4
1885       // (1 << Y) <= 30 -> Y <= 4
1886       // (1 << Y) >= 30 -> Y >  4
1887       // (1 << Y) >  30 -> Y >  4
1888       if (Pred == ICmpInst::ICMP_ULT)
1889         Pred = ICmpInst::ICMP_ULE;
1890       else if (Pred == ICmpInst::ICMP_UGE)
1891         Pred = ICmpInst::ICMP_UGT;
1892     }
1893 
1894     // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1895     // (1 << Y) <  2147483648 -> Y <  31 -> Y != 31
1896     unsigned CLog2 = C.logBase2();
1897     if (CLog2 == TypeBits - 1) {
1898       if (Pred == ICmpInst::ICMP_UGE)
1899         Pred = ICmpInst::ICMP_EQ;
1900       else if (Pred == ICmpInst::ICMP_ULT)
1901         Pred = ICmpInst::ICMP_NE;
1902     }
1903     return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1904   } else if (Cmp.isSigned()) {
1905     Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1906     if (C.isAllOnesValue()) {
1907       // (1 << Y) <= -1 -> Y == 31
1908       if (Pred == ICmpInst::ICMP_SLE)
1909         return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1910 
1911       // (1 << Y) >  -1 -> Y != 31
1912       if (Pred == ICmpInst::ICMP_SGT)
1913         return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1914     } else if (!C) {
1915       // (1 << Y) <  0 -> Y == 31
1916       // (1 << Y) <= 0 -> Y == 31
1917       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1918         return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1919 
1920       // (1 << Y) >= 0 -> Y != 31
1921       // (1 << Y) >  0 -> Y != 31
1922       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1923         return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1924     }
1925   } else if (Cmp.isEquality() && CIsPowerOf2) {
1926     return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2()));
1927   }
1928 
1929   return nullptr;
1930 }
1931 
1932 /// Fold icmp (shl X, Y), C.
1933 Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1934                                                BinaryOperator *Shl,
1935                                                const APInt &C) {
1936   const APInt *ShiftVal;
1937   if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
1938     return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
1939 
1940   const APInt *ShiftAmt;
1941   if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
1942     return foldICmpShlOne(Cmp, Shl, C);
1943 
1944   // Check that the shift amount is in range. If not, don't perform undefined
1945   // shifts. When the shift is visited, it will be simplified.
1946   unsigned TypeBits = C.getBitWidth();
1947   if (ShiftAmt->uge(TypeBits))
1948     return nullptr;
1949 
1950   ICmpInst::Predicate Pred = Cmp.getPredicate();
1951   Value *X = Shl->getOperand(0);
1952   Type *ShType = Shl->getType();
1953 
1954   // NSW guarantees that we are only shifting out sign bits from the high bits,
1955   // so we can ASHR the compare constant without needing a mask and eliminate
1956   // the shift.
1957   if (Shl->hasNoSignedWrap()) {
1958     if (Pred == ICmpInst::ICMP_SGT) {
1959       // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
1960       APInt ShiftedC = C.ashr(*ShiftAmt);
1961       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1962     }
1963     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
1964         C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
1965       APInt ShiftedC = C.ashr(*ShiftAmt);
1966       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1967     }
1968     if (Pred == ICmpInst::ICMP_SLT) {
1969       // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
1970       // (X << S) <=s C is equiv to X <=s (C >> S) for all C
1971       // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
1972       // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
1973       assert(!C.isMinSignedValue() && "Unexpected icmp slt");
1974       APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
1975       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1976     }
1977     // If this is a signed comparison to 0 and the shift is sign preserving,
1978     // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1979     // do that if we're sure to not continue on in this function.
1980     if (isSignTest(Pred, C))
1981       return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
1982   }
1983 
1984   // NUW guarantees that we are only shifting out zero bits from the high bits,
1985   // so we can LSHR the compare constant without needing a mask and eliminate
1986   // the shift.
1987   if (Shl->hasNoUnsignedWrap()) {
1988     if (Pred == ICmpInst::ICMP_UGT) {
1989       // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
1990       APInt ShiftedC = C.lshr(*ShiftAmt);
1991       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1992     }
1993     if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
1994         C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
1995       APInt ShiftedC = C.lshr(*ShiftAmt);
1996       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
1997     }
1998     if (Pred == ICmpInst::ICMP_ULT) {
1999       // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2000       // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2001       // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2002       // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2003       assert(C.ugt(0) && "ult 0 should have been eliminated");
2004       APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2005       return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2006     }
2007   }
2008 
2009   if (Cmp.isEquality() && Shl->hasOneUse()) {
2010     // Strength-reduce the shift into an 'and'.
2011     Constant *Mask = ConstantInt::get(
2012         ShType,
2013         APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2014     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2015     Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2016     return new ICmpInst(Pred, And, LShrC);
2017   }
2018 
2019   // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2020   bool TrueIfSigned = false;
2021   if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2022     // (X << 31) <s 0  --> (X & 1) != 0
2023     Constant *Mask = ConstantInt::get(
2024         ShType,
2025         APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2026     Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2027     return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2028                         And, Constant::getNullValue(ShType));
2029   }
2030 
2031   // Simplify 'shl' inequality test into 'and' equality test.
2032   if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2033     // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2034     if ((C + 1).isPowerOf2() &&
2035         (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2036       Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2037       return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2038                                                      : ICmpInst::ICMP_NE,
2039                           And, Constant::getNullValue(ShType));
2040     }
2041     // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2042     if (C.isPowerOf2() &&
2043         (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2044       Value *And =
2045           Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2046       return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2047                                                      : ICmpInst::ICMP_NE,
2048                           And, Constant::getNullValue(ShType));
2049     }
2050   }
2051 
2052   // Transform (icmp pred iM (shl iM %v, N), C)
2053   // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2054   // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2055   // This enables us to get rid of the shift in favor of a trunc that may be
2056   // free on the target. It has the additional benefit of comparing to a
2057   // smaller constant that may be more target-friendly.
2058   unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2059   if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2060       DL.isLegalInteger(TypeBits - Amt)) {
2061     Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2062     if (ShType->isVectorTy())
2063       TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements());
2064     Constant *NewC =
2065         ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2066     return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2067   }
2068 
2069   return nullptr;
2070 }
2071 
2072 /// Fold icmp ({al}shr X, Y), C.
2073 Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
2074                                                BinaryOperator *Shr,
2075                                                const APInt &C) {
2076   // An exact shr only shifts out zero bits, so:
2077   // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2078   Value *X = Shr->getOperand(0);
2079   CmpInst::Predicate Pred = Cmp.getPredicate();
2080   if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() &&
2081       C.isNullValue())
2082     return new ICmpInst(Pred, X, Cmp.getOperand(1));
2083 
2084   const APInt *ShiftVal;
2085   if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal)))
2086     return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftVal);
2087 
2088   const APInt *ShiftAmt;
2089   if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
2090     return nullptr;
2091 
2092   // Check that the shift amount is in range. If not, don't perform undefined
2093   // shifts. When the shift is visited it will be simplified.
2094   unsigned TypeBits = C.getBitWidth();
2095   unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2096   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2097     return nullptr;
2098 
2099   bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2100   bool IsExact = Shr->isExact();
2101   Type *ShrTy = Shr->getType();
2102   // TODO: If we could guarantee that InstSimplify would handle all of the
2103   // constant-value-based preconditions in the folds below, then we could assert
2104   // those conditions rather than checking them. This is difficult because of
2105   // undef/poison (PR34838).
2106   if (IsAShr) {
2107     if (Pred == CmpInst::ICMP_SLT || (Pred == CmpInst::ICMP_SGT && IsExact)) {
2108       // icmp slt (ashr X, ShAmtC), C --> icmp slt X, (C << ShAmtC)
2109       // icmp sgt (ashr exact X, ShAmtC), C --> icmp sgt X, (C << ShAmtC)
2110       APInt ShiftedC = C.shl(ShAmtVal);
2111       if (ShiftedC.ashr(ShAmtVal) == C)
2112         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2113     }
2114     if (Pred == CmpInst::ICMP_SGT) {
2115       // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2116       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2117       if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2118           (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2119         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2120     }
2121   } else {
2122     if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2123       // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2124       // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2125       APInt ShiftedC = C.shl(ShAmtVal);
2126       if (ShiftedC.lshr(ShAmtVal) == C)
2127         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2128     }
2129     if (Pred == CmpInst::ICMP_UGT) {
2130       // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2131       APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2132       if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2133         return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2134     }
2135   }
2136 
2137   if (!Cmp.isEquality())
2138     return nullptr;
2139 
2140   // Handle equality comparisons of shift-by-constant.
2141 
2142   // If the comparison constant changes with the shift, the comparison cannot
2143   // succeed (bits of the comparison constant cannot match the shifted value).
2144   // This should be known by InstSimplify and already be folded to true/false.
2145   assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2146           (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2147          "Expected icmp+shr simplify did not occur.");
2148 
2149   // If the bits shifted out are known zero, compare the unshifted value:
2150   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
2151   if (Shr->isExact())
2152     return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2153 
2154   if (Shr->hasOneUse()) {
2155     // Canonicalize the shift into an 'and':
2156     // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2157     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2158     Constant *Mask = ConstantInt::get(ShrTy, Val);
2159     Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2160     return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2161   }
2162 
2163   return nullptr;
2164 }
2165 
2166 /// Fold icmp (udiv X, Y), C.
2167 Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
2168                                                 BinaryOperator *UDiv,
2169                                                 const APInt &C) {
2170   const APInt *C2;
2171   if (!match(UDiv->getOperand(0), m_APInt(C2)))
2172     return nullptr;
2173 
2174   assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2175 
2176   // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2177   Value *Y = UDiv->getOperand(1);
2178   if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2179     assert(!C.isMaxValue() &&
2180            "icmp ugt X, UINT_MAX should have been simplified already.");
2181     return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2182                         ConstantInt::get(Y->getType(), C2->udiv(C + 1)));
2183   }
2184 
2185   // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2186   if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2187     assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2188     return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2189                         ConstantInt::get(Y->getType(), C2->udiv(C)));
2190   }
2191 
2192   return nullptr;
2193 }
2194 
2195 /// Fold icmp ({su}div X, Y), C.
2196 Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2197                                                BinaryOperator *Div,
2198                                                const APInt &C) {
2199   // Fold: icmp pred ([us]div X, C2), C -> range test
2200   // Fold this div into the comparison, producing a range check.
2201   // Determine, based on the divide type, what the range is being
2202   // checked.  If there is an overflow on the low or high side, remember
2203   // it, otherwise compute the range [low, hi) bounding the new value.
2204   // See: InsertRangeTest above for the kinds of replacements possible.
2205   const APInt *C2;
2206   if (!match(Div->getOperand(1), m_APInt(C2)))
2207     return nullptr;
2208 
2209   // FIXME: If the operand types don't match the type of the divide
2210   // then don't attempt this transform. The code below doesn't have the
2211   // logic to deal with a signed divide and an unsigned compare (and
2212   // vice versa). This is because (x /s C2) <s C  produces different
2213   // results than (x /s C2) <u C or (x /u C2) <s C or even
2214   // (x /u C2) <u C.  Simply casting the operands and result won't
2215   // work. :(  The if statement below tests that condition and bails
2216   // if it finds it.
2217   bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2218   if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2219     return nullptr;
2220 
2221   // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2222   // INT_MIN will also fail if the divisor is 1. Although folds of all these
2223   // division-by-constant cases should be present, we can not assert that they
2224   // have happened before we reach this icmp instruction.
2225   if (C2->isNullValue() || C2->isOneValue() ||
2226       (DivIsSigned && C2->isAllOnesValue()))
2227     return nullptr;
2228 
2229   // Compute Prod = C * C2. We are essentially solving an equation of
2230   // form X / C2 = C. We solve for X by multiplying C2 and C.
2231   // By solving for X, we can turn this into a range check instead of computing
2232   // a divide.
2233   APInt Prod = C * *C2;
2234 
2235   // Determine if the product overflows by seeing if the product is not equal to
2236   // the divide. Make sure we do the same kind of divide as in the LHS
2237   // instruction that we're folding.
2238   bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2239 
2240   ICmpInst::Predicate Pred = Cmp.getPredicate();
2241 
2242   // If the division is known to be exact, then there is no remainder from the
2243   // divide, so the covered range size is unit, otherwise it is the divisor.
2244   APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2245 
2246   // Figure out the interval that is being checked.  For example, a comparison
2247   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2248   // Compute this interval based on the constants involved and the signedness of
2249   // the compare/divide.  This computes a half-open interval, keeping track of
2250   // whether either value in the interval overflows.  After analysis each
2251   // overflow variable is set to 0 if it's corresponding bound variable is valid
2252   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2253   int LoOverflow = 0, HiOverflow = 0;
2254   APInt LoBound, HiBound;
2255 
2256   if (!DivIsSigned) {  // udiv
2257     // e.g. X/5 op 3  --> [15, 20)
2258     LoBound = Prod;
2259     HiOverflow = LoOverflow = ProdOV;
2260     if (!HiOverflow) {
2261       // If this is not an exact divide, then many values in the range collapse
2262       // to the same result value.
2263       HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2264     }
2265   } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2266     if (C.isNullValue()) {       // (X / pos) op 0
2267       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
2268       LoBound = -(RangeSize - 1);
2269       HiBound = RangeSize;
2270     } else if (C.isStrictlyPositive()) {   // (X / pos) op pos
2271       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
2272       HiOverflow = LoOverflow = ProdOV;
2273       if (!HiOverflow)
2274         HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2275     } else {                       // (X / pos) op neg
2276       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
2277       HiBound = Prod + 1;
2278       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2279       if (!LoOverflow) {
2280         APInt DivNeg = -RangeSize;
2281         LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2282       }
2283     }
2284   } else if (C2->isNegative()) { // Divisor is < 0.
2285     if (Div->isExact())
2286       RangeSize.negate();
2287     if (C.isNullValue()) { // (X / neg) op 0
2288       // e.g. X/-5 op 0  --> [-4, 5)
2289       LoBound = RangeSize + 1;
2290       HiBound = -RangeSize;
2291       if (HiBound == *C2) {        // -INTMIN = INTMIN
2292         HiOverflow = 1;            // [INTMIN+1, overflow)
2293         HiBound = APInt();         // e.g. X/INTMIN = 0 --> X > INTMIN
2294       }
2295     } else if (C.isStrictlyPositive()) {   // (X / neg) op pos
2296       // e.g. X/-5 op 3  --> [-19, -14)
2297       HiBound = Prod + 1;
2298       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2299       if (!LoOverflow)
2300         LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2301     } else {                       // (X / neg) op neg
2302       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
2303       LoOverflow = HiOverflow = ProdOV;
2304       if (!HiOverflow)
2305         HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2306     }
2307 
2308     // Dividing by a negative swaps the condition.  LT <-> GT
2309     Pred = ICmpInst::getSwappedPredicate(Pred);
2310   }
2311 
2312   Value *X = Div->getOperand(0);
2313   switch (Pred) {
2314     default: llvm_unreachable("Unhandled icmp opcode!");
2315     case ICmpInst::ICMP_EQ:
2316       if (LoOverflow && HiOverflow)
2317         return replaceInstUsesWith(Cmp, Builder.getFalse());
2318       if (HiOverflow)
2319         return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2320                             ICmpInst::ICMP_UGE, X,
2321                             ConstantInt::get(Div->getType(), LoBound));
2322       if (LoOverflow)
2323         return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2324                             ICmpInst::ICMP_ULT, X,
2325                             ConstantInt::get(Div->getType(), HiBound));
2326       return replaceInstUsesWith(
2327           Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2328     case ICmpInst::ICMP_NE:
2329       if (LoOverflow && HiOverflow)
2330         return replaceInstUsesWith(Cmp, Builder.getTrue());
2331       if (HiOverflow)
2332         return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2333                             ICmpInst::ICMP_ULT, X,
2334                             ConstantInt::get(Div->getType(), LoBound));
2335       if (LoOverflow)
2336         return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2337                             ICmpInst::ICMP_UGE, X,
2338                             ConstantInt::get(Div->getType(), HiBound));
2339       return replaceInstUsesWith(Cmp,
2340                                  insertRangeTest(X, LoBound, HiBound,
2341                                                  DivIsSigned, false));
2342     case ICmpInst::ICMP_ULT:
2343     case ICmpInst::ICMP_SLT:
2344       if (LoOverflow == +1)   // Low bound is greater than input range.
2345         return replaceInstUsesWith(Cmp, Builder.getTrue());
2346       if (LoOverflow == -1)   // Low bound is less than input range.
2347         return replaceInstUsesWith(Cmp, Builder.getFalse());
2348       return new ICmpInst(Pred, X, ConstantInt::get(Div->getType(), LoBound));
2349     case ICmpInst::ICMP_UGT:
2350     case ICmpInst::ICMP_SGT:
2351       if (HiOverflow == +1)       // High bound greater than input range.
2352         return replaceInstUsesWith(Cmp, Builder.getFalse());
2353       if (HiOverflow == -1)       // High bound less than input range.
2354         return replaceInstUsesWith(Cmp, Builder.getTrue());
2355       if (Pred == ICmpInst::ICMP_UGT)
2356         return new ICmpInst(ICmpInst::ICMP_UGE, X,
2357                             ConstantInt::get(Div->getType(), HiBound));
2358       return new ICmpInst(ICmpInst::ICMP_SGE, X,
2359                           ConstantInt::get(Div->getType(), HiBound));
2360   }
2361 
2362   return nullptr;
2363 }
2364 
2365 /// Fold icmp (sub X, Y), C.
2366 Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2367                                                BinaryOperator *Sub,
2368                                                const APInt &C) {
2369   Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2370   ICmpInst::Predicate Pred = Cmp.getPredicate();
2371   const APInt *C2;
2372   APInt SubResult;
2373 
2374   // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2375   if (match(X, m_APInt(C2)) &&
2376       ((Cmp.isUnsigned() && Sub->hasNoUnsignedWrap()) ||
2377        (Cmp.isSigned() && Sub->hasNoSignedWrap())) &&
2378       !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2379     return new ICmpInst(Cmp.getSwappedPredicate(), Y,
2380                         ConstantInt::get(Y->getType(), SubResult));
2381 
2382   // The following transforms are only worth it if the only user of the subtract
2383   // is the icmp.
2384   if (!Sub->hasOneUse())
2385     return nullptr;
2386 
2387   if (Sub->hasNoSignedWrap()) {
2388     // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2389     if (Pred == ICmpInst::ICMP_SGT && C.isAllOnesValue())
2390       return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2391 
2392     // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2393     if (Pred == ICmpInst::ICMP_SGT && C.isNullValue())
2394       return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2395 
2396     // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2397     if (Pred == ICmpInst::ICMP_SLT && C.isNullValue())
2398       return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2399 
2400     // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2401     if (Pred == ICmpInst::ICMP_SLT && C.isOneValue())
2402       return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2403   }
2404 
2405   if (!match(X, m_APInt(C2)))
2406     return nullptr;
2407 
2408   // C2 - Y <u C -> (Y | (C - 1)) == C2
2409   //   iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2410   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2411       (*C2 & (C - 1)) == (C - 1))
2412     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2413 
2414   // C2 - Y >u C -> (Y | C) != C2
2415   //   iff C2 & C == C and C + 1 is a power of 2
2416   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2417     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2418 
2419   return nullptr;
2420 }
2421 
2422 /// Fold icmp (add X, Y), C.
2423 Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2424                                                BinaryOperator *Add,
2425                                                const APInt &C) {
2426   Value *Y = Add->getOperand(1);
2427   const APInt *C2;
2428   if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2429     return nullptr;
2430 
2431   // Fold icmp pred (add X, C2), C.
2432   Value *X = Add->getOperand(0);
2433   Type *Ty = Add->getType();
2434   CmpInst::Predicate Pred = Cmp.getPredicate();
2435 
2436   if (!Add->hasOneUse())
2437     return nullptr;
2438 
2439   // If the add does not wrap, we can always adjust the compare by subtracting
2440   // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2441   // are canonicalized to SGT/SLT/UGT/ULT.
2442   if ((Add->hasNoSignedWrap() &&
2443        (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2444       (Add->hasNoUnsignedWrap() &&
2445        (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2446     bool Overflow;
2447     APInt NewC =
2448         Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2449     // If there is overflow, the result must be true or false.
2450     // TODO: Can we assert there is no overflow because InstSimplify always
2451     // handles those cases?
2452     if (!Overflow)
2453       // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2454       return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2455   }
2456 
2457   auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2458   const APInt &Upper = CR.getUpper();
2459   const APInt &Lower = CR.getLower();
2460   if (Cmp.isSigned()) {
2461     if (Lower.isSignMask())
2462       return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2463     if (Upper.isSignMask())
2464       return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2465   } else {
2466     if (Lower.isMinValue())
2467       return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2468     if (Upper.isMinValue())
2469       return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2470   }
2471 
2472   // X+C <u C2 -> (X & -C2) == C
2473   //   iff C & (C2-1) == 0
2474   //       C2 is a power of 2
2475   if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2476     return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2477                         ConstantExpr::getNeg(cast<Constant>(Y)));
2478 
2479   // X+C >u C2 -> (X & ~C2) != C
2480   //   iff C & C2 == 0
2481   //       C2+1 is a power of 2
2482   if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2483     return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2484                         ConstantExpr::getNeg(cast<Constant>(Y)));
2485 
2486   return nullptr;
2487 }
2488 
2489 bool InstCombiner::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
2490                                            Value *&RHS, ConstantInt *&Less,
2491                                            ConstantInt *&Equal,
2492                                            ConstantInt *&Greater) {
2493   // TODO: Generalize this to work with other comparison idioms or ensure
2494   // they get canonicalized into this form.
2495 
2496   // select i1 (a == b), i32 Equal, i32 (select i1 (a < b), i32 Less, i32
2497   // Greater), where Equal, Less and Greater are placeholders for any three
2498   // constants.
2499   ICmpInst::Predicate PredA, PredB;
2500   if (match(SI->getTrueValue(), m_ConstantInt(Equal)) &&
2501       match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) &&
2502       PredA == ICmpInst::ICMP_EQ &&
2503       match(SI->getFalseValue(),
2504             m_Select(m_ICmp(PredB, m_Specific(LHS), m_Specific(RHS)),
2505                      m_ConstantInt(Less), m_ConstantInt(Greater))) &&
2506       PredB == ICmpInst::ICMP_SLT) {
2507     return true;
2508   }
2509   return false;
2510 }
2511 
2512 Instruction *InstCombiner::foldICmpSelectConstant(ICmpInst &Cmp,
2513                                                   SelectInst *Select,
2514                                                   ConstantInt *C) {
2515 
2516   assert(C && "Cmp RHS should be a constant int!");
2517   // If we're testing a constant value against the result of a three way
2518   // comparison, the result can be expressed directly in terms of the
2519   // original values being compared.  Note: We could possibly be more
2520   // aggressive here and remove the hasOneUse test. The original select is
2521   // really likely to simplify or sink when we remove a test of the result.
2522   Value *OrigLHS, *OrigRHS;
2523   ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2524   if (Cmp.hasOneUse() &&
2525       matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2526                               C3GreaterThan)) {
2527     assert(C1LessThan && C2Equal && C3GreaterThan);
2528 
2529     bool TrueWhenLessThan =
2530         ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
2531             ->isAllOnesValue();
2532     bool TrueWhenEqual =
2533         ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
2534             ->isAllOnesValue();
2535     bool TrueWhenGreaterThan =
2536         ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
2537             ->isAllOnesValue();
2538 
2539     // This generates the new instruction that will replace the original Cmp
2540     // Instruction. Instead of enumerating the various combinations when
2541     // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
2542     // false, we rely on chaining of ORs and future passes of InstCombine to
2543     // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
2544 
2545     // When none of the three constants satisfy the predicate for the RHS (C),
2546     // the entire original Cmp can be simplified to a false.
2547     Value *Cond = Builder.getFalse();
2548     if (TrueWhenLessThan)
2549       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
2550                                                        OrigLHS, OrigRHS));
2551     if (TrueWhenEqual)
2552       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
2553                                                        OrigLHS, OrigRHS));
2554     if (TrueWhenGreaterThan)
2555       Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
2556                                                        OrigLHS, OrigRHS));
2557 
2558     return replaceInstUsesWith(Cmp, Cond);
2559   }
2560   return nullptr;
2561 }
2562 
2563 static Instruction *foldICmpBitCast(ICmpInst &Cmp,
2564                                     InstCombiner::BuilderTy &Builder) {
2565   auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
2566   if (!Bitcast)
2567     return nullptr;
2568 
2569   ICmpInst::Predicate Pred = Cmp.getPredicate();
2570   Value *Op1 = Cmp.getOperand(1);
2571   Value *BCSrcOp = Bitcast->getOperand(0);
2572 
2573   // Make sure the bitcast doesn't change the number of vector elements.
2574   if (Bitcast->getSrcTy()->getScalarSizeInBits() ==
2575           Bitcast->getDestTy()->getScalarSizeInBits()) {
2576     // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
2577     Value *X;
2578     if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
2579       // icmp  eq (bitcast (sitofp X)), 0 --> icmp  eq X, 0
2580       // icmp  ne (bitcast (sitofp X)), 0 --> icmp  ne X, 0
2581       // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
2582       // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
2583       if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
2584            Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
2585           match(Op1, m_Zero()))
2586         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2587 
2588       // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
2589       if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
2590         return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
2591 
2592       // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
2593       if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
2594         return new ICmpInst(Pred, X,
2595                             ConstantInt::getAllOnesValue(X->getType()));
2596     }
2597 
2598     // Zero-equality checks are preserved through unsigned floating-point casts:
2599     // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
2600     // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
2601     if (match(BCSrcOp, m_UIToFP(m_Value(X))))
2602       if (Cmp.isEquality() && match(Op1, m_Zero()))
2603         return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2604   }
2605 
2606   // Test to see if the operands of the icmp are casted versions of other
2607   // values. If the ptr->ptr cast can be stripped off both arguments, do so.
2608   if (Bitcast->getType()->isPointerTy() &&
2609       (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2610     // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2611     // so eliminate it as well.
2612     if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
2613       Op1 = BC2->getOperand(0);
2614 
2615     Op1 = Builder.CreateBitCast(Op1, BCSrcOp->getType());
2616     return new ICmpInst(Pred, BCSrcOp, Op1);
2617   }
2618 
2619   // Folding: icmp <pred> iN X, C
2620   //  where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
2621   //    and C is a splat of a K-bit pattern
2622   //    and SC is a constant vector = <C', C', C', ..., C'>
2623   // Into:
2624   //   %E = extractelement <M x iK> %vec, i32 C'
2625   //   icmp <pred> iK %E, trunc(C)
2626   const APInt *C;
2627   if (!match(Cmp.getOperand(1), m_APInt(C)) ||
2628       !Bitcast->getType()->isIntegerTy() ||
2629       !Bitcast->getSrcTy()->isIntOrIntVectorTy())
2630     return nullptr;
2631 
2632   Value *Vec;
2633   Constant *Mask;
2634   if (match(BCSrcOp,
2635             m_ShuffleVector(m_Value(Vec), m_Undef(), m_Constant(Mask)))) {
2636     // Check whether every element of Mask is the same constant
2637     if (auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->getSplatValue())) {
2638       auto *VecTy = cast<VectorType>(BCSrcOp->getType());
2639       auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2640       if (C->isSplat(EltTy->getBitWidth())) {
2641         // Fold the icmp based on the value of C
2642         // If C is M copies of an iK sized bit pattern,
2643         // then:
2644         //   =>  %E = extractelement <N x iK> %vec, i32 Elem
2645         //       icmp <pred> iK %SplatVal, <pattern>
2646         Value *Extract = Builder.CreateExtractElement(Vec, Elem);
2647         Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
2648         return new ICmpInst(Pred, Extract, NewC);
2649       }
2650     }
2651   }
2652   return nullptr;
2653 }
2654 
2655 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2656 /// where X is some kind of instruction.
2657 Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
2658   const APInt *C;
2659   if (!match(Cmp.getOperand(1), m_APInt(C)))
2660     return nullptr;
2661 
2662   if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) {
2663     switch (BO->getOpcode()) {
2664     case Instruction::Xor:
2665       if (Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2666         return I;
2667       break;
2668     case Instruction::And:
2669       if (Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2670         return I;
2671       break;
2672     case Instruction::Or:
2673       if (Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2674         return I;
2675       break;
2676     case Instruction::Mul:
2677       if (Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2678         return I;
2679       break;
2680     case Instruction::Shl:
2681       if (Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2682         return I;
2683       break;
2684     case Instruction::LShr:
2685     case Instruction::AShr:
2686       if (Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2687         return I;
2688       break;
2689     case Instruction::UDiv:
2690       if (Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2691         return I;
2692       LLVM_FALLTHROUGH;
2693     case Instruction::SDiv:
2694       if (Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2695         return I;
2696       break;
2697     case Instruction::Sub:
2698       if (Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2699         return I;
2700       break;
2701     case Instruction::Add:
2702       if (Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2703         return I;
2704       break;
2705     default:
2706       break;
2707     }
2708     // TODO: These folds could be refactored to be part of the above calls.
2709     if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2710       return I;
2711   }
2712 
2713   // Match against CmpInst LHS being instructions other than binary operators.
2714 
2715   if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) {
2716     // For now, we only support constant integers while folding the
2717     // ICMP(SELECT)) pattern. We can extend this to support vector of integers
2718     // similar to the cases handled by binary ops above.
2719     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
2720       if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2721         return I;
2722   }
2723 
2724   if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) {
2725     if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2726       return I;
2727   }
2728 
2729   if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
2730     if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
2731       return I;
2732 
2733   return nullptr;
2734 }
2735 
2736 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2737 /// icmp eq/ne BO, C.
2738 Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2739                                                              BinaryOperator *BO,
2740                                                              const APInt &C) {
2741   // TODO: Some of these folds could work with arbitrary constants, but this
2742   // function is limited to scalar and vector splat constants.
2743   if (!Cmp.isEquality())
2744     return nullptr;
2745 
2746   ICmpInst::Predicate Pred = Cmp.getPredicate();
2747   bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2748   Constant *RHS = cast<Constant>(Cmp.getOperand(1));
2749   Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2750 
2751   switch (BO->getOpcode()) {
2752   case Instruction::SRem:
2753     // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2754     if (C.isNullValue() && BO->hasOneUse()) {
2755       const APInt *BOC;
2756       if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
2757         Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
2758         return new ICmpInst(Pred, NewRem,
2759                             Constant::getNullValue(BO->getType()));
2760       }
2761     }
2762     break;
2763   case Instruction::Add: {
2764     // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2765     const APInt *BOC;
2766     if (match(BOp1, m_APInt(BOC))) {
2767       if (BO->hasOneUse()) {
2768         Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2769         return new ICmpInst(Pred, BOp0, SubC);
2770       }
2771     } else if (C.isNullValue()) {
2772       // Replace ((add A, B) != 0) with (A != -B) if A or B is
2773       // efficiently invertible, or if the add has just this one use.
2774       if (Value *NegVal = dyn_castNegVal(BOp1))
2775         return new ICmpInst(Pred, BOp0, NegVal);
2776       if (Value *NegVal = dyn_castNegVal(BOp0))
2777         return new ICmpInst(Pred, NegVal, BOp1);
2778       if (BO->hasOneUse()) {
2779         Value *Neg = Builder.CreateNeg(BOp1);
2780         Neg->takeName(BO);
2781         return new ICmpInst(Pred, BOp0, Neg);
2782       }
2783     }
2784     break;
2785   }
2786   case Instruction::Xor:
2787     if (BO->hasOneUse()) {
2788       if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
2789         // For the xor case, we can xor two constants together, eliminating
2790         // the explicit xor.
2791         return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2792       } else if (C.isNullValue()) {
2793         // Replace ((xor A, B) != 0) with (A != B)
2794         return new ICmpInst(Pred, BOp0, BOp1);
2795       }
2796     }
2797     break;
2798   case Instruction::Sub:
2799     if (BO->hasOneUse()) {
2800       const APInt *BOC;
2801       if (match(BOp0, m_APInt(BOC))) {
2802         // Replace ((sub BOC, B) != C) with (B != BOC-C).
2803         Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2804         return new ICmpInst(Pred, BOp1, SubC);
2805       } else if (C.isNullValue()) {
2806         // Replace ((sub A, B) != 0) with (A != B).
2807         return new ICmpInst(Pred, BOp0, BOp1);
2808       }
2809     }
2810     break;
2811   case Instruction::Or: {
2812     const APInt *BOC;
2813     if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
2814       // Comparing if all bits outside of a constant mask are set?
2815       // Replace (X | C) == -1 with (X & ~C) == ~C.
2816       // This removes the -1 constant.
2817       Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2818       Value *And = Builder.CreateAnd(BOp0, NotBOC);
2819       return new ICmpInst(Pred, And, NotBOC);
2820     }
2821     break;
2822   }
2823   case Instruction::And: {
2824     const APInt *BOC;
2825     if (match(BOp1, m_APInt(BOC))) {
2826       // If we have ((X & C) == C), turn it into ((X & C) != 0).
2827       if (C == *BOC && C.isPowerOf2())
2828         return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
2829                             BO, Constant::getNullValue(RHS->getType()));
2830     }
2831     break;
2832   }
2833   case Instruction::Mul:
2834     if (C.isNullValue() && BO->hasNoSignedWrap()) {
2835       const APInt *BOC;
2836       if (match(BOp1, m_APInt(BOC)) && !BOC->isNullValue()) {
2837         // The trivial case (mul X, 0) is handled by InstSimplify.
2838         // General case : (mul X, C) != 0 iff X != 0
2839         //                (mul X, C) == 0 iff X == 0
2840         return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
2841       }
2842     }
2843     break;
2844   case Instruction::UDiv:
2845     if (C.isNullValue()) {
2846       // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2847       auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2848       return new ICmpInst(NewPred, BOp1, BOp0);
2849     }
2850     break;
2851   default:
2852     break;
2853   }
2854   return nullptr;
2855 }
2856 
2857 /// Fold an equality icmp with LLVM intrinsic and constant operand.
2858 Instruction *InstCombiner::foldICmpEqIntrinsicWithConstant(ICmpInst &Cmp,
2859                                                            IntrinsicInst *II,
2860                                                            const APInt &C) {
2861   Type *Ty = II->getType();
2862   unsigned BitWidth = C.getBitWidth();
2863   switch (II->getIntrinsicID()) {
2864   case Intrinsic::bswap:
2865     Worklist.Add(II);
2866     Cmp.setOperand(0, II->getArgOperand(0));
2867     Cmp.setOperand(1, ConstantInt::get(Ty, C.byteSwap()));
2868     return &Cmp;
2869 
2870   case Intrinsic::ctlz:
2871   case Intrinsic::cttz: {
2872     // ctz(A) == bitwidth(A)  ->  A == 0 and likewise for !=
2873     if (C == BitWidth) {
2874       Worklist.Add(II);
2875       Cmp.setOperand(0, II->getArgOperand(0));
2876       Cmp.setOperand(1, ConstantInt::getNullValue(Ty));
2877       return &Cmp;
2878     }
2879 
2880     // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
2881     // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
2882     // Limit to one use to ensure we don't increase instruction count.
2883     unsigned Num = C.getLimitedValue(BitWidth);
2884     if (Num != BitWidth && II->hasOneUse()) {
2885       bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
2886       APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
2887                                : APInt::getHighBitsSet(BitWidth, Num + 1);
2888       APInt Mask2 = IsTrailing
2889         ? APInt::getOneBitSet(BitWidth, Num)
2890         : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
2891       Cmp.setOperand(0, Builder.CreateAnd(II->getArgOperand(0), Mask1));
2892       Cmp.setOperand(1, ConstantInt::get(Ty, Mask2));
2893       Worklist.Add(II);
2894       return &Cmp;
2895     }
2896     break;
2897   }
2898 
2899   case Intrinsic::ctpop: {
2900     // popcount(A) == 0  ->  A == 0 and likewise for !=
2901     // popcount(A) == bitwidth(A)  ->  A == -1 and likewise for !=
2902     bool IsZero = C.isNullValue();
2903     if (IsZero || C == BitWidth) {
2904       Worklist.Add(II);
2905       Cmp.setOperand(0, II->getArgOperand(0));
2906       auto *NewOp =
2907           IsZero ? Constant::getNullValue(Ty) : Constant::getAllOnesValue(Ty);
2908       Cmp.setOperand(1, NewOp);
2909       return &Cmp;
2910     }
2911     break;
2912   }
2913   default:
2914     break;
2915   }
2916 
2917   return nullptr;
2918 }
2919 
2920 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2921 Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2922                                                          IntrinsicInst *II,
2923                                                          const APInt &C) {
2924   if (Cmp.isEquality())
2925     return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
2926 
2927   Type *Ty = II->getType();
2928   unsigned BitWidth = C.getBitWidth();
2929   switch (II->getIntrinsicID()) {
2930   case Intrinsic::ctlz: {
2931     // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
2932     if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
2933       unsigned Num = C.getLimitedValue();
2934       APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
2935       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
2936                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
2937     }
2938 
2939     // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
2940     if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
2941         C.uge(1) && C.ule(BitWidth)) {
2942       unsigned Num = C.getLimitedValue();
2943       APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
2944       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
2945                              II->getArgOperand(0), ConstantInt::get(Ty, Limit));
2946     }
2947     break;
2948   }
2949   case Intrinsic::cttz: {
2950     // Limit to one use to ensure we don't increase instruction count.
2951     if (!II->hasOneUse())
2952       return nullptr;
2953 
2954     // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
2955     if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
2956       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
2957       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
2958                              Builder.CreateAnd(II->getArgOperand(0), Mask),
2959                              ConstantInt::getNullValue(Ty));
2960     }
2961 
2962     // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
2963     if (Cmp.getPredicate() == ICmpInst::ICMP_ULT &&
2964         C.uge(1) && C.ule(BitWidth)) {
2965       APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
2966       return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
2967                              Builder.CreateAnd(II->getArgOperand(0), Mask),
2968                              ConstantInt::getNullValue(Ty));
2969     }
2970     break;
2971   }
2972   default:
2973     break;
2974   }
2975 
2976   return nullptr;
2977 }
2978 
2979 /// Handle icmp with constant (but not simple integer constant) RHS.
2980 Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
2981   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2982   Constant *RHSC = dyn_cast<Constant>(Op1);
2983   Instruction *LHSI = dyn_cast<Instruction>(Op0);
2984   if (!RHSC || !LHSI)
2985     return nullptr;
2986 
2987   switch (LHSI->getOpcode()) {
2988   case Instruction::GetElementPtr:
2989     // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2990     if (RHSC->isNullValue() &&
2991         cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2992       return new ICmpInst(
2993           I.getPredicate(), LHSI->getOperand(0),
2994           Constant::getNullValue(LHSI->getOperand(0)->getType()));
2995     break;
2996   case Instruction::PHI:
2997     // Only fold icmp into the PHI if the phi and icmp are in the same
2998     // block.  If in the same block, we're encouraging jump threading.  If
2999     // not, we are just pessimizing the code by making an i1 phi.
3000     if (LHSI->getParent() == I.getParent())
3001       if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3002         return NV;
3003     break;
3004   case Instruction::Select: {
3005     // If either operand of the select is a constant, we can fold the
3006     // comparison into the select arms, which will cause one to be
3007     // constant folded and the select turned into a bitwise or.
3008     Value *Op1 = nullptr, *Op2 = nullptr;
3009     ConstantInt *CI = nullptr;
3010     if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3011       Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3012       CI = dyn_cast<ConstantInt>(Op1);
3013     }
3014     if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3015       Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3016       CI = dyn_cast<ConstantInt>(Op2);
3017     }
3018 
3019     // We only want to perform this transformation if it will not lead to
3020     // additional code. This is true if either both sides of the select
3021     // fold to a constant (in which case the icmp is replaced with a select
3022     // which will usually simplify) or this is the only user of the
3023     // select (in which case we are trading a select+icmp for a simpler
3024     // select+icmp) or all uses of the select can be replaced based on
3025     // dominance information ("Global cases").
3026     bool Transform = false;
3027     if (Op1 && Op2)
3028       Transform = true;
3029     else if (Op1 || Op2) {
3030       // Local case
3031       if (LHSI->hasOneUse())
3032         Transform = true;
3033       // Global cases
3034       else if (CI && !CI->isZero())
3035         // When Op1 is constant try replacing select with second operand.
3036         // Otherwise Op2 is constant and try replacing select with first
3037         // operand.
3038         Transform =
3039             replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
3040     }
3041     if (Transform) {
3042       if (!Op1)
3043         Op1 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
3044                                  I.getName());
3045       if (!Op2)
3046         Op2 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
3047                                  I.getName());
3048       return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3049     }
3050     break;
3051   }
3052   case Instruction::IntToPtr:
3053     // icmp pred inttoptr(X), null -> icmp pred X, 0
3054     if (RHSC->isNullValue() &&
3055         DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3056       return new ICmpInst(
3057           I.getPredicate(), LHSI->getOperand(0),
3058           Constant::getNullValue(LHSI->getOperand(0)->getType()));
3059     break;
3060 
3061   case Instruction::Load:
3062     // Try to optimize things like "A[i] > 4" to index computations.
3063     if (GetElementPtrInst *GEP =
3064             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3065       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3066         if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3067             !cast<LoadInst>(LHSI)->isVolatile())
3068           if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
3069             return Res;
3070     }
3071     break;
3072   }
3073 
3074   return nullptr;
3075 }
3076 
3077 /// Some comparisons can be simplified.
3078 /// In this case, we are looking for comparisons that look like
3079 /// a check for a lossy truncation.
3080 /// Folds:
3081 ///   icmp SrcPred (x & Mask), x    to    icmp DstPred x, Mask
3082 /// Where Mask is some pattern that produces all-ones in low bits:
3083 ///    (-1 >> y)
3084 ///    ((-1 << y) >> y)     <- non-canonical, has extra uses
3085 ///   ~(-1 << y)
3086 ///    ((1 << y) + (-1))    <- non-canonical, has extra uses
3087 /// The Mask can be a constant, too.
3088 /// For some predicates, the operands are commutative.
3089 /// For others, x can only be on a specific side.
3090 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
3091                                           InstCombiner::BuilderTy &Builder) {
3092   ICmpInst::Predicate SrcPred;
3093   Value *X, *M, *Y;
3094   auto m_VariableMask = m_CombineOr(
3095       m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
3096                   m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3097       m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
3098                   m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
3099   auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3100   if (!match(&I, m_c_ICmp(SrcPred,
3101                           m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
3102                           m_Deferred(X))))
3103     return nullptr;
3104 
3105   ICmpInst::Predicate DstPred;
3106   switch (SrcPred) {
3107   case ICmpInst::Predicate::ICMP_EQ:
3108     //  x & (-1 >> y) == x    ->    x u<= (-1 >> y)
3109     DstPred = ICmpInst::Predicate::ICMP_ULE;
3110     break;
3111   case ICmpInst::Predicate::ICMP_NE:
3112     //  x & (-1 >> y) != x    ->    x u> (-1 >> y)
3113     DstPred = ICmpInst::Predicate::ICMP_UGT;
3114     break;
3115   case ICmpInst::Predicate::ICMP_UGT:
3116     //  x u> x & (-1 >> y)    ->    x u> (-1 >> y)
3117     assert(X == I.getOperand(0) && "instsimplify took care of commut. variant");
3118     DstPred = ICmpInst::Predicate::ICMP_UGT;
3119     break;
3120   case ICmpInst::Predicate::ICMP_UGE:
3121     //  x & (-1 >> y) u>= x    ->    x u<= (-1 >> y)
3122     assert(X == I.getOperand(1) && "instsimplify took care of commut. variant");
3123     DstPred = ICmpInst::Predicate::ICMP_ULE;
3124     break;
3125   case ICmpInst::Predicate::ICMP_ULT:
3126     //  x & (-1 >> y) u< x    ->    x u> (-1 >> y)
3127     assert(X == I.getOperand(1) && "instsimplify took care of commut. variant");
3128     DstPred = ICmpInst::Predicate::ICMP_UGT;
3129     break;
3130   case ICmpInst::Predicate::ICMP_ULE:
3131     //  x u<= x & (-1 >> y)    ->    x u<= (-1 >> y)
3132     assert(X == I.getOperand(0) && "instsimplify took care of commut. variant");
3133     DstPred = ICmpInst::Predicate::ICMP_ULE;
3134     break;
3135   case ICmpInst::Predicate::ICMP_SGT:
3136     //  x s> x & (-1 >> y)    ->    x s> (-1 >> y)
3137     if (X != I.getOperand(0)) // X must be on LHS of comparison!
3138       return nullptr;         // Ignore the other case.
3139     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3140       return nullptr;
3141     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3142       return nullptr;
3143     DstPred = ICmpInst::Predicate::ICMP_SGT;
3144     break;
3145   case ICmpInst::Predicate::ICMP_SGE:
3146     //  x & (-1 >> y) s>= x    ->    x s<= (-1 >> y)
3147     if (X != I.getOperand(1)) // X must be on RHS of comparison!
3148       return nullptr;         // Ignore the other case.
3149     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3150       return nullptr;
3151     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3152       return nullptr;
3153     DstPred = ICmpInst::Predicate::ICMP_SLE;
3154     break;
3155   case ICmpInst::Predicate::ICMP_SLT:
3156     //  x & (-1 >> y) s< x    ->    x s> (-1 >> y)
3157     if (X != I.getOperand(1)) // X must be on RHS of comparison!
3158       return nullptr;         // Ignore the other case.
3159     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3160       return nullptr;
3161     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3162       return nullptr;
3163     DstPred = ICmpInst::Predicate::ICMP_SGT;
3164     break;
3165   case ICmpInst::Predicate::ICMP_SLE:
3166     //  x s<= x & (-1 >> y)    ->    x s<= (-1 >> y)
3167     if (X != I.getOperand(0)) // X must be on LHS of comparison!
3168       return nullptr;         // Ignore the other case.
3169     if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3170       return nullptr;
3171     if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3172       return nullptr;
3173     DstPred = ICmpInst::Predicate::ICMP_SLE;
3174     break;
3175   default:
3176     llvm_unreachable("All possible folds are handled.");
3177   }
3178 
3179   return Builder.CreateICmp(DstPred, X, M);
3180 }
3181 
3182 /// Some comparisons can be simplified.
3183 /// In this case, we are looking for comparisons that look like
3184 /// a check for a lossy signed truncation.
3185 /// Folds:   (MaskedBits is a constant.)
3186 ///   ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3187 /// Into:
3188 ///   (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3189 /// Where  KeptBits = bitwidth(%x) - MaskedBits
3190 static Value *
3191 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
3192                                  InstCombiner::BuilderTy &Builder) {
3193   ICmpInst::Predicate SrcPred;
3194   Value *X;
3195   const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3196   // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3197   if (!match(&I, m_c_ICmp(SrcPred,
3198                           m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
3199                                           m_APInt(C1))),
3200                           m_Deferred(X))))
3201     return nullptr;
3202 
3203   // Potential handling of non-splats: for each element:
3204   //  * if both are undef, replace with constant 0.
3205   //    Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3206   //  * if both are not undef, and are different, bailout.
3207   //  * else, only one is undef, then pick the non-undef one.
3208 
3209   // The shift amount must be equal.
3210   if (*C0 != *C1)
3211     return nullptr;
3212   const APInt &MaskedBits = *C0;
3213   assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3214 
3215   ICmpInst::Predicate DstPred;
3216   switch (SrcPred) {
3217   case ICmpInst::Predicate::ICMP_EQ:
3218     // ((%x << MaskedBits) a>> MaskedBits) == %x
3219     //   =>
3220     // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3221     DstPred = ICmpInst::Predicate::ICMP_ULT;
3222     break;
3223   case ICmpInst::Predicate::ICMP_NE:
3224     // ((%x << MaskedBits) a>> MaskedBits) != %x
3225     //   =>
3226     // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3227     DstPred = ICmpInst::Predicate::ICMP_UGE;
3228     break;
3229   // FIXME: are more folds possible?
3230   default:
3231     return nullptr;
3232   }
3233 
3234   auto *XType = X->getType();
3235   const unsigned XBitWidth = XType->getScalarSizeInBits();
3236   const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3237   assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3238 
3239   // KeptBits = bitwidth(%x) - MaskedBits
3240   const APInt KeptBits = BitWidth - MaskedBits;
3241   assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3242   // ICmpCst = (1 << KeptBits)
3243   const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3244   assert(ICmpCst.isPowerOf2());
3245   // AddCst = (1 << (KeptBits-1))
3246   const APInt AddCst = ICmpCst.lshr(1);
3247   assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3248 
3249   // T0 = add %x, AddCst
3250   Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3251   // T1 = T0 DstPred ICmpCst
3252   Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3253 
3254   return T1;
3255 }
3256 
3257 /// Try to fold icmp (binop), X or icmp X, (binop).
3258 /// TODO: A large part of this logic is duplicated in InstSimplify's
3259 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
3260 /// duplication.
3261 Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) {
3262   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3263 
3264   // Special logic for binary operators.
3265   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3266   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3267   if (!BO0 && !BO1)
3268     return nullptr;
3269 
3270   const CmpInst::Predicate Pred = I.getPredicate();
3271   Value *X;
3272 
3273   // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
3274   // (Op1 + X) <u Op1 --> ~Op1 <u X
3275   // Op0 >u (Op0 + X) --> X >u ~Op0
3276   if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
3277       Pred == ICmpInst::ICMP_ULT)
3278     return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
3279   if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
3280       Pred == ICmpInst::ICMP_UGT)
3281     return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
3282 
3283   bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3284   if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3285     NoOp0WrapProblem =
3286         ICmpInst::isEquality(Pred) ||
3287         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3288         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3289   if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3290     NoOp1WrapProblem =
3291         ICmpInst::isEquality(Pred) ||
3292         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3293         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3294 
3295   // Analyze the case when either Op0 or Op1 is an add instruction.
3296   // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
3297   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3298   if (BO0 && BO0->getOpcode() == Instruction::Add) {
3299     A = BO0->getOperand(0);
3300     B = BO0->getOperand(1);
3301   }
3302   if (BO1 && BO1->getOpcode() == Instruction::Add) {
3303     C = BO1->getOperand(0);
3304     D = BO1->getOperand(1);
3305   }
3306 
3307   // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3308   if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3309     return new ICmpInst(Pred, A == Op1 ? B : A,
3310                         Constant::getNullValue(Op1->getType()));
3311 
3312   // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3313   if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3314     return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3315                         C == Op0 ? D : C);
3316 
3317   // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
3318   if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
3319       NoOp1WrapProblem &&
3320       // Try not to increase register pressure.
3321       BO0->hasOneUse() && BO1->hasOneUse()) {
3322     // Determine Y and Z in the form icmp (X+Y), (X+Z).
3323     Value *Y, *Z;
3324     if (A == C) {
3325       // C + B == C + D  ->  B == D
3326       Y = B;
3327       Z = D;
3328     } else if (A == D) {
3329       // D + B == C + D  ->  B == C
3330       Y = B;
3331       Z = C;
3332     } else if (B == C) {
3333       // A + C == C + D  ->  A == D
3334       Y = A;
3335       Z = D;
3336     } else {
3337       assert(B == D);
3338       // A + D == C + D  ->  A == C
3339       Y = A;
3340       Z = C;
3341     }
3342     return new ICmpInst(Pred, Y, Z);
3343   }
3344 
3345   // icmp slt (X + -1), Y -> icmp sle X, Y
3346   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3347       match(B, m_AllOnes()))
3348     return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3349 
3350   // icmp sge (X + -1), Y -> icmp sgt X, Y
3351   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3352       match(B, m_AllOnes()))
3353     return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3354 
3355   // icmp sle (X + 1), Y -> icmp slt X, Y
3356   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
3357     return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3358 
3359   // icmp sgt (X + 1), Y -> icmp sge X, Y
3360   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
3361     return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3362 
3363   // icmp sgt X, (Y + -1) -> icmp sge X, Y
3364   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3365       match(D, m_AllOnes()))
3366     return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3367 
3368   // icmp sle X, (Y + -1) -> icmp slt X, Y
3369   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3370       match(D, m_AllOnes()))
3371     return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3372 
3373   // icmp sge X, (Y + 1) -> icmp sgt X, Y
3374   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
3375     return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3376 
3377   // icmp slt X, (Y + 1) -> icmp sle X, Y
3378   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
3379     return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3380 
3381   // TODO: The subtraction-related identities shown below also hold, but
3382   // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
3383   // wouldn't happen even if they were implemented.
3384   //
3385   // icmp ult (X - 1), Y -> icmp ule X, Y
3386   // icmp uge (X - 1), Y -> icmp ugt X, Y
3387   // icmp ugt X, (Y - 1) -> icmp uge X, Y
3388   // icmp ule X, (Y - 1) -> icmp ult X, Y
3389 
3390   // icmp ule (X + 1), Y -> icmp ult X, Y
3391   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
3392     return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
3393 
3394   // icmp ugt (X + 1), Y -> icmp uge X, Y
3395   if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
3396     return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
3397 
3398   // icmp uge X, (Y + 1) -> icmp ugt X, Y
3399   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
3400     return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
3401 
3402   // icmp ult X, (Y + 1) -> icmp ule X, Y
3403   if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
3404     return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
3405 
3406   // if C1 has greater magnitude than C2:
3407   //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3408   //  s.t. C3 = C1 - C2
3409   //
3410   // if C2 has greater magnitude than C1:
3411   //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3412   //  s.t. C3 = C2 - C1
3413   if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3414       (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3415     if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3416       if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3417         const APInt &AP1 = C1->getValue();
3418         const APInt &AP2 = C2->getValue();
3419         if (AP1.isNegative() == AP2.isNegative()) {
3420           APInt AP1Abs = C1->getValue().abs();
3421           APInt AP2Abs = C2->getValue().abs();
3422           if (AP1Abs.uge(AP2Abs)) {
3423             ConstantInt *C3 = Builder.getInt(AP1 - AP2);
3424             Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3425             return new ICmpInst(Pred, NewAdd, C);
3426           } else {
3427             ConstantInt *C3 = Builder.getInt(AP2 - AP1);
3428             Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3429             return new ICmpInst(Pred, A, NewAdd);
3430           }
3431         }
3432       }
3433 
3434   // Analyze the case when either Op0 or Op1 is a sub instruction.
3435   // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
3436   A = nullptr;
3437   B = nullptr;
3438   C = nullptr;
3439   D = nullptr;
3440   if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3441     A = BO0->getOperand(0);
3442     B = BO0->getOperand(1);
3443   }
3444   if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3445     C = BO1->getOperand(0);
3446     D = BO1->getOperand(1);
3447   }
3448 
3449   // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3450   if (A == Op1 && NoOp0WrapProblem)
3451     return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3452   // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3453   if (C == Op0 && NoOp1WrapProblem)
3454     return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3455 
3456   // (A - B) >u A --> A <u B
3457   if (A == Op1 && Pred == ICmpInst::ICMP_UGT)
3458     return new ICmpInst(ICmpInst::ICMP_ULT, A, B);
3459   // C <u (C - D) --> C <u D
3460   if (C == Op0 && Pred == ICmpInst::ICMP_ULT)
3461     return new ICmpInst(ICmpInst::ICMP_ULT, C, D);
3462 
3463   // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
3464   if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3465       // Try not to increase register pressure.
3466       BO0->hasOneUse() && BO1->hasOneUse())
3467     return new ICmpInst(Pred, A, C);
3468   // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3469   if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3470       // Try not to increase register pressure.
3471       BO0->hasOneUse() && BO1->hasOneUse())
3472     return new ICmpInst(Pred, D, B);
3473 
3474   // icmp (0-X) < cst --> x > -cst
3475   if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3476     Value *X;
3477     if (match(BO0, m_Neg(m_Value(X))))
3478       if (Constant *RHSC = dyn_cast<Constant>(Op1))
3479         if (RHSC->isNotMinSignedValue())
3480           return new ICmpInst(I.getSwappedPredicate(), X,
3481                               ConstantExpr::getNeg(RHSC));
3482   }
3483 
3484   BinaryOperator *SRem = nullptr;
3485   // icmp (srem X, Y), Y
3486   if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
3487     SRem = BO0;
3488   // icmp Y, (srem X, Y)
3489   else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3490            Op0 == BO1->getOperand(1))
3491     SRem = BO1;
3492   if (SRem) {
3493     // We don't check hasOneUse to avoid increasing register pressure because
3494     // the value we use is the same value this instruction was already using.
3495     switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3496     default:
3497       break;
3498     case ICmpInst::ICMP_EQ:
3499       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3500     case ICmpInst::ICMP_NE:
3501       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3502     case ICmpInst::ICMP_SGT:
3503     case ICmpInst::ICMP_SGE:
3504       return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3505                           Constant::getAllOnesValue(SRem->getType()));
3506     case ICmpInst::ICMP_SLT:
3507     case ICmpInst::ICMP_SLE:
3508       return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3509                           Constant::getNullValue(SRem->getType()));
3510     }
3511   }
3512 
3513   if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
3514       BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
3515     switch (BO0->getOpcode()) {
3516     default:
3517       break;
3518     case Instruction::Add:
3519     case Instruction::Sub:
3520     case Instruction::Xor: {
3521       if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3522         return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3523 
3524       const APInt *C;
3525       if (match(BO0->getOperand(1), m_APInt(C))) {
3526         // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
3527         if (C->isSignMask()) {
3528           ICmpInst::Predicate NewPred =
3529               I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3530           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3531         }
3532 
3533         // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
3534         if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
3535           ICmpInst::Predicate NewPred =
3536               I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
3537           NewPred = I.getSwappedPredicate(NewPred);
3538           return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
3539         }
3540       }
3541       break;
3542     }
3543     case Instruction::Mul: {
3544       if (!I.isEquality())
3545         break;
3546 
3547       const APInt *C;
3548       if (match(BO0->getOperand(1), m_APInt(C)) && !C->isNullValue() &&
3549           !C->isOneValue()) {
3550         // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
3551         // Mask = -1 >> count-trailing-zeros(C).
3552         if (unsigned TZs = C->countTrailingZeros()) {
3553           Constant *Mask = ConstantInt::get(
3554               BO0->getType(),
3555               APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
3556           Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
3557           Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
3558           return new ICmpInst(Pred, And1, And2);
3559         }
3560         // If there are no trailing zeros in the multiplier, just eliminate
3561         // the multiplies (no masking is needed):
3562         // icmp eq/ne (X * C), (Y * C) --> icmp eq/ne X, Y
3563         return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3564       }
3565       break;
3566     }
3567     case Instruction::UDiv:
3568     case Instruction::LShr:
3569       if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
3570         break;
3571       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3572 
3573     case Instruction::SDiv:
3574       if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
3575         break;
3576       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3577 
3578     case Instruction::AShr:
3579       if (!BO0->isExact() || !BO1->isExact())
3580         break;
3581       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3582 
3583     case Instruction::Shl: {
3584       bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3585       bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3586       if (!NUW && !NSW)
3587         break;
3588       if (!NSW && I.isSigned())
3589         break;
3590       return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
3591     }
3592     }
3593   }
3594 
3595   if (BO0) {
3596     // Transform  A & (L - 1) `ult` L --> L != 0
3597     auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3598     auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
3599 
3600     if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
3601       auto *Zero = Constant::getNullValue(BO0->getType());
3602       return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3603     }
3604   }
3605 
3606   if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
3607     return replaceInstUsesWith(I, V);
3608 
3609   if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
3610     return replaceInstUsesWith(I, V);
3611 
3612   return nullptr;
3613 }
3614 
3615 /// Fold icmp Pred min|max(X, Y), X.
3616 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
3617   ICmpInst::Predicate Pred = Cmp.getPredicate();
3618   Value *Op0 = Cmp.getOperand(0);
3619   Value *X = Cmp.getOperand(1);
3620 
3621   // Canonicalize minimum or maximum operand to LHS of the icmp.
3622   if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
3623       match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
3624       match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
3625       match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
3626     std::swap(Op0, X);
3627     Pred = Cmp.getSwappedPredicate();
3628   }
3629 
3630   Value *Y;
3631   if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
3632     // smin(X, Y)  == X --> X s<= Y
3633     // smin(X, Y) s>= X --> X s<= Y
3634     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
3635       return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3636 
3637     // smin(X, Y) != X --> X s> Y
3638     // smin(X, Y) s< X --> X s> Y
3639     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
3640       return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3641 
3642     // These cases should be handled in InstSimplify:
3643     // smin(X, Y) s<= X --> true
3644     // smin(X, Y) s> X --> false
3645     return nullptr;
3646   }
3647 
3648   if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
3649     // smax(X, Y)  == X --> X s>= Y
3650     // smax(X, Y) s<= X --> X s>= Y
3651     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
3652       return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3653 
3654     // smax(X, Y) != X --> X s< Y
3655     // smax(X, Y) s> X --> X s< Y
3656     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
3657       return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3658 
3659     // These cases should be handled in InstSimplify:
3660     // smax(X, Y) s>= X --> true
3661     // smax(X, Y) s< X --> false
3662     return nullptr;
3663   }
3664 
3665   if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
3666     // umin(X, Y)  == X --> X u<= Y
3667     // umin(X, Y) u>= X --> X u<= Y
3668     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
3669       return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
3670 
3671     // umin(X, Y) != X --> X u> Y
3672     // umin(X, Y) u< X --> X u> Y
3673     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
3674       return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
3675 
3676     // These cases should be handled in InstSimplify:
3677     // umin(X, Y) u<= X --> true
3678     // umin(X, Y) u> X --> false
3679     return nullptr;
3680   }
3681 
3682   if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
3683     // umax(X, Y)  == X --> X u>= Y
3684     // umax(X, Y) u<= X --> X u>= Y
3685     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
3686       return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
3687 
3688     // umax(X, Y) != X --> X u< Y
3689     // umax(X, Y) u> X --> X u< Y
3690     if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
3691       return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
3692 
3693     // These cases should be handled in InstSimplify:
3694     // umax(X, Y) u>= X --> true
3695     // umax(X, Y) u< X --> false
3696     return nullptr;
3697   }
3698 
3699   return nullptr;
3700 }
3701 
3702 Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
3703   if (!I.isEquality())
3704     return nullptr;
3705 
3706   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3707   const CmpInst::Predicate Pred = I.getPredicate();
3708   Value *A, *B, *C, *D;
3709   if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3710     if (A == Op1 || B == Op1) { // (A^B) == A  ->  B == 0
3711       Value *OtherVal = A == Op1 ? B : A;
3712       return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
3713     }
3714 
3715     if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3716       // A^c1 == C^c2 --> A == C^(c1^c2)
3717       ConstantInt *C1, *C2;
3718       if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
3719           Op1->hasOneUse()) {
3720         Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
3721         Value *Xor = Builder.CreateXor(C, NC);
3722         return new ICmpInst(Pred, A, Xor);
3723       }
3724 
3725       // A^B == A^D -> B == D
3726       if (A == C)
3727         return new ICmpInst(Pred, B, D);
3728       if (A == D)
3729         return new ICmpInst(Pred, B, C);
3730       if (B == C)
3731         return new ICmpInst(Pred, A, D);
3732       if (B == D)
3733         return new ICmpInst(Pred, A, C);
3734     }
3735   }
3736 
3737   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
3738     // A == (A^B)  ->  B == 0
3739     Value *OtherVal = A == Op0 ? B : A;
3740     return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
3741   }
3742 
3743   // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3744   if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3745       match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3746     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3747 
3748     if (A == C) {
3749       X = B;
3750       Y = D;
3751       Z = A;
3752     } else if (A == D) {
3753       X = B;
3754       Y = C;
3755       Z = A;
3756     } else if (B == C) {
3757       X = A;
3758       Y = D;
3759       Z = B;
3760     } else if (B == D) {
3761       X = A;
3762       Y = C;
3763       Z = B;
3764     }
3765 
3766     if (X) { // Build (X^Y) & Z
3767       Op1 = Builder.CreateXor(X, Y);
3768       Op1 = Builder.CreateAnd(Op1, Z);
3769       I.setOperand(0, Op1);
3770       I.setOperand(1, Constant::getNullValue(Op1->getType()));
3771       return &I;
3772     }
3773   }
3774 
3775   // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3776   // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3777   ConstantInt *Cst1;
3778   if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
3779        match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3780       (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3781        match(Op1, m_ZExt(m_Value(A))))) {
3782     APInt Pow2 = Cst1->getValue() + 1;
3783     if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3784         Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3785       return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
3786   }
3787 
3788   // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3789   // For lshr and ashr pairs.
3790   if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3791        match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3792       (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3793        match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3794     unsigned TypeBits = Cst1->getBitWidth();
3795     unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3796     if (ShAmt < TypeBits && ShAmt != 0) {
3797       ICmpInst::Predicate NewPred =
3798           Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
3799       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
3800       APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3801       return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
3802     }
3803   }
3804 
3805   // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3806   if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3807       match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3808     unsigned TypeBits = Cst1->getBitWidth();
3809     unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3810     if (ShAmt < TypeBits && ShAmt != 0) {
3811       Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
3812       APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3813       Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
3814                                       I.getName() + ".mask");
3815       return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
3816     }
3817   }
3818 
3819   // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3820   // "icmp (and X, mask), cst"
3821   uint64_t ShAmt = 0;
3822   if (Op0->hasOneUse() &&
3823       match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
3824       match(Op1, m_ConstantInt(Cst1)) &&
3825       // Only do this when A has multiple uses.  This is most important to do
3826       // when it exposes other optimizations.
3827       !A->hasOneUse()) {
3828     unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
3829 
3830     if (ShAmt < ASize) {
3831       APInt MaskV =
3832           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3833       MaskV <<= ShAmt;
3834 
3835       APInt CmpV = Cst1->getValue().zext(ASize);
3836       CmpV <<= ShAmt;
3837 
3838       Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
3839       return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
3840     }
3841   }
3842 
3843   // If both operands are byte-swapped or bit-reversed, just compare the
3844   // original values.
3845   // TODO: Move this to a function similar to foldICmpIntrinsicWithConstant()
3846   // and handle more intrinsics.
3847   if ((match(Op0, m_BSwap(m_Value(A))) && match(Op1, m_BSwap(m_Value(B)))) ||
3848       (match(Op0, m_BitReverse(m_Value(A))) &&
3849        match(Op1, m_BitReverse(m_Value(B)))))
3850     return new ICmpInst(Pred, A, B);
3851 
3852   // Canonicalize checking for a power-of-2-or-zero value:
3853   // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
3854   // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
3855   A = nullptr;
3856   if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
3857     A = Op1;
3858   else if (match(Op1,
3859                  m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
3860     A = Op0;
3861 
3862   if (A) {
3863     Type *Ty = A->getType();
3864     CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
3865     return Pred == ICmpInst::ICMP_EQ
3866         ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2))
3867         : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1));
3868   }
3869 
3870   return nullptr;
3871 }
3872 
3873 /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
3874 /// far.
3875 Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
3876   const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
3877   Value *LHSCIOp        = LHSCI->getOperand(0);
3878   Type *SrcTy     = LHSCIOp->getType();
3879   Type *DestTy    = LHSCI->getType();
3880 
3881   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
3882   // integer type is the same size as the pointer type.
3883   const auto& CompatibleSizes = [&](Type* SrcTy, Type* DestTy) -> bool {
3884     if (isa<VectorType>(SrcTy)) {
3885       SrcTy = cast<VectorType>(SrcTy)->getElementType();
3886       DestTy = cast<VectorType>(DestTy)->getElementType();
3887     }
3888     return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
3889   };
3890   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
3891       CompatibleSizes(SrcTy, DestTy)) {
3892     Value *RHSOp = nullptr;
3893     if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
3894       Value *RHSCIOp = RHSC->getOperand(0);
3895       if (RHSCIOp->getType()->getPointerAddressSpace() ==
3896           LHSCIOp->getType()->getPointerAddressSpace()) {
3897         RHSOp = RHSC->getOperand(0);
3898         // If the pointer types don't match, insert a bitcast.
3899         if (LHSCIOp->getType() != RHSOp->getType())
3900           RHSOp = Builder.CreateBitCast(RHSOp, LHSCIOp->getType());
3901       }
3902     } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
3903       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
3904     }
3905 
3906     if (RHSOp)
3907       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
3908   }
3909 
3910   // The code below only handles extension cast instructions, so far.
3911   // Enforce this.
3912   if (LHSCI->getOpcode() != Instruction::ZExt &&
3913       LHSCI->getOpcode() != Instruction::SExt)
3914     return nullptr;
3915 
3916   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
3917   bool isSignedCmp = ICmp.isSigned();
3918 
3919   if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
3920     // Not an extension from the same type?
3921     Value *RHSCIOp = CI->getOperand(0);
3922     if (RHSCIOp->getType() != LHSCIOp->getType())
3923       return nullptr;
3924 
3925     // If the signedness of the two casts doesn't agree (i.e. one is a sext
3926     // and the other is a zext), then we can't handle this.
3927     if (CI->getOpcode() != LHSCI->getOpcode())
3928       return nullptr;
3929 
3930     // Deal with equality cases early.
3931     if (ICmp.isEquality())
3932       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
3933 
3934     // A signed comparison of sign extended values simplifies into a
3935     // signed comparison.
3936     if (isSignedCmp && isSignedExt)
3937       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
3938 
3939     // The other three cases all fold into an unsigned comparison.
3940     return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
3941   }
3942 
3943   // If we aren't dealing with a constant on the RHS, exit early.
3944   auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
3945   if (!C)
3946     return nullptr;
3947 
3948   // Compute the constant that would happen if we truncated to SrcTy then
3949   // re-extended to DestTy.
3950   Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
3951   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
3952 
3953   // If the re-extended constant didn't change...
3954   if (Res2 == C) {
3955     // Deal with equality cases early.
3956     if (ICmp.isEquality())
3957       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
3958 
3959     // A signed comparison of sign extended values simplifies into a
3960     // signed comparison.
3961     if (isSignedExt && isSignedCmp)
3962       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
3963 
3964     // The other three cases all fold into an unsigned comparison.
3965     return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
3966   }
3967 
3968   // The re-extended constant changed, partly changed (in the case of a vector),
3969   // or could not be determined to be equal (in the case of a constant
3970   // expression), so the constant cannot be represented in the shorter type.
3971   // Consequently, we cannot emit a simple comparison.
3972   // All the cases that fold to true or false will have already been handled
3973   // by SimplifyICmpInst, so only deal with the tricky case.
3974 
3975   if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
3976     return nullptr;
3977 
3978   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
3979   // should have been folded away previously and not enter in here.
3980 
3981   // We're performing an unsigned comp with a sign extended value.
3982   // This is true if the input is >= 0. [aka >s -1]
3983   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
3984   Value *Result = Builder.CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
3985 
3986   // Finally, return the value computed.
3987   if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
3988     return replaceInstUsesWith(ICmp, Result);
3989 
3990   assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
3991   return BinaryOperator::CreateNot(Result);
3992 }
3993 
3994 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS) {
3995   switch (BinaryOp) {
3996     default:
3997       llvm_unreachable("Unsupported binary op");
3998     case Instruction::Add:
3999     case Instruction::Sub:
4000       return match(RHS, m_Zero());
4001     case Instruction::Mul:
4002       return match(RHS, m_One());
4003   }
4004 }
4005 
4006 OverflowResult InstCombiner::computeOverflow(
4007     Instruction::BinaryOps BinaryOp, bool IsSigned,
4008     Value *LHS, Value *RHS, Instruction *CxtI) const {
4009   switch (BinaryOp) {
4010     default:
4011       llvm_unreachable("Unsupported binary op");
4012     case Instruction::Add:
4013       if (IsSigned)
4014         return computeOverflowForSignedAdd(LHS, RHS, CxtI);
4015       else
4016         return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
4017     case Instruction::Sub:
4018       if (IsSigned)
4019         return computeOverflowForSignedSub(LHS, RHS, CxtI);
4020       else
4021         return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
4022     case Instruction::Mul:
4023       if (IsSigned)
4024         return computeOverflowForSignedMul(LHS, RHS, CxtI);
4025       else
4026         return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
4027   }
4028 }
4029 
4030 bool InstCombiner::OptimizeOverflowCheck(
4031     Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS,
4032     Instruction &OrigI, Value *&Result, Constant *&Overflow) {
4033   if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
4034     std::swap(LHS, RHS);
4035 
4036   // If the overflow check was an add followed by a compare, the insertion point
4037   // may be pointing to the compare.  We want to insert the new instructions
4038   // before the add in case there are uses of the add between the add and the
4039   // compare.
4040   Builder.SetInsertPoint(&OrigI);
4041 
4042   if (isNeutralValue(BinaryOp, RHS)) {
4043     Result = LHS;
4044     Overflow = Builder.getFalse();
4045     return true;
4046   }
4047 
4048   switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
4049     case OverflowResult::MayOverflow:
4050       return false;
4051     case OverflowResult::AlwaysOverflowsLow:
4052     case OverflowResult::AlwaysOverflowsHigh:
4053       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4054       Result->takeName(&OrigI);
4055       Overflow = Builder.getTrue();
4056       return true;
4057     case OverflowResult::NeverOverflows:
4058       Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
4059       Result->takeName(&OrigI);
4060       Overflow = Builder.getFalse();
4061       if (auto *Inst = dyn_cast<Instruction>(Result)) {
4062         if (IsSigned)
4063           Inst->setHasNoSignedWrap();
4064         else
4065           Inst->setHasNoUnsignedWrap();
4066       }
4067       return true;
4068   }
4069 
4070   llvm_unreachable("Unexpected overflow result");
4071 }
4072 
4073 /// Recognize and process idiom involving test for multiplication
4074 /// overflow.
4075 ///
4076 /// The caller has matched a pattern of the form:
4077 ///   I = cmp u (mul(zext A, zext B), V
4078 /// The function checks if this is a test for overflow and if so replaces
4079 /// multiplication with call to 'mul.with.overflow' intrinsic.
4080 ///
4081 /// \param I Compare instruction.
4082 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
4083 ///               the compare instruction.  Must be of integer type.
4084 /// \param OtherVal The other argument of compare instruction.
4085 /// \returns Instruction which must replace the compare instruction, NULL if no
4086 ///          replacement required.
4087 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
4088                                          Value *OtherVal, InstCombiner &IC) {
4089   // Don't bother doing this transformation for pointers, don't do it for
4090   // vectors.
4091   if (!isa<IntegerType>(MulVal->getType()))
4092     return nullptr;
4093 
4094   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
4095   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
4096   auto *MulInstr = dyn_cast<Instruction>(MulVal);
4097   if (!MulInstr)
4098     return nullptr;
4099   assert(MulInstr->getOpcode() == Instruction::Mul);
4100 
4101   auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
4102        *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
4103   assert(LHS->getOpcode() == Instruction::ZExt);
4104   assert(RHS->getOpcode() == Instruction::ZExt);
4105   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
4106 
4107   // Calculate type and width of the result produced by mul.with.overflow.
4108   Type *TyA = A->getType(), *TyB = B->getType();
4109   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
4110            WidthB = TyB->getPrimitiveSizeInBits();
4111   unsigned MulWidth;
4112   Type *MulType;
4113   if (WidthB > WidthA) {
4114     MulWidth = WidthB;
4115     MulType = TyB;
4116   } else {
4117     MulWidth = WidthA;
4118     MulType = TyA;
4119   }
4120 
4121   // In order to replace the original mul with a narrower mul.with.overflow,
4122   // all uses must ignore upper bits of the product.  The number of used low
4123   // bits must be not greater than the width of mul.with.overflow.
4124   if (MulVal->hasNUsesOrMore(2))
4125     for (User *U : MulVal->users()) {
4126       if (U == &I)
4127         continue;
4128       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4129         // Check if truncation ignores bits above MulWidth.
4130         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
4131         if (TruncWidth > MulWidth)
4132           return nullptr;
4133       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4134         // Check if AND ignores bits above MulWidth.
4135         if (BO->getOpcode() != Instruction::And)
4136           return nullptr;
4137         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4138           const APInt &CVal = CI->getValue();
4139           if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
4140             return nullptr;
4141         } else {
4142           // In this case we could have the operand of the binary operation
4143           // being defined in another block, and performing the replacement
4144           // could break the dominance relation.
4145           return nullptr;
4146         }
4147       } else {
4148         // Other uses prohibit this transformation.
4149         return nullptr;
4150       }
4151     }
4152 
4153   // Recognize patterns
4154   switch (I.getPredicate()) {
4155   case ICmpInst::ICMP_EQ:
4156   case ICmpInst::ICMP_NE:
4157     // Recognize pattern:
4158     //   mulval = mul(zext A, zext B)
4159     //   cmp eq/neq mulval, zext trunc mulval
4160     if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
4161       if (Zext->hasOneUse()) {
4162         Value *ZextArg = Zext->getOperand(0);
4163         if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
4164           if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
4165             break; //Recognized
4166       }
4167 
4168     // Recognize pattern:
4169     //   mulval = mul(zext A, zext B)
4170     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
4171     ConstantInt *CI;
4172     Value *ValToMask;
4173     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
4174       if (ValToMask != MulVal)
4175         return nullptr;
4176       const APInt &CVal = CI->getValue() + 1;
4177       if (CVal.isPowerOf2()) {
4178         unsigned MaskWidth = CVal.logBase2();
4179         if (MaskWidth == MulWidth)
4180           break; // Recognized
4181       }
4182     }
4183     return nullptr;
4184 
4185   case ICmpInst::ICMP_UGT:
4186     // Recognize pattern:
4187     //   mulval = mul(zext A, zext B)
4188     //   cmp ugt mulval, max
4189     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4190       APInt MaxVal = APInt::getMaxValue(MulWidth);
4191       MaxVal = MaxVal.zext(CI->getBitWidth());
4192       if (MaxVal.eq(CI->getValue()))
4193         break; // Recognized
4194     }
4195     return nullptr;
4196 
4197   case ICmpInst::ICMP_UGE:
4198     // Recognize pattern:
4199     //   mulval = mul(zext A, zext B)
4200     //   cmp uge mulval, max+1
4201     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4202       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4203       if (MaxVal.eq(CI->getValue()))
4204         break; // Recognized
4205     }
4206     return nullptr;
4207 
4208   case ICmpInst::ICMP_ULE:
4209     // Recognize pattern:
4210     //   mulval = mul(zext A, zext B)
4211     //   cmp ule mulval, max
4212     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4213       APInt MaxVal = APInt::getMaxValue(MulWidth);
4214       MaxVal = MaxVal.zext(CI->getBitWidth());
4215       if (MaxVal.eq(CI->getValue()))
4216         break; // Recognized
4217     }
4218     return nullptr;
4219 
4220   case ICmpInst::ICMP_ULT:
4221     // Recognize pattern:
4222     //   mulval = mul(zext A, zext B)
4223     //   cmp ule mulval, max + 1
4224     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
4225       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
4226       if (MaxVal.eq(CI->getValue()))
4227         break; // Recognized
4228     }
4229     return nullptr;
4230 
4231   default:
4232     return nullptr;
4233   }
4234 
4235   InstCombiner::BuilderTy &Builder = IC.Builder;
4236   Builder.SetInsertPoint(MulInstr);
4237 
4238   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
4239   Value *MulA = A, *MulB = B;
4240   if (WidthA < MulWidth)
4241     MulA = Builder.CreateZExt(A, MulType);
4242   if (WidthB < MulWidth)
4243     MulB = Builder.CreateZExt(B, MulType);
4244   Function *F = Intrinsic::getDeclaration(
4245       I.getModule(), Intrinsic::umul_with_overflow, MulType);
4246   CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
4247   IC.Worklist.Add(MulInstr);
4248 
4249   // If there are uses of mul result other than the comparison, we know that
4250   // they are truncation or binary AND. Change them to use result of
4251   // mul.with.overflow and adjust properly mask/size.
4252   if (MulVal->hasNUsesOrMore(2)) {
4253     Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
4254     for (auto UI = MulVal->user_begin(), UE = MulVal->user_end(); UI != UE;) {
4255       User *U = *UI++;
4256       if (U == &I || U == OtherVal)
4257         continue;
4258       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
4259         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4260           IC.replaceInstUsesWith(*TI, Mul);
4261         else
4262           TI->setOperand(0, Mul);
4263       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
4264         assert(BO->getOpcode() == Instruction::And);
4265         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
4266         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
4267         APInt ShortMask = CI->getValue().trunc(MulWidth);
4268         Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
4269         Instruction *Zext =
4270             cast<Instruction>(Builder.CreateZExt(ShortAnd, BO->getType()));
4271         IC.Worklist.Add(Zext);
4272         IC.replaceInstUsesWith(*BO, Zext);
4273       } else {
4274         llvm_unreachable("Unexpected Binary operation");
4275       }
4276       IC.Worklist.Add(cast<Instruction>(U));
4277     }
4278   }
4279   if (isa<Instruction>(OtherVal))
4280     IC.Worklist.Add(cast<Instruction>(OtherVal));
4281 
4282   // The original icmp gets replaced with the overflow value, maybe inverted
4283   // depending on predicate.
4284   bool Inverse = false;
4285   switch (I.getPredicate()) {
4286   case ICmpInst::ICMP_NE:
4287     break;
4288   case ICmpInst::ICMP_EQ:
4289     Inverse = true;
4290     break;
4291   case ICmpInst::ICMP_UGT:
4292   case ICmpInst::ICMP_UGE:
4293     if (I.getOperand(0) == MulVal)
4294       break;
4295     Inverse = true;
4296     break;
4297   case ICmpInst::ICMP_ULT:
4298   case ICmpInst::ICMP_ULE:
4299     if (I.getOperand(1) == MulVal)
4300       break;
4301     Inverse = true;
4302     break;
4303   default:
4304     llvm_unreachable("Unexpected predicate");
4305   }
4306   if (Inverse) {
4307     Value *Res = Builder.CreateExtractValue(Call, 1);
4308     return BinaryOperator::CreateNot(Res);
4309   }
4310 
4311   return ExtractValueInst::Create(Call, 1);
4312 }
4313 
4314 /// When performing a comparison against a constant, it is possible that not all
4315 /// the bits in the LHS are demanded. This helper method computes the mask that
4316 /// IS demanded.
4317 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
4318   const APInt *RHS;
4319   if (!match(I.getOperand(1), m_APInt(RHS)))
4320     return APInt::getAllOnesValue(BitWidth);
4321 
4322   // If this is a normal comparison, it demands all bits. If it is a sign bit
4323   // comparison, it only demands the sign bit.
4324   bool UnusedBit;
4325   if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
4326     return APInt::getSignMask(BitWidth);
4327 
4328   switch (I.getPredicate()) {
4329   // For a UGT comparison, we don't care about any bits that
4330   // correspond to the trailing ones of the comparand.  The value of these
4331   // bits doesn't impact the outcome of the comparison, because any value
4332   // greater than the RHS must differ in a bit higher than these due to carry.
4333   case ICmpInst::ICMP_UGT:
4334     return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes());
4335 
4336   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
4337   // Any value less than the RHS must differ in a higher bit because of carries.
4338   case ICmpInst::ICMP_ULT:
4339     return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros());
4340 
4341   default:
4342     return APInt::getAllOnesValue(BitWidth);
4343   }
4344 }
4345 
4346 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst
4347 /// should be swapped.
4348 /// The decision is based on how many times these two operands are reused
4349 /// as subtract operands and their positions in those instructions.
4350 /// The rationale is that several architectures use the same instruction for
4351 /// both subtract and cmp. Thus, it is better if the order of those operands
4352 /// match.
4353 /// \return true if Op0 and Op1 should be swapped.
4354 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) {
4355   // Filter out pointer values as those cannot appear directly in subtract.
4356   // FIXME: we may want to go through inttoptrs or bitcasts.
4357   if (Op0->getType()->isPointerTy())
4358     return false;
4359   // If a subtract already has the same operands as a compare, swapping would be
4360   // bad. If a subtract has the same operands as a compare but in reverse order,
4361   // then swapping is good.
4362   int GoodToSwap = 0;
4363   for (const User *U : Op0->users()) {
4364     if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
4365       GoodToSwap++;
4366     else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
4367       GoodToSwap--;
4368   }
4369   return GoodToSwap > 0;
4370 }
4371 
4372 /// Check that one use is in the same block as the definition and all
4373 /// other uses are in blocks dominated by a given block.
4374 ///
4375 /// \param DI Definition
4376 /// \param UI Use
4377 /// \param DB Block that must dominate all uses of \p DI outside
4378 ///           the parent block
4379 /// \return true when \p UI is the only use of \p DI in the parent block
4380 /// and all other uses of \p DI are in blocks dominated by \p DB.
4381 ///
4382 bool InstCombiner::dominatesAllUses(const Instruction *DI,
4383                                     const Instruction *UI,
4384                                     const BasicBlock *DB) const {
4385   assert(DI && UI && "Instruction not defined\n");
4386   // Ignore incomplete definitions.
4387   if (!DI->getParent())
4388     return false;
4389   // DI and UI must be in the same block.
4390   if (DI->getParent() != UI->getParent())
4391     return false;
4392   // Protect from self-referencing blocks.
4393   if (DI->getParent() == DB)
4394     return false;
4395   for (const User *U : DI->users()) {
4396     auto *Usr = cast<Instruction>(U);
4397     if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
4398       return false;
4399   }
4400   return true;
4401 }
4402 
4403 /// Return true when the instruction sequence within a block is select-cmp-br.
4404 static bool isChainSelectCmpBranch(const SelectInst *SI) {
4405   const BasicBlock *BB = SI->getParent();
4406   if (!BB)
4407     return false;
4408   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
4409   if (!BI || BI->getNumSuccessors() != 2)
4410     return false;
4411   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
4412   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
4413     return false;
4414   return true;
4415 }
4416 
4417 /// True when a select result is replaced by one of its operands
4418 /// in select-icmp sequence. This will eventually result in the elimination
4419 /// of the select.
4420 ///
4421 /// \param SI    Select instruction
4422 /// \param Icmp  Compare instruction
4423 /// \param SIOpd Operand that replaces the select
4424 ///
4425 /// Notes:
4426 /// - The replacement is global and requires dominator information
4427 /// - The caller is responsible for the actual replacement
4428 ///
4429 /// Example:
4430 ///
4431 /// entry:
4432 ///  %4 = select i1 %3, %C* %0, %C* null
4433 ///  %5 = icmp eq %C* %4, null
4434 ///  br i1 %5, label %9, label %7
4435 ///  ...
4436 ///  ; <label>:7                                       ; preds = %entry
4437 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
4438 ///  ...
4439 ///
4440 /// can be transformed to
4441 ///
4442 ///  %5 = icmp eq %C* %0, null
4443 ///  %6 = select i1 %3, i1 %5, i1 true
4444 ///  br i1 %6, label %9, label %7
4445 ///  ...
4446 ///  ; <label>:7                                       ; preds = %entry
4447 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
4448 ///
4449 /// Similar when the first operand of the select is a constant or/and
4450 /// the compare is for not equal rather than equal.
4451 ///
4452 /// NOTE: The function is only called when the select and compare constants
4453 /// are equal, the optimization can work only for EQ predicates. This is not a
4454 /// major restriction since a NE compare should be 'normalized' to an equal
4455 /// compare, which usually happens in the combiner and test case
4456 /// select-cmp-br.ll checks for it.
4457 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
4458                                              const ICmpInst *Icmp,
4459                                              const unsigned SIOpd) {
4460   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
4461   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
4462     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
4463     // The check for the single predecessor is not the best that can be
4464     // done. But it protects efficiently against cases like when SI's
4465     // home block has two successors, Succ and Succ1, and Succ1 predecessor
4466     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
4467     // replaced can be reached on either path. So the uniqueness check
4468     // guarantees that the path all uses of SI (outside SI's parent) are on
4469     // is disjoint from all other paths out of SI. But that information
4470     // is more expensive to compute, and the trade-off here is in favor
4471     // of compile-time. It should also be noticed that we check for a single
4472     // predecessor and not only uniqueness. This to handle the situation when
4473     // Succ and Succ1 points to the same basic block.
4474     if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
4475       NumSel++;
4476       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
4477       return true;
4478     }
4479   }
4480   return false;
4481 }
4482 
4483 /// Try to fold the comparison based on range information we can get by checking
4484 /// whether bits are known to be zero or one in the inputs.
4485 Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
4486   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4487   Type *Ty = Op0->getType();
4488   ICmpInst::Predicate Pred = I.getPredicate();
4489 
4490   // Get scalar or pointer size.
4491   unsigned BitWidth = Ty->isIntOrIntVectorTy()
4492                           ? Ty->getScalarSizeInBits()
4493                           : DL.getIndexTypeSizeInBits(Ty->getScalarType());
4494 
4495   if (!BitWidth)
4496     return nullptr;
4497 
4498   KnownBits Op0Known(BitWidth);
4499   KnownBits Op1Known(BitWidth);
4500 
4501   if (SimplifyDemandedBits(&I, 0,
4502                            getDemandedBitsLHSMask(I, BitWidth),
4503                            Op0Known, 0))
4504     return &I;
4505 
4506   if (SimplifyDemandedBits(&I, 1, APInt::getAllOnesValue(BitWidth),
4507                            Op1Known, 0))
4508     return &I;
4509 
4510   // Given the known and unknown bits, compute a range that the LHS could be
4511   // in.  Compute the Min, Max and RHS values based on the known bits. For the
4512   // EQ and NE we use unsigned values.
4513   APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4514   APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4515   if (I.isSigned()) {
4516     computeSignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4517     computeSignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4518   } else {
4519     computeUnsignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max);
4520     computeUnsignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max);
4521   }
4522 
4523   // If Min and Max are known to be the same, then SimplifyDemandedBits figured
4524   // out that the LHS or RHS is a constant. Constant fold this now, so that
4525   // code below can assume that Min != Max.
4526   if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4527     return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
4528   if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4529     return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
4530 
4531   // Based on the range information we know about the LHS, see if we can
4532   // simplify this comparison.  For example, (x&4) < 8 is always true.
4533   switch (Pred) {
4534   default:
4535     llvm_unreachable("Unknown icmp opcode!");
4536   case ICmpInst::ICMP_EQ:
4537   case ICmpInst::ICMP_NE: {
4538     if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4539       return Pred == CmpInst::ICMP_EQ
4540                  ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
4541                  : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4542     }
4543 
4544     // If all bits are known zero except for one, then we know at most one bit
4545     // is set. If the comparison is against zero, then this is a check to see if
4546     // *that* bit is set.
4547     APInt Op0KnownZeroInverted = ~Op0Known.Zero;
4548     if (Op1Known.isZero()) {
4549       // If the LHS is an AND with the same constant, look through it.
4550       Value *LHS = nullptr;
4551       const APInt *LHSC;
4552       if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
4553           *LHSC != Op0KnownZeroInverted)
4554         LHS = Op0;
4555 
4556       Value *X;
4557       if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
4558         APInt ValToCheck = Op0KnownZeroInverted;
4559         Type *XTy = X->getType();
4560         if (ValToCheck.isPowerOf2()) {
4561           // ((1 << X) & 8) == 0 -> X != 3
4562           // ((1 << X) & 8) != 0 -> X == 3
4563           auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4564           auto NewPred = ICmpInst::getInversePredicate(Pred);
4565           return new ICmpInst(NewPred, X, CmpC);
4566         } else if ((++ValToCheck).isPowerOf2()) {
4567           // ((1 << X) & 7) == 0 -> X >= 3
4568           // ((1 << X) & 7) != 0 -> X  < 3
4569           auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
4570           auto NewPred =
4571               Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
4572           return new ICmpInst(NewPred, X, CmpC);
4573         }
4574       }
4575 
4576       // Check if the LHS is 8 >>u x and the result is a power of 2 like 1.
4577       const APInt *CI;
4578       if (Op0KnownZeroInverted.isOneValue() &&
4579           match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
4580         // ((8 >>u X) & 1) == 0 -> X != 3
4581         // ((8 >>u X) & 1) != 0 -> X == 3
4582         unsigned CmpVal = CI->countTrailingZeros();
4583         auto NewPred = ICmpInst::getInversePredicate(Pred);
4584         return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
4585       }
4586     }
4587     break;
4588   }
4589   case ICmpInst::ICMP_ULT: {
4590     if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
4591       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4592     if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
4593       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4594     if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
4595       return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4596 
4597     const APInt *CmpC;
4598     if (match(Op1, m_APInt(CmpC))) {
4599       // A <u C -> A == C-1 if min(A)+1 == C
4600       if (*CmpC == Op0Min + 1)
4601         return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4602                             ConstantInt::get(Op1->getType(), *CmpC - 1));
4603       // X <u C --> X == 0, if the number of zero bits in the bottom of X
4604       // exceeds the log2 of C.
4605       if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
4606         return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4607                             Constant::getNullValue(Op1->getType()));
4608     }
4609     break;
4610   }
4611   case ICmpInst::ICMP_UGT: {
4612     if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
4613       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4614     if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
4615       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4616     if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
4617       return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4618 
4619     const APInt *CmpC;
4620     if (match(Op1, m_APInt(CmpC))) {
4621       // A >u C -> A == C+1 if max(a)-1 == C
4622       if (*CmpC == Op0Max - 1)
4623         return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4624                             ConstantInt::get(Op1->getType(), *CmpC + 1));
4625       // X >u C --> X != 0, if the number of zero bits in the bottom of X
4626       // exceeds the log2 of C.
4627       if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
4628         return new ICmpInst(ICmpInst::ICMP_NE, Op0,
4629                             Constant::getNullValue(Op1->getType()));
4630     }
4631     break;
4632   }
4633   case ICmpInst::ICMP_SLT: {
4634     if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
4635       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4636     if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
4637       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4638     if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
4639       return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4640     const APInt *CmpC;
4641     if (match(Op1, m_APInt(CmpC))) {
4642       if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
4643         return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4644                             ConstantInt::get(Op1->getType(), *CmpC - 1));
4645     }
4646     break;
4647   }
4648   case ICmpInst::ICMP_SGT: {
4649     if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
4650       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4651     if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
4652       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4653     if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
4654       return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4655     const APInt *CmpC;
4656     if (match(Op1, m_APInt(CmpC))) {
4657       if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
4658         return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4659                             ConstantInt::get(Op1->getType(), *CmpC + 1));
4660     }
4661     break;
4662   }
4663   case ICmpInst::ICMP_SGE:
4664     assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
4665     if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
4666       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4667     if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
4668       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4669     if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
4670       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4671     break;
4672   case ICmpInst::ICMP_SLE:
4673     assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
4674     if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
4675       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4676     if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
4677       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4678     if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
4679       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4680     break;
4681   case ICmpInst::ICMP_UGE:
4682     assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
4683     if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
4684       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4685     if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
4686       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4687     if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
4688       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4689     break;
4690   case ICmpInst::ICMP_ULE:
4691     assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
4692     if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
4693       return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4694     if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
4695       return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4696     if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
4697       return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4698     break;
4699   }
4700 
4701   // Turn a signed comparison into an unsigned one if both operands are known to
4702   // have the same sign.
4703   if (I.isSigned() &&
4704       ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
4705        (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
4706     return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
4707 
4708   return nullptr;
4709 }
4710 
4711 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
4712 /// it into the appropriate icmp lt or icmp gt instruction. This transform
4713 /// allows them to be folded in visitICmpInst.
4714 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
4715   ICmpInst::Predicate Pred = I.getPredicate();
4716   if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
4717       Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
4718     return nullptr;
4719 
4720   Value *Op0 = I.getOperand(0);
4721   Value *Op1 = I.getOperand(1);
4722   auto *Op1C = dyn_cast<Constant>(Op1);
4723   if (!Op1C)
4724     return nullptr;
4725 
4726   // Check if the constant operand can be safely incremented/decremented without
4727   // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
4728   // the edge cases for us, so we just assert on them. For vectors, we must
4729   // handle the edge cases.
4730   Type *Op1Type = Op1->getType();
4731   bool IsSigned = I.isSigned();
4732   bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
4733   auto *CI = dyn_cast<ConstantInt>(Op1C);
4734   if (CI) {
4735     // A <= MAX -> TRUE ; A >= MIN -> TRUE
4736     assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
4737   } else if (Op1Type->isVectorTy()) {
4738     // TODO? If the edge cases for vectors were guaranteed to be handled as they
4739     // are for scalar, we could remove the min/max checks. However, to do that,
4740     // we would have to use insertelement/shufflevector to replace edge values.
4741     unsigned NumElts = Op1Type->getVectorNumElements();
4742     for (unsigned i = 0; i != NumElts; ++i) {
4743       Constant *Elt = Op1C->getAggregateElement(i);
4744       if (!Elt)
4745         return nullptr;
4746 
4747       if (isa<UndefValue>(Elt))
4748         continue;
4749 
4750       // Bail out if we can't determine if this constant is min/max or if we
4751       // know that this constant is min/max.
4752       auto *CI = dyn_cast<ConstantInt>(Elt);
4753       if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
4754         return nullptr;
4755     }
4756   } else {
4757     // ConstantExpr?
4758     return nullptr;
4759   }
4760 
4761   // Increment or decrement the constant and set the new comparison predicate:
4762   // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
4763   Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
4764   CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
4765   NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
4766   return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
4767 }
4768 
4769 /// Integer compare with boolean values can always be turned into bitwise ops.
4770 static Instruction *canonicalizeICmpBool(ICmpInst &I,
4771                                          InstCombiner::BuilderTy &Builder) {
4772   Value *A = I.getOperand(0), *B = I.getOperand(1);
4773   assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
4774 
4775   // A boolean compared to true/false can be simplified to Op0/true/false in
4776   // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
4777   // Cases not handled by InstSimplify are always 'not' of Op0.
4778   if (match(B, m_Zero())) {
4779     switch (I.getPredicate()) {
4780       case CmpInst::ICMP_EQ:  // A ==   0 -> !A
4781       case CmpInst::ICMP_ULE: // A <=u  0 -> !A
4782       case CmpInst::ICMP_SGE: // A >=s  0 -> !A
4783         return BinaryOperator::CreateNot(A);
4784       default:
4785         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
4786     }
4787   } else if (match(B, m_One())) {
4788     switch (I.getPredicate()) {
4789       case CmpInst::ICMP_NE:  // A !=  1 -> !A
4790       case CmpInst::ICMP_ULT: // A <u  1 -> !A
4791       case CmpInst::ICMP_SGT: // A >s -1 -> !A
4792         return BinaryOperator::CreateNot(A);
4793       default:
4794         llvm_unreachable("ICmp i1 X, C not simplified as expected.");
4795     }
4796   }
4797 
4798   switch (I.getPredicate()) {
4799   default:
4800     llvm_unreachable("Invalid icmp instruction!");
4801   case ICmpInst::ICMP_EQ:
4802     // icmp eq i1 A, B -> ~(A ^ B)
4803     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
4804 
4805   case ICmpInst::ICMP_NE:
4806     // icmp ne i1 A, B -> A ^ B
4807     return BinaryOperator::CreateXor(A, B);
4808 
4809   case ICmpInst::ICMP_UGT:
4810     // icmp ugt -> icmp ult
4811     std::swap(A, B);
4812     LLVM_FALLTHROUGH;
4813   case ICmpInst::ICMP_ULT:
4814     // icmp ult i1 A, B -> ~A & B
4815     return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
4816 
4817   case ICmpInst::ICMP_SGT:
4818     // icmp sgt -> icmp slt
4819     std::swap(A, B);
4820     LLVM_FALLTHROUGH;
4821   case ICmpInst::ICMP_SLT:
4822     // icmp slt i1 A, B -> A & ~B
4823     return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
4824 
4825   case ICmpInst::ICMP_UGE:
4826     // icmp uge -> icmp ule
4827     std::swap(A, B);
4828     LLVM_FALLTHROUGH;
4829   case ICmpInst::ICMP_ULE:
4830     // icmp ule i1 A, B -> ~A | B
4831     return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
4832 
4833   case ICmpInst::ICMP_SGE:
4834     // icmp sge -> icmp sle
4835     std::swap(A, B);
4836     LLVM_FALLTHROUGH;
4837   case ICmpInst::ICMP_SLE:
4838     // icmp sle i1 A, B -> A | ~B
4839     return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
4840   }
4841 }
4842 
4843 // Transform pattern like:
4844 //   (1 << Y) u<= X  or  ~(-1 << Y) u<  X  or  ((1 << Y)+(-1)) u<  X
4845 //   (1 << Y) u>  X  or  ~(-1 << Y) u>= X  or  ((1 << Y)+(-1)) u>= X
4846 // Into:
4847 //   (X l>> Y) != 0
4848 //   (X l>> Y) == 0
4849 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
4850                                             InstCombiner::BuilderTy &Builder) {
4851   ICmpInst::Predicate Pred, NewPred;
4852   Value *X, *Y;
4853   if (match(&Cmp,
4854             m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
4855     // We want X to be the icmp's second operand, so swap predicate if it isn't.
4856     if (Cmp.getOperand(0) == X)
4857       Pred = Cmp.getSwappedPredicate();
4858 
4859     switch (Pred) {
4860     case ICmpInst::ICMP_ULE:
4861       NewPred = ICmpInst::ICMP_NE;
4862       break;
4863     case ICmpInst::ICMP_UGT:
4864       NewPred = ICmpInst::ICMP_EQ;
4865       break;
4866     default:
4867       return nullptr;
4868     }
4869   } else if (match(&Cmp, m_c_ICmp(Pred,
4870                                   m_OneUse(m_CombineOr(
4871                                       m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
4872                                       m_Add(m_Shl(m_One(), m_Value(Y)),
4873                                             m_AllOnes()))),
4874                                   m_Value(X)))) {
4875     // The variant with 'add' is not canonical, (the variant with 'not' is)
4876     // we only get it because it has extra uses, and can't be canonicalized,
4877 
4878     // We want X to be the icmp's second operand, so swap predicate if it isn't.
4879     if (Cmp.getOperand(0) == X)
4880       Pred = Cmp.getSwappedPredicate();
4881 
4882     switch (Pred) {
4883     case ICmpInst::ICMP_ULT:
4884       NewPred = ICmpInst::ICMP_NE;
4885       break;
4886     case ICmpInst::ICMP_UGE:
4887       NewPred = ICmpInst::ICMP_EQ;
4888       break;
4889     default:
4890       return nullptr;
4891     }
4892   } else
4893     return nullptr;
4894 
4895   Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
4896   Constant *Zero = Constant::getNullValue(NewX->getType());
4897   return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
4898 }
4899 
4900 static Instruction *foldVectorCmp(CmpInst &Cmp,
4901                                   InstCombiner::BuilderTy &Builder) {
4902   // If both arguments of the cmp are shuffles that use the same mask and
4903   // shuffle within a single vector, move the shuffle after the cmp.
4904   Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
4905   Value *V1, *V2;
4906   Constant *M;
4907   if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(M))) &&
4908       match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(M))) &&
4909       V1->getType() == V2->getType() &&
4910       (LHS->hasOneUse() || RHS->hasOneUse())) {
4911     // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
4912     CmpInst::Predicate P = Cmp.getPredicate();
4913     Value *NewCmp = isa<ICmpInst>(Cmp) ? Builder.CreateICmp(P, V1, V2)
4914                                        : Builder.CreateFCmp(P, V1, V2);
4915     return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), M);
4916   }
4917   return nullptr;
4918 }
4919 
4920 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4921   bool Changed = false;
4922   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4923   unsigned Op0Cplxity = getComplexity(Op0);
4924   unsigned Op1Cplxity = getComplexity(Op1);
4925 
4926   /// Orders the operands of the compare so that they are listed from most
4927   /// complex to least complex.  This puts constants before unary operators,
4928   /// before binary operators.
4929   if (Op0Cplxity < Op1Cplxity ||
4930       (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
4931     I.swapOperands();
4932     std::swap(Op0, Op1);
4933     Changed = true;
4934   }
4935 
4936   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1,
4937                                   SQ.getWithInstruction(&I)))
4938     return replaceInstUsesWith(I, V);
4939 
4940   // Comparing -val or val with non-zero is the same as just comparing val
4941   // ie, abs(val) != 0 -> val != 0
4942   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
4943     Value *Cond, *SelectTrue, *SelectFalse;
4944     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
4945                             m_Value(SelectFalse)))) {
4946       if (Value *V = dyn_castNegVal(SelectTrue)) {
4947         if (V == SelectFalse)
4948           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
4949       }
4950       else if (Value *V = dyn_castNegVal(SelectFalse)) {
4951         if (V == SelectTrue)
4952           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
4953       }
4954     }
4955   }
4956 
4957   if (Op0->getType()->isIntOrIntVectorTy(1))
4958     if (Instruction *Res = canonicalizeICmpBool(I, Builder))
4959       return Res;
4960 
4961   if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
4962     return NewICmp;
4963 
4964   if (Instruction *Res = foldICmpWithConstant(I))
4965     return Res;
4966 
4967   if (Instruction *Res = foldICmpWithDominatingICmp(I))
4968     return Res;
4969 
4970   if (Instruction *Res = foldICmpUsingKnownBits(I))
4971     return Res;
4972 
4973   // Test if the ICmpInst instruction is used exclusively by a select as
4974   // part of a minimum or maximum operation. If so, refrain from doing
4975   // any other folding. This helps out other analyses which understand
4976   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4977   // and CodeGen. And in this case, at least one of the comparison
4978   // operands has at least one user besides the compare (the select),
4979   // which would often largely negate the benefit of folding anyway.
4980   //
4981   // Do the same for the other patterns recognized by matchSelectPattern.
4982   if (I.hasOneUse())
4983     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
4984       Value *A, *B;
4985       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
4986       if (SPR.Flavor != SPF_UNKNOWN)
4987         return nullptr;
4988     }
4989 
4990   // Do this after checking for min/max to prevent infinite looping.
4991   if (Instruction *Res = foldICmpWithZero(I))
4992     return Res;
4993 
4994   // FIXME: We only do this after checking for min/max to prevent infinite
4995   // looping caused by a reverse canonicalization of these patterns for min/max.
4996   // FIXME: The organization of folds is a mess. These would naturally go into
4997   // canonicalizeCmpWithConstant(), but we can't move all of the above folds
4998   // down here after the min/max restriction.
4999   ICmpInst::Predicate Pred = I.getPredicate();
5000   const APInt *C;
5001   if (match(Op1, m_APInt(C))) {
5002     // For i32: x >u 2147483647 -> x <s 0  -> true if sign bit set
5003     if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
5004       Constant *Zero = Constant::getNullValue(Op0->getType());
5005       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
5006     }
5007 
5008     // For i32: x <u 2147483648 -> x >s -1  -> true if sign bit clear
5009     if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
5010       Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
5011       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
5012     }
5013   }
5014 
5015   if (Instruction *Res = foldICmpInstWithConstant(I))
5016     return Res;
5017 
5018   if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
5019     return Res;
5020 
5021   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5022   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
5023     if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
5024       return NI;
5025   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
5026     if (Instruction *NI = foldGEPICmp(GEP, Op0,
5027                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5028       return NI;
5029 
5030   // Try to optimize equality comparisons against alloca-based pointers.
5031   if (Op0->getType()->isPointerTy() && I.isEquality()) {
5032     assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
5033     if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
5034       if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
5035         return New;
5036     if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
5037       if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
5038         return New;
5039   }
5040 
5041   if (Instruction *Res = foldICmpBitCast(I, Builder))
5042     return Res;
5043 
5044   if (isa<CastInst>(Op0)) {
5045     // Handle the special case of: icmp (cast bool to X), <cst>
5046     // This comes up when you have code like
5047     //   int X = A < B;
5048     //   if (X) ...
5049     // For generality, we handle any zero-extension of any operand comparison
5050     // with a constant or another cast from the same type.
5051     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
5052       if (Instruction *R = foldICmpWithCastAndCast(I))
5053         return R;
5054   }
5055 
5056   if (Instruction *Res = foldICmpBinOp(I))
5057     return Res;
5058 
5059   if (Instruction *Res = foldICmpWithMinMax(I))
5060     return Res;
5061 
5062   {
5063     Value *A, *B;
5064     // Transform (A & ~B) == 0 --> (A & B) != 0
5065     // and       (A & ~B) != 0 --> (A & B) == 0
5066     // if A is a power of 2.
5067     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
5068         match(Op1, m_Zero()) &&
5069         isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
5070       return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
5071                           Op1);
5072 
5073     // ~X < ~Y --> Y < X
5074     // ~X < C -->  X > ~C
5075     if (match(Op0, m_Not(m_Value(A)))) {
5076       if (match(Op1, m_Not(m_Value(B))))
5077         return new ICmpInst(I.getPredicate(), B, A);
5078 
5079       const APInt *C;
5080       if (match(Op1, m_APInt(C)))
5081         return new ICmpInst(I.getSwappedPredicate(), A,
5082                             ConstantInt::get(Op1->getType(), ~(*C)));
5083     }
5084 
5085     Instruction *AddI = nullptr;
5086     if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
5087                                      m_Instruction(AddI))) &&
5088         isa<IntegerType>(A->getType())) {
5089       Value *Result;
5090       Constant *Overflow;
5091       if (OptimizeOverflowCheck(Instruction::Add, /*Signed*/false, A, B,
5092                                 *AddI, Result, Overflow)) {
5093         replaceInstUsesWith(*AddI, Result);
5094         return replaceInstUsesWith(I, Overflow);
5095       }
5096     }
5097 
5098     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
5099     if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5100       if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
5101         return R;
5102     }
5103     if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
5104       if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
5105         return R;
5106     }
5107   }
5108 
5109   if (Instruction *Res = foldICmpEquality(I))
5110     return Res;
5111 
5112   // The 'cmpxchg' instruction returns an aggregate containing the old value and
5113   // an i1 which indicates whether or not we successfully did the swap.
5114   //
5115   // Replace comparisons between the old value and the expected value with the
5116   // indicator that 'cmpxchg' returns.
5117   //
5118   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
5119   // spuriously fail.  In those cases, the old value may equal the expected
5120   // value but it is possible for the swap to not occur.
5121   if (I.getPredicate() == ICmpInst::ICMP_EQ)
5122     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
5123       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
5124         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
5125             !ACXI->isWeak())
5126           return ExtractValueInst::Create(ACXI, 1);
5127 
5128   {
5129     Value *X;
5130     const APInt *C;
5131     // icmp X+Cst, X
5132     if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
5133       return foldICmpAddOpConst(X, *C, I.getPredicate());
5134 
5135     // icmp X, X+Cst
5136     if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
5137       return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
5138   }
5139 
5140   if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
5141     return Res;
5142 
5143   if (I.getType()->isVectorTy())
5144     if (Instruction *Res = foldVectorCmp(I, Builder))
5145       return Res;
5146 
5147   return Changed ? &I : nullptr;
5148 }
5149 
5150 /// Fold fcmp ([us]itofp x, cst) if possible.
5151 Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
5152                                                 Constant *RHSC) {
5153   if (!isa<ConstantFP>(RHSC)) return nullptr;
5154   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5155 
5156   // Get the width of the mantissa.  We don't want to hack on conversions that
5157   // might lose information from the integer, e.g. "i64 -> float"
5158   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5159   if (MantissaWidth == -1) return nullptr;  // Unknown.
5160 
5161   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5162 
5163   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5164 
5165   if (I.isEquality()) {
5166     FCmpInst::Predicate P = I.getPredicate();
5167     bool IsExact = false;
5168     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
5169     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
5170 
5171     // If the floating point constant isn't an integer value, we know if we will
5172     // ever compare equal / not equal to it.
5173     if (!IsExact) {
5174       // TODO: Can never be -0.0 and other non-representable values
5175       APFloat RHSRoundInt(RHS);
5176       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
5177       if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
5178         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
5179           return replaceInstUsesWith(I, Builder.getFalse());
5180 
5181         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
5182         return replaceInstUsesWith(I, Builder.getTrue());
5183       }
5184     }
5185 
5186     // TODO: If the constant is exactly representable, is it always OK to do
5187     // equality compares as integer?
5188   }
5189 
5190   // Check to see that the input is converted from an integer type that is small
5191   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5192   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5193   unsigned InputSize = IntTy->getScalarSizeInBits();
5194 
5195   // Following test does NOT adjust InputSize downwards for signed inputs,
5196   // because the most negative value still requires all the mantissa bits
5197   // to distinguish it from one less than that value.
5198   if ((int)InputSize > MantissaWidth) {
5199     // Conversion would lose accuracy. Check if loss can impact comparison.
5200     int Exp = ilogb(RHS);
5201     if (Exp == APFloat::IEK_Inf) {
5202       int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
5203       if (MaxExponent < (int)InputSize - !LHSUnsigned)
5204         // Conversion could create infinity.
5205         return nullptr;
5206     } else {
5207       // Note that if RHS is zero or NaN, then Exp is negative
5208       // and first condition is trivially false.
5209       if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
5210         // Conversion could affect comparison.
5211         return nullptr;
5212     }
5213   }
5214 
5215   // Otherwise, we can potentially simplify the comparison.  We know that it
5216   // will always come through as an integer value and we know the constant is
5217   // not a NAN (it would have been previously simplified).
5218   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5219 
5220   ICmpInst::Predicate Pred;
5221   switch (I.getPredicate()) {
5222   default: llvm_unreachable("Unexpected predicate!");
5223   case FCmpInst::FCMP_UEQ:
5224   case FCmpInst::FCMP_OEQ:
5225     Pred = ICmpInst::ICMP_EQ;
5226     break;
5227   case FCmpInst::FCMP_UGT:
5228   case FCmpInst::FCMP_OGT:
5229     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5230     break;
5231   case FCmpInst::FCMP_UGE:
5232   case FCmpInst::FCMP_OGE:
5233     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5234     break;
5235   case FCmpInst::FCMP_ULT:
5236   case FCmpInst::FCMP_OLT:
5237     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5238     break;
5239   case FCmpInst::FCMP_ULE:
5240   case FCmpInst::FCMP_OLE:
5241     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5242     break;
5243   case FCmpInst::FCMP_UNE:
5244   case FCmpInst::FCMP_ONE:
5245     Pred = ICmpInst::ICMP_NE;
5246     break;
5247   case FCmpInst::FCMP_ORD:
5248     return replaceInstUsesWith(I, Builder.getTrue());
5249   case FCmpInst::FCMP_UNO:
5250     return replaceInstUsesWith(I, Builder.getFalse());
5251   }
5252 
5253   // Now we know that the APFloat is a normal number, zero or inf.
5254 
5255   // See if the FP constant is too large for the integer.  For example,
5256   // comparing an i8 to 300.0.
5257   unsigned IntWidth = IntTy->getScalarSizeInBits();
5258 
5259   if (!LHSUnsigned) {
5260     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5261     // and large values.
5262     APFloat SMax(RHS.getSemantics());
5263     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5264                           APFloat::rmNearestTiesToEven);
5265     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5266       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5267           Pred == ICmpInst::ICMP_SLE)
5268         return replaceInstUsesWith(I, Builder.getTrue());
5269       return replaceInstUsesWith(I, Builder.getFalse());
5270     }
5271   } else {
5272     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5273     // +INF and large values.
5274     APFloat UMax(RHS.getSemantics());
5275     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5276                           APFloat::rmNearestTiesToEven);
5277     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5278       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5279           Pred == ICmpInst::ICMP_ULE)
5280         return replaceInstUsesWith(I, Builder.getTrue());
5281       return replaceInstUsesWith(I, Builder.getFalse());
5282     }
5283   }
5284 
5285   if (!LHSUnsigned) {
5286     // See if the RHS value is < SignedMin.
5287     APFloat SMin(RHS.getSemantics());
5288     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5289                           APFloat::rmNearestTiesToEven);
5290     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5291       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5292           Pred == ICmpInst::ICMP_SGE)
5293         return replaceInstUsesWith(I, Builder.getTrue());
5294       return replaceInstUsesWith(I, Builder.getFalse());
5295     }
5296   } else {
5297     // See if the RHS value is < UnsignedMin.
5298     APFloat SMin(RHS.getSemantics());
5299     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
5300                           APFloat::rmNearestTiesToEven);
5301     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
5302       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
5303           Pred == ICmpInst::ICMP_UGE)
5304         return replaceInstUsesWith(I, Builder.getTrue());
5305       return replaceInstUsesWith(I, Builder.getFalse());
5306     }
5307   }
5308 
5309   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5310   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5311   // casting the FP value to the integer value and back, checking for equality.
5312   // Don't do this for zero, because -0.0 is not fractional.
5313   Constant *RHSInt = LHSUnsigned
5314     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5315     : ConstantExpr::getFPToSI(RHSC, IntTy);
5316   if (!RHS.isZero()) {
5317     bool Equal = LHSUnsigned
5318       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5319       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5320     if (!Equal) {
5321       // If we had a comparison against a fractional value, we have to adjust
5322       // the compare predicate and sometimes the value.  RHSC is rounded towards
5323       // zero at this point.
5324       switch (Pred) {
5325       default: llvm_unreachable("Unexpected integer comparison!");
5326       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5327         return replaceInstUsesWith(I, Builder.getTrue());
5328       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5329         return replaceInstUsesWith(I, Builder.getFalse());
5330       case ICmpInst::ICMP_ULE:
5331         // (float)int <= 4.4   --> int <= 4
5332         // (float)int <= -4.4  --> false
5333         if (RHS.isNegative())
5334           return replaceInstUsesWith(I, Builder.getFalse());
5335         break;
5336       case ICmpInst::ICMP_SLE:
5337         // (float)int <= 4.4   --> int <= 4
5338         // (float)int <= -4.4  --> int < -4
5339         if (RHS.isNegative())
5340           Pred = ICmpInst::ICMP_SLT;
5341         break;
5342       case ICmpInst::ICMP_ULT:
5343         // (float)int < -4.4   --> false
5344         // (float)int < 4.4    --> int <= 4
5345         if (RHS.isNegative())
5346           return replaceInstUsesWith(I, Builder.getFalse());
5347         Pred = ICmpInst::ICMP_ULE;
5348         break;
5349       case ICmpInst::ICMP_SLT:
5350         // (float)int < -4.4   --> int < -4
5351         // (float)int < 4.4    --> int <= 4
5352         if (!RHS.isNegative())
5353           Pred = ICmpInst::ICMP_SLE;
5354         break;
5355       case ICmpInst::ICMP_UGT:
5356         // (float)int > 4.4    --> int > 4
5357         // (float)int > -4.4   --> true
5358         if (RHS.isNegative())
5359           return replaceInstUsesWith(I, Builder.getTrue());
5360         break;
5361       case ICmpInst::ICMP_SGT:
5362         // (float)int > 4.4    --> int > 4
5363         // (float)int > -4.4   --> int >= -4
5364         if (RHS.isNegative())
5365           Pred = ICmpInst::ICMP_SGE;
5366         break;
5367       case ICmpInst::ICMP_UGE:
5368         // (float)int >= -4.4   --> true
5369         // (float)int >= 4.4    --> int > 4
5370         if (RHS.isNegative())
5371           return replaceInstUsesWith(I, Builder.getTrue());
5372         Pred = ICmpInst::ICMP_UGT;
5373         break;
5374       case ICmpInst::ICMP_SGE:
5375         // (float)int >= -4.4   --> int >= -4
5376         // (float)int >= 4.4    --> int > 4
5377         if (!RHS.isNegative())
5378           Pred = ICmpInst::ICMP_SGT;
5379         break;
5380       }
5381     }
5382   }
5383 
5384   // Lower this FP comparison into an appropriate integer version of the
5385   // comparison.
5386   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5387 }
5388 
5389 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
5390 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
5391                                               Constant *RHSC) {
5392   // When C is not 0.0 and infinities are not allowed:
5393   // (C / X) < 0.0 is a sign-bit test of X
5394   // (C / X) < 0.0 --> X < 0.0 (if C is positive)
5395   // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
5396   //
5397   // Proof:
5398   // Multiply (C / X) < 0.0 by X * X / C.
5399   // - X is non zero, if it is the flag 'ninf' is violated.
5400   // - C defines the sign of X * X * C. Thus it also defines whether to swap
5401   //   the predicate. C is also non zero by definition.
5402   //
5403   // Thus X * X / C is non zero and the transformation is valid. [qed]
5404 
5405   FCmpInst::Predicate Pred = I.getPredicate();
5406 
5407   // Check that predicates are valid.
5408   if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
5409       (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
5410     return nullptr;
5411 
5412   // Check that RHS operand is zero.
5413   if (!match(RHSC, m_AnyZeroFP()))
5414     return nullptr;
5415 
5416   // Check fastmath flags ('ninf').
5417   if (!LHSI->hasNoInfs() || !I.hasNoInfs())
5418     return nullptr;
5419 
5420   // Check the properties of the dividend. It must not be zero to avoid a
5421   // division by zero (see Proof).
5422   const APFloat *C;
5423   if (!match(LHSI->getOperand(0), m_APFloat(C)))
5424     return nullptr;
5425 
5426   if (C->isZero())
5427     return nullptr;
5428 
5429   // Get swapped predicate if necessary.
5430   if (C->isNegative())
5431     Pred = I.getSwappedPredicate();
5432 
5433   return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
5434 }
5435 
5436 /// Optimize fabs(X) compared with zero.
5437 static Instruction *foldFabsWithFcmpZero(FCmpInst &I) {
5438   Value *X;
5439   if (!match(I.getOperand(0), m_Intrinsic<Intrinsic::fabs>(m_Value(X))) ||
5440       !match(I.getOperand(1), m_PosZeroFP()))
5441     return nullptr;
5442 
5443   auto replacePredAndOp0 = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
5444     I->setPredicate(P);
5445     I->setOperand(0, X);
5446     return I;
5447   };
5448 
5449   switch (I.getPredicate()) {
5450   case FCmpInst::FCMP_UGE:
5451   case FCmpInst::FCMP_OLT:
5452     // fabs(X) >= 0.0 --> true
5453     // fabs(X) <  0.0 --> false
5454     llvm_unreachable("fcmp should have simplified");
5455 
5456   case FCmpInst::FCMP_OGT:
5457     // fabs(X) > 0.0 --> X != 0.0
5458     return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
5459 
5460   case FCmpInst::FCMP_UGT:
5461     // fabs(X) u> 0.0 --> X u!= 0.0
5462     return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
5463 
5464   case FCmpInst::FCMP_OLE:
5465     // fabs(X) <= 0.0 --> X == 0.0
5466     return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
5467 
5468   case FCmpInst::FCMP_ULE:
5469     // fabs(X) u<= 0.0 --> X u== 0.0
5470     return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
5471 
5472   case FCmpInst::FCMP_OGE:
5473     // fabs(X) >= 0.0 --> !isnan(X)
5474     assert(!I.hasNoNaNs() && "fcmp should have simplified");
5475     return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
5476 
5477   case FCmpInst::FCMP_ULT:
5478     // fabs(X) u< 0.0 --> isnan(X)
5479     assert(!I.hasNoNaNs() && "fcmp should have simplified");
5480     return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
5481 
5482   case FCmpInst::FCMP_OEQ:
5483   case FCmpInst::FCMP_UEQ:
5484   case FCmpInst::FCMP_ONE:
5485   case FCmpInst::FCMP_UNE:
5486   case FCmpInst::FCMP_ORD:
5487   case FCmpInst::FCMP_UNO:
5488     // Look through the fabs() because it doesn't change anything but the sign.
5489     // fabs(X) == 0.0 --> X == 0.0,
5490     // fabs(X) != 0.0 --> X != 0.0
5491     // isnan(fabs(X)) --> isnan(X)
5492     // !isnan(fabs(X) --> !isnan(X)
5493     return replacePredAndOp0(&I, I.getPredicate(), X);
5494 
5495   default:
5496     return nullptr;
5497   }
5498 }
5499 
5500 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5501   bool Changed = false;
5502 
5503   /// Orders the operands of the compare so that they are listed from most
5504   /// complex to least complex.  This puts constants before unary operators,
5505   /// before binary operators.
5506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5507     I.swapOperands();
5508     Changed = true;
5509   }
5510 
5511   const CmpInst::Predicate Pred = I.getPredicate();
5512   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5513   if (Value *V = SimplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
5514                                   SQ.getWithInstruction(&I)))
5515     return replaceInstUsesWith(I, V);
5516 
5517   // Simplify 'fcmp pred X, X'
5518   Type *OpType = Op0->getType();
5519   assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
5520   if (Op0 == Op1) {
5521     switch (Pred) {
5522       default: break;
5523     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5524     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5525     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5526     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5527       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5528       I.setPredicate(FCmpInst::FCMP_UNO);
5529       I.setOperand(1, Constant::getNullValue(OpType));
5530       return &I;
5531 
5532     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5533     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5534     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5535     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5536       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5537       I.setPredicate(FCmpInst::FCMP_ORD);
5538       I.setOperand(1, Constant::getNullValue(OpType));
5539       return &I;
5540     }
5541   }
5542 
5543   // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
5544   // then canonicalize the operand to 0.0.
5545   if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
5546     if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI)) {
5547       I.setOperand(0, ConstantFP::getNullValue(OpType));
5548       return &I;
5549     }
5550     if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI)) {
5551       I.setOperand(1, ConstantFP::getNullValue(OpType));
5552       return &I;
5553     }
5554   }
5555 
5556   // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
5557   Value *X, *Y;
5558   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
5559     return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
5560 
5561   // Test if the FCmpInst instruction is used exclusively by a select as
5562   // part of a minimum or maximum operation. If so, refrain from doing
5563   // any other folding. This helps out other analyses which understand
5564   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5565   // and CodeGen. And in this case, at least one of the comparison
5566   // operands has at least one user besides the compare (the select),
5567   // which would often largely negate the benefit of folding anyway.
5568   if (I.hasOneUse())
5569     if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
5570       Value *A, *B;
5571       SelectPatternResult SPR = matchSelectPattern(SI, A, B);
5572       if (SPR.Flavor != SPF_UNKNOWN)
5573         return nullptr;
5574     }
5575 
5576   // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
5577   // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
5578   if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP())) {
5579     I.setOperand(1, ConstantFP::getNullValue(OpType));
5580     return &I;
5581   }
5582 
5583   // Handle fcmp with instruction LHS and constant RHS.
5584   Instruction *LHSI;
5585   Constant *RHSC;
5586   if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
5587     switch (LHSI->getOpcode()) {
5588     case Instruction::PHI:
5589       // Only fold fcmp into the PHI if the phi and fcmp are in the same
5590       // block.  If in the same block, we're encouraging jump threading.  If
5591       // not, we are just pessimizing the code by making an i1 phi.
5592       if (LHSI->getParent() == I.getParent())
5593         if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
5594           return NV;
5595       break;
5596     case Instruction::SIToFP:
5597     case Instruction::UIToFP:
5598       if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
5599         return NV;
5600       break;
5601     case Instruction::FDiv:
5602       if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
5603         return NV;
5604       break;
5605     case Instruction::Load:
5606       if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
5607         if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
5608           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
5609               !cast<LoadInst>(LHSI)->isVolatile())
5610             if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
5611               return Res;
5612       break;
5613   }
5614   }
5615 
5616   if (Instruction *R = foldFabsWithFcmpZero(I))
5617     return R;
5618 
5619   if (match(Op0, m_FNeg(m_Value(X)))) {
5620     // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
5621     Constant *C;
5622     if (match(Op1, m_Constant(C))) {
5623       Constant *NegC = ConstantExpr::getFNeg(C);
5624       return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
5625     }
5626   }
5627 
5628   if (match(Op0, m_FPExt(m_Value(X)))) {
5629     // fcmp (fpext X), (fpext Y) -> fcmp X, Y
5630     if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
5631       return new FCmpInst(Pred, X, Y, "", &I);
5632 
5633     // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
5634     const APFloat *C;
5635     if (match(Op1, m_APFloat(C))) {
5636       const fltSemantics &FPSem =
5637           X->getType()->getScalarType()->getFltSemantics();
5638       bool Lossy;
5639       APFloat TruncC = *C;
5640       TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
5641 
5642       // Avoid lossy conversions and denormals.
5643       // Zero is a special case that's OK to convert.
5644       APFloat Fabs = TruncC;
5645       Fabs.clearSign();
5646       if (!Lossy &&
5647           ((Fabs.compare(APFloat::getSmallestNormalized(FPSem)) !=
5648             APFloat::cmpLessThan) || Fabs.isZero())) {
5649         Constant *NewC = ConstantFP::get(X->getType(), TruncC);
5650         return new FCmpInst(Pred, X, NewC, "", &I);
5651       }
5652     }
5653   }
5654 
5655   if (I.getType()->isVectorTy())
5656     if (Instruction *Res = foldVectorCmp(I, Builder))
5657       return Res;
5658 
5659   return Changed ? &I : nullptr;
5660 }
5661