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