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