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