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