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