Improved fix for PR17827 (instcombine of shift/and/compare).
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCompares.cpp
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 "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/PatternMatch.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
24 using namespace llvm;
25 using namespace PatternMatch;
26
27 static ConstantInt *getOne(Constant *C) {
28   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29 }
30
31 /// AddOne - Add one to a ConstantInt
32 static Constant *AddOne(Constant *C) {
33   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34 }
35 /// SubOne - Subtract one from a ConstantInt
36 static Constant *SubOne(Constant *C) {
37   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
38 }
39
40 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42 }
43
44 static bool HasAddOverflow(ConstantInt *Result,
45                            ConstantInt *In1, ConstantInt *In2,
46                            bool IsSigned) {
47   if (!IsSigned)
48     return Result->getValue().ult(In1->getValue());
49
50   if (In2->isNegative())
51     return Result->getValue().sgt(In1->getValue());
52   return Result->getValue().slt(In1->getValue());
53 }
54
55 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56 /// overflowed for this type.
57 static bool AddWithOverflow(Constant *&Result, Constant *In1,
58                             Constant *In2, bool IsSigned = false) {
59   Result = ConstantExpr::getAdd(In1, In2);
60
61   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
62     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64       if (HasAddOverflow(ExtractElement(Result, Idx),
65                          ExtractElement(In1, Idx),
66                          ExtractElement(In2, Idx),
67                          IsSigned))
68         return true;
69     }
70     return false;
71   }
72
73   return HasAddOverflow(cast<ConstantInt>(Result),
74                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75                         IsSigned);
76 }
77
78 static bool HasSubOverflow(ConstantInt *Result,
79                            ConstantInt *In1, ConstantInt *In2,
80                            bool IsSigned) {
81   if (!IsSigned)
82     return Result->getValue().ugt(In1->getValue());
83
84   if (In2->isNegative())
85     return Result->getValue().slt(In1->getValue());
86
87   return Result->getValue().sgt(In1->getValue());
88 }
89
90 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91 /// overflowed for this type.
92 static bool SubWithOverflow(Constant *&Result, Constant *In1,
93                             Constant *In2, bool IsSigned = false) {
94   Result = ConstantExpr::getSub(In1, In2);
95
96   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
97     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99       if (HasSubOverflow(ExtractElement(Result, Idx),
100                          ExtractElement(In1, Idx),
101                          ExtractElement(In2, Idx),
102                          IsSigned))
103         return true;
104     }
105     return false;
106   }
107
108   return HasSubOverflow(cast<ConstantInt>(Result),
109                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110                         IsSigned);
111 }
112
113 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
114 /// comparison only checks the sign bit.  If it only checks the sign bit, set
115 /// TrueIfSigned if the result of the comparison is true when the input value is
116 /// signed.
117 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118                            bool &TrueIfSigned) {
119   switch (pred) {
120   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
121     TrueIfSigned = true;
122     return RHS->isZero();
123   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
124     TrueIfSigned = true;
125     return RHS->isAllOnesValue();
126   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
127     TrueIfSigned = false;
128     return RHS->isAllOnesValue();
129   case ICmpInst::ICMP_UGT:
130     // True if LHS u> RHS and RHS == high-bit-mask - 1
131     TrueIfSigned = true;
132     return RHS->isMaxValue(true);
133   case ICmpInst::ICMP_UGE:
134     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135     TrueIfSigned = true;
136     return RHS->getValue().isSignBit();
137   default:
138     return false;
139   }
140 }
141
142 /// Returns true if the exploded icmp can be expressed as a signed comparison
143 /// to zero and updates the predicate accordingly.
144 /// The signedness of the comparison is preserved.
145 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146   if (!ICmpInst::isSigned(pred))
147     return false;
148
149   if (RHS->isZero())
150     return ICmpInst::isRelational(pred);
151
152   if (RHS->isOne()) {
153     if (pred == ICmpInst::ICMP_SLT) {
154       pred = ICmpInst::ICMP_SLE;
155       return true;
156     }
157   } else if (RHS->isAllOnesValue()) {
158     if (pred == ICmpInst::ICMP_SGT) {
159       pred = ICmpInst::ICMP_SGE;
160       return true;
161     }
162   }
163
164   return false;
165 }
166
167 // isHighOnes - Return true if the constant is of the form 1+0+.
168 // This is the same as lowones(~X).
169 static bool isHighOnes(const ConstantInt *CI) {
170   return (~CI->getValue() + 1).isPowerOf2();
171 }
172
173 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
174 /// set of known zero and one bits, compute the maximum and minimum values that
175 /// could have the specified known zero and known one bits, returning them in
176 /// min/max.
177 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178                                                    const APInt& KnownOne,
179                                                    APInt& Min, APInt& Max) {
180   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181          KnownZero.getBitWidth() == Min.getBitWidth() &&
182          KnownZero.getBitWidth() == Max.getBitWidth() &&
183          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184   APInt UnknownBits = ~(KnownZero|KnownOne);
185
186   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187   // bit if it is unknown.
188   Min = KnownOne;
189   Max = KnownOne|UnknownBits;
190
191   if (UnknownBits.isNegative()) { // Sign bit is unknown
192     Min.setBit(Min.getBitWidth()-1);
193     Max.clearBit(Max.getBitWidth()-1);
194   }
195 }
196
197 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198 // a set of known zero and one bits, compute the maximum and minimum values that
199 // could have the specified known zero and known one bits, returning them in
200 // min/max.
201 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202                                                      const APInt &KnownOne,
203                                                      APInt &Min, APInt &Max) {
204   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205          KnownZero.getBitWidth() == Min.getBitWidth() &&
206          KnownZero.getBitWidth() == Max.getBitWidth() &&
207          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208   APInt UnknownBits = ~(KnownZero|KnownOne);
209
210   // The minimum value is when the unknown bits are all zeros.
211   Min = KnownOne;
212   // The maximum value is when the unknown bits are all ones.
213   Max = KnownOne|UnknownBits;
214 }
215
216
217
218 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219 ///   cmp pred (load (gep GV, ...)), cmpcst
220 /// where GV is a global variable with a constant initializer.  Try to simplify
221 /// this into some simple computation that does not need the load.  For example
222 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223 ///
224 /// If AndCst is non-null, then the loaded value is masked with that constant
225 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
226 Instruction *InstCombiner::
227 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228                              CmpInst &ICI, ConstantInt *AndCst) {
229   // We need TD information to know the pointer size unless this is inbounds.
230   if (!GEP->isInBounds() && TD == 0)
231     return 0;
232
233   Constant *Init = GV->getInitializer();
234   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
235     return 0;
236
237   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
238   if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
239
240   // There are many forms of this optimization we can handle, for now, just do
241   // the simple index into a single-dimensional array.
242   //
243   // Require: GEP GV, 0, i {{, constant indices}}
244   if (GEP->getNumOperands() < 3 ||
245       !isa<ConstantInt>(GEP->getOperand(1)) ||
246       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247       isa<Constant>(GEP->getOperand(2)))
248     return 0;
249
250   // Check that indices after the variable are constants and in-range for the
251   // type they index.  Collect the indices.  This is typically for arrays of
252   // structs.
253   SmallVector<unsigned, 4> LaterIndices;
254
255   Type *EltTy = Init->getType()->getArrayElementType();
256   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
258     if (Idx == 0) return 0;  // Variable index.
259
260     uint64_t IdxVal = Idx->getZExtValue();
261     if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
262
263     if (StructType *STy = dyn_cast<StructType>(EltTy))
264       EltTy = STy->getElementType(IdxVal);
265     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
266       if (IdxVal >= ATy->getNumElements()) return 0;
267       EltTy = ATy->getElementType();
268     } else {
269       return 0; // Unknown type.
270     }
271
272     LaterIndices.push_back(IdxVal);
273   }
274
275   enum { Overdefined = -3, Undefined = -2 };
276
277   // Variables for our state machines.
278
279   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
282   // undefined, otherwise set to the first true element.  SecondTrueElement is
283   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285
286   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287   // form "i != 47 & i != 87".  Same state transitions as for true elements.
288   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
289
290   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291   /// define a state machine that triggers for ranges of values that the index
292   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
293   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294   /// index in the range (inclusive).  We use -2 for undefined here because we
295   /// use relative comparisons and don't want 0-1 to match -1.
296   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
297
298   // MagicBitvector - This is a magic bitvector where we set a bit if the
299   // comparison is true for element 'i'.  If there are 64 elements or less in
300   // the array, this will fully represent all the comparison results.
301   uint64_t MagicBitvector = 0;
302
303
304   // Scan the array and see if one of our patterns matches.
305   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
306   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
307     Constant *Elt = Init->getAggregateElement(i);
308     if (Elt == 0) return 0;
309
310     // If this is indexing an array of structures, get the structure element.
311     if (!LaterIndices.empty())
312       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
313
314     // If the element is masked, handle it.
315     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
316
317     // Find out if the comparison would be true or false for the i'th element.
318     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
319                                                   CompareRHS, TD, TLI);
320     // If the result is undef for this element, ignore it.
321     if (isa<UndefValue>(C)) {
322       // Extend range state machines to cover this element in case there is an
323       // undef in the middle of the range.
324       if (TrueRangeEnd == (int)i-1)
325         TrueRangeEnd = i;
326       if (FalseRangeEnd == (int)i-1)
327         FalseRangeEnd = i;
328       continue;
329     }
330
331     // If we can't compute the result for any of the elements, we have to give
332     // up evaluating the entire conditional.
333     if (!isa<ConstantInt>(C)) return 0;
334
335     // Otherwise, we know if the comparison is true or false for this element,
336     // update our state machines.
337     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
338
339     // State machine for single/double/range index comparison.
340     if (IsTrueForElt) {
341       // Update the TrueElement state machine.
342       if (FirstTrueElement == Undefined)
343         FirstTrueElement = TrueRangeEnd = i;  // First true element.
344       else {
345         // Update double-compare state machine.
346         if (SecondTrueElement == Undefined)
347           SecondTrueElement = i;
348         else
349           SecondTrueElement = Overdefined;
350
351         // Update range state machine.
352         if (TrueRangeEnd == (int)i-1)
353           TrueRangeEnd = i;
354         else
355           TrueRangeEnd = Overdefined;
356       }
357     } else {
358       // Update the FalseElement state machine.
359       if (FirstFalseElement == Undefined)
360         FirstFalseElement = FalseRangeEnd = i; // First false element.
361       else {
362         // Update double-compare state machine.
363         if (SecondFalseElement == Undefined)
364           SecondFalseElement = i;
365         else
366           SecondFalseElement = Overdefined;
367
368         // Update range state machine.
369         if (FalseRangeEnd == (int)i-1)
370           FalseRangeEnd = i;
371         else
372           FalseRangeEnd = Overdefined;
373       }
374     }
375
376
377     // If this element is in range, update our magic bitvector.
378     if (i < 64 && IsTrueForElt)
379       MagicBitvector |= 1ULL << i;
380
381     // If all of our states become overdefined, bail out early.  Since the
382     // predicate is expensive, only check it every 8 elements.  This is only
383     // really useful for really huge arrays.
384     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
385         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
386         FalseRangeEnd == Overdefined)
387       return 0;
388   }
389
390   // Now that we've scanned the entire array, emit our new comparison(s).  We
391   // order the state machines in complexity of the generated code.
392   Value *Idx = GEP->getOperand(2);
393
394   // If the index is larger than the pointer size of the target, truncate the
395   // index down like the GEP would do implicitly.  We don't have to do this for
396   // an inbounds GEP because the index can't be out of range.
397   if (!GEP->isInBounds()) {
398     Type *IntPtrTy = TD->getIntPtrType(GEP->getType());
399     unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
400     if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
401       Idx = Builder->CreateTrunc(Idx, IntPtrTy);
402   }
403
404   // If the comparison is only true for one or two elements, emit direct
405   // comparisons.
406   if (SecondTrueElement != Overdefined) {
407     // None true -> false.
408     if (FirstTrueElement == Undefined)
409       return ReplaceInstUsesWith(ICI, Builder->getFalse());
410
411     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
412
413     // True for one element -> 'i == 47'.
414     if (SecondTrueElement == Undefined)
415       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
416
417     // True for two elements -> 'i == 47 | i == 72'.
418     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
419     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
420     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
421     return BinaryOperator::CreateOr(C1, C2);
422   }
423
424   // If the comparison is only false for one or two elements, emit direct
425   // comparisons.
426   if (SecondFalseElement != Overdefined) {
427     // None false -> true.
428     if (FirstFalseElement == Undefined)
429       return ReplaceInstUsesWith(ICI, Builder->getTrue());
430
431     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
432
433     // False for one element -> 'i != 47'.
434     if (SecondFalseElement == Undefined)
435       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
436
437     // False for two elements -> 'i != 47 & i != 72'.
438     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
439     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
440     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
441     return BinaryOperator::CreateAnd(C1, C2);
442   }
443
444   // If the comparison can be replaced with a range comparison for the elements
445   // where it is true, emit the range check.
446   if (TrueRangeEnd != Overdefined) {
447     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
448
449     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
450     if (FirstTrueElement) {
451       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
452       Idx = Builder->CreateAdd(Idx, Offs);
453     }
454
455     Value *End = ConstantInt::get(Idx->getType(),
456                                   TrueRangeEnd-FirstTrueElement+1);
457     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
458   }
459
460   // False range check.
461   if (FalseRangeEnd != Overdefined) {
462     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
463     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
464     if (FirstFalseElement) {
465       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
466       Idx = Builder->CreateAdd(Idx, Offs);
467     }
468
469     Value *End = ConstantInt::get(Idx->getType(),
470                                   FalseRangeEnd-FirstFalseElement);
471     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
472   }
473
474
475   // If a magic bitvector captures the entire comparison state
476   // of this load, replace it with computation that does:
477   //   ((magic_cst >> i) & 1) != 0
478   {
479     Type *Ty = 0;
480
481     // Look for an appropriate type:
482     // - The type of Idx if the magic fits
483     // - The smallest fitting legal type if we have a DataLayout
484     // - Default to i32
485     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
486       Ty = Idx->getType();
487     else if (TD)
488       Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
489     else if (ArrayElementCount <= 32)
490       Ty = Type::getInt32Ty(Init->getContext());
491
492     if (Ty != 0) {
493       Value *V = Builder->CreateIntCast(Idx, Ty, false);
494       V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495       V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
497     }
498   }
499
500   return 0;
501 }
502
503
504 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
505 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
506 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
507 /// be complex, and scales are involved.  The above expression would also be
508 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
509 /// This later form is less amenable to optimization though, and we are allowed
510 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
511 ///
512 /// If we can't emit an optimized form for this expression, this returns null.
513 ///
514 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
515   DataLayout &TD = *IC.getDataLayout();
516   gep_type_iterator GTI = gep_type_begin(GEP);
517
518   // Check to see if this gep only has a single variable index.  If so, and if
519   // any constant indices are a multiple of its scale, then we can compute this
520   // in terms of the scale of the variable index.  For example, if the GEP
521   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
522   // because the expression will cross zero at the same point.
523   unsigned i, e = GEP->getNumOperands();
524   int64_t Offset = 0;
525   for (i = 1; i != e; ++i, ++GTI) {
526     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
527       // Compute the aggregate offset of constant indices.
528       if (CI->isZero()) continue;
529
530       // Handle a struct index, which adds its field offset to the pointer.
531       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
532         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
533       } else {
534         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
535         Offset += Size*CI->getSExtValue();
536       }
537     } else {
538       // Found our variable index.
539       break;
540     }
541   }
542
543   // If there are no variable indices, we must have a constant offset, just
544   // evaluate it the general way.
545   if (i == e) return 0;
546
547   Value *VariableIdx = GEP->getOperand(i);
548   // Determine the scale factor of the variable element.  For example, this is
549   // 4 if the variable index is into an array of i32.
550   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
551
552   // Verify that there are no other variable indices.  If so, emit the hard way.
553   for (++i, ++GTI; i != e; ++i, ++GTI) {
554     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
555     if (!CI) return 0;
556
557     // Compute the aggregate offset of constant indices.
558     if (CI->isZero()) continue;
559
560     // Handle a struct index, which adds its field offset to the pointer.
561     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
562       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
563     } else {
564       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
565       Offset += Size*CI->getSExtValue();
566     }
567   }
568
569
570
571   // Okay, we know we have a single variable index, which must be a
572   // pointer/array/vector index.  If there is no offset, life is simple, return
573   // the index.
574   Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
575   unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
576   if (Offset == 0) {
577     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
578     // we don't need to bother extending: the extension won't affect where the
579     // computation crosses zero.
580     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
581       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
582     }
583     return VariableIdx;
584   }
585
586   // Otherwise, there is an index.  The computation we will do will be modulo
587   // the pointer size, so get it.
588   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
589
590   Offset &= PtrSizeMask;
591   VariableScale &= PtrSizeMask;
592
593   // To do this transformation, any constant index must be a multiple of the
594   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
595   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
596   // multiple of the variable scale.
597   int64_t NewOffs = Offset / (int64_t)VariableScale;
598   if (Offset != NewOffs*(int64_t)VariableScale)
599     return 0;
600
601   // Okay, we can do this evaluation.  Start by converting the index to intptr.
602   if (VariableIdx->getType() != IntPtrTy)
603     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
604                                             true /*Signed*/);
605   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
606   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
607 }
608
609 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
610 /// else.  At this point we know that the GEP is on the LHS of the comparison.
611 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
612                                        ICmpInst::Predicate Cond,
613                                        Instruction &I) {
614   // Don't transform signed compares of GEPs into index compares. Even if the
615   // GEP is inbounds, the final add of the base pointer can have signed overflow
616   // and would change the result of the icmp.
617   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
618   // the maximum signed value for the pointer type.
619   if (ICmpInst::isSigned(Cond))
620     return 0;
621
622   // Look through bitcasts.
623   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
624     RHS = BCI->getOperand(0);
625
626   Value *PtrBase = GEPLHS->getOperand(0);
627   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
628     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
629     // This transformation (ignoring the base and scales) is valid because we
630     // know pointers can't overflow since the gep is inbounds.  See if we can
631     // output an optimized form.
632     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
633
634     // If not, synthesize the offset the hard way.
635     if (Offset == 0)
636       Offset = EmitGEPOffset(GEPLHS);
637     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
638                         Constant::getNullValue(Offset->getType()));
639   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
640     // If the base pointers are different, but the indices are the same, just
641     // compare the base pointer.
642     if (PtrBase != GEPRHS->getOperand(0)) {
643       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
644       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
645                         GEPRHS->getOperand(0)->getType();
646       if (IndicesTheSame)
647         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
648           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
649             IndicesTheSame = false;
650             break;
651           }
652
653       // If all indices are the same, just compare the base pointers.
654       if (IndicesTheSame)
655         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
656
657       // If we're comparing GEPs with two base pointers that only differ in type
658       // and both GEPs have only constant indices or just one use, then fold
659       // the compare with the adjusted indices.
660       if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
661           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
662           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
663           PtrBase->stripPointerCasts() ==
664             GEPRHS->getOperand(0)->stripPointerCasts()) {
665         Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
666                                          EmitGEPOffset(GEPLHS),
667                                          EmitGEPOffset(GEPRHS));
668         return ReplaceInstUsesWith(I, Cmp);
669       }
670
671       // Otherwise, the base pointers are different and the indices are
672       // different, bail out.
673       return 0;
674     }
675
676     // If one of the GEPs has all zero indices, recurse.
677     bool AllZeros = true;
678     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
679       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
680           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
681         AllZeros = false;
682         break;
683       }
684     if (AllZeros)
685       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
686                          ICmpInst::getSwappedPredicate(Cond), I);
687
688     // If the other GEP has all zero indices, recurse.
689     AllZeros = true;
690     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
691       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
692           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
693         AllZeros = false;
694         break;
695       }
696     if (AllZeros)
697       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
698
699     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
700     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
701       // If the GEPs only differ by one index, compare it.
702       unsigned NumDifferences = 0;  // Keep track of # differences.
703       unsigned DiffOperand = 0;     // The operand that differs.
704       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
705         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
706           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
707                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
708             // Irreconcilable differences.
709             NumDifferences = 2;
710             break;
711           } else {
712             if (NumDifferences++) break;
713             DiffOperand = i;
714           }
715         }
716
717       if (NumDifferences == 0)   // SAME GEP?
718         return ReplaceInstUsesWith(I, // No comparison is needed here.
719                              Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
720
721       else if (NumDifferences == 1 && GEPsInBounds) {
722         Value *LHSV = GEPLHS->getOperand(DiffOperand);
723         Value *RHSV = GEPRHS->getOperand(DiffOperand);
724         // Make sure we do a signed comparison here.
725         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
726       }
727     }
728
729     // Only lower this if the icmp is the only user of the GEP or if we expect
730     // the result to fold to a constant!
731     if (TD &&
732         GEPsInBounds &&
733         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
734         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
735       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
736       Value *L = EmitGEPOffset(GEPLHS);
737       Value *R = EmitGEPOffset(GEPRHS);
738       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
739     }
740   }
741   return 0;
742 }
743
744 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
745 Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
746                                             Value *X, ConstantInt *CI,
747                                             ICmpInst::Predicate Pred) {
748   // If we have X+0, exit early (simplifying logic below) and let it get folded
749   // elsewhere.   icmp X+0, X  -> icmp X, X
750   if (CI->isZero()) {
751     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
752     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
753   }
754
755   // (X+4) == X -> false.
756   if (Pred == ICmpInst::ICMP_EQ)
757     return ReplaceInstUsesWith(ICI, Builder->getFalse());
758
759   // (X+4) != X -> true.
760   if (Pred == ICmpInst::ICMP_NE)
761     return ReplaceInstUsesWith(ICI, Builder->getTrue());
762
763   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
764   // so the values can never be equal.  Similarly for all other "or equals"
765   // operators.
766
767   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
768   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
769   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
770   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
771     Value *R =
772       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
773     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
774   }
775
776   // (X+1) >u X        --> X <u (0-1)        --> X != 255
777   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
778   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
779   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
780     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
781
782   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
783   ConstantInt *SMax = ConstantInt::get(X->getContext(),
784                                        APInt::getSignedMaxValue(BitWidth));
785
786   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
787   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
788   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
789   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
790   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
791   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
792   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
793     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
794
795   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
796   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
797   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
798   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
799   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
800   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
801
802   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
803   Constant *C = Builder->getInt(CI->getValue()-1);
804   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
805 }
806
807 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
808 /// and CmpRHS are both known to be integer constants.
809 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
810                                           ConstantInt *DivRHS) {
811   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
812   const APInt &CmpRHSV = CmpRHS->getValue();
813
814   // FIXME: If the operand types don't match the type of the divide
815   // then don't attempt this transform. The code below doesn't have the
816   // logic to deal with a signed divide and an unsigned compare (and
817   // vice versa). This is because (x /s C1) <s C2  produces different
818   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
819   // (x /u C1) <u C2.  Simply casting the operands and result won't
820   // work. :(  The if statement below tests that condition and bails
821   // if it finds it.
822   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
823   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
824     return 0;
825   if (DivRHS->isZero())
826     return 0; // The ProdOV computation fails on divide by zero.
827   if (DivIsSigned && DivRHS->isAllOnesValue())
828     return 0; // The overflow computation also screws up here
829   if (DivRHS->isOne()) {
830     // This eliminates some funny cases with INT_MIN.
831     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
832     return &ICI;
833   }
834
835   // Compute Prod = CI * DivRHS. We are essentially solving an equation
836   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
837   // C2 (CI). By solving for X we can turn this into a range check
838   // instead of computing a divide.
839   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
840
841   // Determine if the product overflows by seeing if the product is
842   // not equal to the divide. Make sure we do the same kind of divide
843   // as in the LHS instruction that we're folding.
844   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
845                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
846
847   // Get the ICmp opcode
848   ICmpInst::Predicate Pred = ICI.getPredicate();
849
850   /// If the division is known to be exact, then there is no remainder from the
851   /// divide, so the covered range size is unit, otherwise it is the divisor.
852   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
853
854   // Figure out the interval that is being checked.  For example, a comparison
855   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
856   // Compute this interval based on the constants involved and the signedness of
857   // the compare/divide.  This computes a half-open interval, keeping track of
858   // whether either value in the interval overflows.  After analysis each
859   // overflow variable is set to 0 if it's corresponding bound variable is valid
860   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
861   int LoOverflow = 0, HiOverflow = 0;
862   Constant *LoBound = 0, *HiBound = 0;
863
864   if (!DivIsSigned) {  // udiv
865     // e.g. X/5 op 3  --> [15, 20)
866     LoBound = Prod;
867     HiOverflow = LoOverflow = ProdOV;
868     if (!HiOverflow) {
869       // If this is not an exact divide, then many values in the range collapse
870       // to the same result value.
871       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
872     }
873
874   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
875     if (CmpRHSV == 0) {       // (X / pos) op 0
876       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
877       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
878       HiBound = RangeSize;
879     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
880       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
881       HiOverflow = LoOverflow = ProdOV;
882       if (!HiOverflow)
883         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
884     } else {                       // (X / pos) op neg
885       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
886       HiBound = AddOne(Prod);
887       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
888       if (!LoOverflow) {
889         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
890         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
891       }
892     }
893   } else if (DivRHS->isNegative()) { // Divisor is < 0.
894     if (DivI->isExact())
895       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
896     if (CmpRHSV == 0) {       // (X / neg) op 0
897       // e.g. X/-5 op 0  --> [-4, 5)
898       LoBound = AddOne(RangeSize);
899       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
900       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
901         HiOverflow = 1;            // [INTMIN+1, overflow)
902         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
903       }
904     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
905       // e.g. X/-5 op 3  --> [-19, -14)
906       HiBound = AddOne(Prod);
907       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
908       if (!LoOverflow)
909         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
910     } else {                       // (X / neg) op neg
911       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
912       LoOverflow = HiOverflow = ProdOV;
913       if (!HiOverflow)
914         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
915     }
916
917     // Dividing by a negative swaps the condition.  LT <-> GT
918     Pred = ICmpInst::getSwappedPredicate(Pred);
919   }
920
921   Value *X = DivI->getOperand(0);
922   switch (Pred) {
923   default: llvm_unreachable("Unhandled icmp opcode!");
924   case ICmpInst::ICMP_EQ:
925     if (LoOverflow && HiOverflow)
926       return ReplaceInstUsesWith(ICI, Builder->getFalse());
927     if (HiOverflow)
928       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
929                           ICmpInst::ICMP_UGE, X, LoBound);
930     if (LoOverflow)
931       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
932                           ICmpInst::ICMP_ULT, X, HiBound);
933     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
934                                                     DivIsSigned, true));
935   case ICmpInst::ICMP_NE:
936     if (LoOverflow && HiOverflow)
937       return ReplaceInstUsesWith(ICI, Builder->getTrue());
938     if (HiOverflow)
939       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
940                           ICmpInst::ICMP_ULT, X, LoBound);
941     if (LoOverflow)
942       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
943                           ICmpInst::ICMP_UGE, X, HiBound);
944     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
945                                                     DivIsSigned, false));
946   case ICmpInst::ICMP_ULT:
947   case ICmpInst::ICMP_SLT:
948     if (LoOverflow == +1)   // Low bound is greater than input range.
949       return ReplaceInstUsesWith(ICI, Builder->getTrue());
950     if (LoOverflow == -1)   // Low bound is less than input range.
951       return ReplaceInstUsesWith(ICI, Builder->getFalse());
952     return new ICmpInst(Pred, X, LoBound);
953   case ICmpInst::ICMP_UGT:
954   case ICmpInst::ICMP_SGT:
955     if (HiOverflow == +1)       // High bound greater than input range.
956       return ReplaceInstUsesWith(ICI, Builder->getFalse());
957     if (HiOverflow == -1)       // High bound less than input range.
958       return ReplaceInstUsesWith(ICI, Builder->getTrue());
959     if (Pred == ICmpInst::ICMP_UGT)
960       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
961     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
962   }
963 }
964
965 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
966 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
967                                           ConstantInt *ShAmt) {
968   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
969
970   // Check that the shift amount is in range.  If not, don't perform
971   // undefined shifts.  When the shift is visited it will be
972   // simplified.
973   uint32_t TypeBits = CmpRHSV.getBitWidth();
974   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
975   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
976     return 0;
977
978   if (!ICI.isEquality()) {
979     // If we have an unsigned comparison and an ashr, we can't simplify this.
980     // Similarly for signed comparisons with lshr.
981     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
982       return 0;
983
984     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
985     // by a power of 2.  Since we already have logic to simplify these,
986     // transform to div and then simplify the resultant comparison.
987     if (Shr->getOpcode() == Instruction::AShr &&
988         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
989       return 0;
990
991     // Revisit the shift (to delete it).
992     Worklist.Add(Shr);
993
994     Constant *DivCst =
995       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
996
997     Value *Tmp =
998       Shr->getOpcode() == Instruction::AShr ?
999       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1000       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
1001
1002     ICI.setOperand(0, Tmp);
1003
1004     // If the builder folded the binop, just return it.
1005     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1006     if (TheDiv == 0)
1007       return &ICI;
1008
1009     // Otherwise, fold this div/compare.
1010     assert(TheDiv->getOpcode() == Instruction::SDiv ||
1011            TheDiv->getOpcode() == Instruction::UDiv);
1012
1013     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1014     assert(Res && "This div/cst should have folded!");
1015     return Res;
1016   }
1017
1018
1019   // If we are comparing against bits always shifted out, the
1020   // comparison cannot succeed.
1021   APInt Comp = CmpRHSV << ShAmtVal;
1022   ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1023   if (Shr->getOpcode() == Instruction::LShr)
1024     Comp = Comp.lshr(ShAmtVal);
1025   else
1026     Comp = Comp.ashr(ShAmtVal);
1027
1028   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1029     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1030     Constant *Cst = Builder->getInt1(IsICMP_NE);
1031     return ReplaceInstUsesWith(ICI, Cst);
1032   }
1033
1034   // Otherwise, check to see if the bits shifted out are known to be zero.
1035   // If so, we can compare against the unshifted value:
1036   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1037   if (Shr->hasOneUse() && Shr->isExact())
1038     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1039
1040   if (Shr->hasOneUse()) {
1041     // Otherwise strength reduce the shift into an and.
1042     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1043     Constant *Mask = Builder->getInt(Val);
1044
1045     Value *And = Builder->CreateAnd(Shr->getOperand(0),
1046                                     Mask, Shr->getName()+".mask");
1047     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1048   }
1049   return 0;
1050 }
1051
1052
1053 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1054 ///
1055 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1056                                                           Instruction *LHSI,
1057                                                           ConstantInt *RHS) {
1058   const APInt &RHSV = RHS->getValue();
1059
1060   switch (LHSI->getOpcode()) {
1061   case Instruction::Trunc:
1062     if (ICI.isEquality() && LHSI->hasOneUse()) {
1063       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1064       // of the high bits truncated out of x are known.
1065       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1066              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1067       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1068       ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1069
1070       // If all the high bits are known, we can do this xform.
1071       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1072         // Pull in the high bits from known-ones set.
1073         APInt NewRHS = RHS->getValue().zext(SrcBits);
1074         NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1075         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1076                             Builder->getInt(NewRHS));
1077       }
1078     }
1079     break;
1080
1081   case Instruction::Xor:         // (icmp pred (xor X, XorCst), CI)
1082     if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1083       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1084       // fold the xor.
1085       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1086           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1087         Value *CompareVal = LHSI->getOperand(0);
1088
1089         // If the sign bit of the XorCst is not set, there is no change to
1090         // the operation, just stop using the Xor.
1091         if (!XorCst->isNegative()) {
1092           ICI.setOperand(0, CompareVal);
1093           Worklist.Add(LHSI);
1094           return &ICI;
1095         }
1096
1097         // Was the old condition true if the operand is positive?
1098         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1099
1100         // If so, the new one isn't.
1101         isTrueIfPositive ^= true;
1102
1103         if (isTrueIfPositive)
1104           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1105                               SubOne(RHS));
1106         else
1107           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1108                               AddOne(RHS));
1109       }
1110
1111       if (LHSI->hasOneUse()) {
1112         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1113         if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1114           const APInt &SignBit = XorCst->getValue();
1115           ICmpInst::Predicate Pred = ICI.isSigned()
1116                                          ? ICI.getUnsignedPredicate()
1117                                          : ICI.getSignedPredicate();
1118           return new ICmpInst(Pred, LHSI->getOperand(0),
1119                               Builder->getInt(RHSV ^ SignBit));
1120         }
1121
1122         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1123         if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1124           const APInt &NotSignBit = XorCst->getValue();
1125           ICmpInst::Predicate Pred = ICI.isSigned()
1126                                          ? ICI.getUnsignedPredicate()
1127                                          : ICI.getSignedPredicate();
1128           Pred = ICI.getSwappedPredicate(Pred);
1129           return new ICmpInst(Pred, LHSI->getOperand(0),
1130                               Builder->getInt(RHSV ^ NotSignBit));
1131         }
1132       }
1133
1134       // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1135       //   iff -C is a power of 2
1136       if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1137           XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1138         return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
1139
1140       // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1141       //   iff -C is a power of 2
1142       if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1143           XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1144         return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
1145     }
1146     break;
1147   case Instruction::And:         // (icmp pred (and X, AndCst), RHS)
1148     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1149         LHSI->getOperand(0)->hasOneUse()) {
1150       ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1151
1152       // If the LHS is an AND of a truncating cast, we can widen the
1153       // and/compare to be the input width without changing the value
1154       // produced, eliminating a cast.
1155       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1156         // We can do this transformation if either the AND constant does not
1157         // have its sign bit set or if it is an equality comparison.
1158         // Extending a relational comparison when we're checking the sign
1159         // bit would not work.
1160         if (ICI.isEquality() ||
1161             (!AndCst->isNegative() && RHSV.isNonNegative())) {
1162           Value *NewAnd =
1163             Builder->CreateAnd(Cast->getOperand(0),
1164                                ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1165           NewAnd->takeName(LHSI);
1166           return new ICmpInst(ICI.getPredicate(), NewAnd,
1167                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1168         }
1169       }
1170
1171       // If the LHS is an AND of a zext, and we have an equality compare, we can
1172       // shrink the and/compare to the smaller type, eliminating the cast.
1173       if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1174         IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1175         // Make sure we don't compare the upper bits, SimplifyDemandedBits
1176         // should fold the icmp to true/false in that case.
1177         if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1178           Value *NewAnd =
1179             Builder->CreateAnd(Cast->getOperand(0),
1180                                ConstantExpr::getTrunc(AndCst, Ty));
1181           NewAnd->takeName(LHSI);
1182           return new ICmpInst(ICI.getPredicate(), NewAnd,
1183                               ConstantExpr::getTrunc(RHS, Ty));
1184         }
1185       }
1186
1187       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1188       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1189       // happens a LOT in code produced by the C front-end, for bitfield
1190       // access.
1191       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1192       if (Shift && !Shift->isShift())
1193         Shift = 0;
1194
1195       ConstantInt *ShAmt;
1196       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1197
1198       // This seemingly simple opportunity to fold away a shift turns out to
1199       // be rather complicated. See PR17827
1200       // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1201       if (ShAmt) {
1202         bool CanFold = false;
1203         unsigned ShiftOpcode = Shift->getOpcode();
1204         if (ShiftOpcode == Instruction::AShr) {
1205           // There may be some constraints that make this possible,
1206           // but nothing simple has been discovered yet.
1207           CanFold = false;
1208         } else if (ShiftOpcode == Instruction::Shl) {
1209           // For a left shift, we can fold if the comparison is not signed.
1210           // We can also fold a signed comparison if the mask value and
1211           // comparison value are not negative. These constraints may not be
1212           // obvious, but we can prove that they are correct using an SMT
1213           // solver such as "Z3" :
1214           // http://rise4fun.com/Z3/DyMp
1215           if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1216             CanFold = true;
1217         } else if (ShiftOpcode == Instruction::LShr) {
1218           // For a logical right shift, we can fold if the comparison is not
1219           // signed. We can also fold a signed comparison if the shifted mask
1220           // value and the shifted comparison value are not negative.
1221           // These constraints may not be obvious, but we can prove that they
1222           // are correct using an SMT solver such as "Z3" :
1223           // http://rise4fun.com/Z3/Tslfh
1224           if (!ICI.isSigned())
1225             CanFold = true;
1226           else {
1227             ConstantInt *ShiftedAndCst =
1228               cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1229             ConstantInt *ShiftedRHSCst =
1230               cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1231             
1232             if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1233               CanFold = true;
1234           }
1235         }
1236
1237         if (CanFold) {
1238           Constant *NewCst;
1239           if (ShiftOpcode == Instruction::Shl)
1240             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1241           else
1242             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1243
1244           // Check to see if we are shifting out any of the bits being
1245           // compared.
1246           if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1247             // If we shifted bits out, the fold is not going to work out.
1248             // As a special case, check to see if this means that the
1249             // result is always true or false now.
1250             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1251               return ReplaceInstUsesWith(ICI, Builder->getFalse());
1252             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1253               return ReplaceInstUsesWith(ICI, Builder->getTrue());
1254           } else {
1255             ICI.setOperand(1, NewCst);
1256             Constant *NewAndCst;
1257             if (ShiftOpcode == Instruction::Shl)
1258               NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1259             else
1260               NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1261             LHSI->setOperand(1, NewAndCst);
1262             LHSI->setOperand(0, Shift->getOperand(0));
1263             Worklist.Add(Shift); // Shift is dead.
1264             return &ICI;
1265           }
1266         }
1267       }
1268
1269       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1270       // preferable because it allows the C<<Y expression to be hoisted out
1271       // of a loop if Y is invariant and X is not.
1272       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1273           ICI.isEquality() && !Shift->isArithmeticShift() &&
1274           !isa<Constant>(Shift->getOperand(0))) {
1275         // Compute C << Y.
1276         Value *NS;
1277         if (Shift->getOpcode() == Instruction::LShr) {
1278           NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1279         } else {
1280           // Insert a logical shift.
1281           NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1282         }
1283
1284         // Compute X & (C << Y).
1285         Value *NewAnd =
1286           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1287
1288         ICI.setOperand(0, NewAnd);
1289         return &ICI;
1290       }
1291
1292       // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1293       // bit set in (X & AndCst) will produce a result greater than RHSV.
1294       if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1295         unsigned NTZ = AndCst->getValue().countTrailingZeros();
1296         if ((NTZ < AndCst->getBitWidth()) &&
1297             APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
1298           return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1299                               Constant::getNullValue(RHS->getType()));
1300       }
1301     }
1302
1303     // Try to optimize things like "A[i]&42 == 0" to index computations.
1304     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1305       if (GetElementPtrInst *GEP =
1306           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1307         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1308           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1309               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1310             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1311             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1312               return Res;
1313           }
1314     }
1315
1316     // X & -C == -C -> X >  u ~C
1317     // X & -C != -C -> X <= u ~C
1318     //   iff C is a power of 2
1319     if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1320       return new ICmpInst(
1321           ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1322                                                   : ICmpInst::ICMP_ULE,
1323           LHSI->getOperand(0), SubOne(RHS));
1324     break;
1325
1326   case Instruction::Or: {
1327     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1328       break;
1329     Value *P, *Q;
1330     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1331       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1332       // -> and (icmp eq P, null), (icmp eq Q, null).
1333       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1334                                         Constant::getNullValue(P->getType()));
1335       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1336                                         Constant::getNullValue(Q->getType()));
1337       Instruction *Op;
1338       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1339         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1340       else
1341         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1342       return Op;
1343     }
1344     break;
1345   }
1346
1347   case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
1348     ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1349     if (!Val) break;
1350
1351     // If this is a signed comparison to 0 and the mul is sign preserving,
1352     // use the mul LHS operand instead.
1353     ICmpInst::Predicate pred = ICI.getPredicate();
1354     if (isSignTest(pred, RHS) && !Val->isZero() &&
1355         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1356       return new ICmpInst(Val->isNegative() ?
1357                           ICmpInst::getSwappedPredicate(pred) : pred,
1358                           LHSI->getOperand(0),
1359                           Constant::getNullValue(RHS->getType()));
1360
1361     break;
1362   }
1363
1364   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1365     uint32_t TypeBits = RHSV.getBitWidth();
1366     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1367     if (!ShAmt) {
1368       Value *X;
1369       // (1 << X) pred P2 -> X pred Log2(P2)
1370       if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1371         bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1372         ICmpInst::Predicate Pred = ICI.getPredicate();
1373         if (ICI.isUnsigned()) {
1374           if (!RHSVIsPowerOf2) {
1375             // (1 << X) <  30 -> X <= 4
1376             // (1 << X) <= 30 -> X <= 4
1377             // (1 << X) >= 30 -> X >  4
1378             // (1 << X) >  30 -> X >  4
1379             if (Pred == ICmpInst::ICMP_ULT)
1380               Pred = ICmpInst::ICMP_ULE;
1381             else if (Pred == ICmpInst::ICMP_UGE)
1382               Pred = ICmpInst::ICMP_UGT;
1383           }
1384           unsigned RHSLog2 = RHSV.logBase2();
1385
1386           // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1387           // (1 << X) >  2147483648 -> X >  31 -> false
1388           // (1 << X) <= 2147483648 -> X <= 31 -> true
1389           // (1 << X) <  2147483648 -> X <  31 -> X != 31
1390           if (RHSLog2 == TypeBits-1) {
1391             if (Pred == ICmpInst::ICMP_UGE)
1392               Pred = ICmpInst::ICMP_EQ;
1393             else if (Pred == ICmpInst::ICMP_UGT)
1394               return ReplaceInstUsesWith(ICI, Builder->getFalse());
1395             else if (Pred == ICmpInst::ICMP_ULE)
1396               return ReplaceInstUsesWith(ICI, Builder->getTrue());
1397             else if (Pred == ICmpInst::ICMP_ULT)
1398               Pred = ICmpInst::ICMP_NE;
1399           }
1400
1401           return new ICmpInst(Pred, X,
1402                               ConstantInt::get(RHS->getType(), RHSLog2));
1403         } else if (ICI.isSigned()) {
1404           if (RHSV.isAllOnesValue()) {
1405             // (1 << X) <= -1 -> X == 31
1406             if (Pred == ICmpInst::ICMP_SLE)
1407               return new ICmpInst(ICmpInst::ICMP_EQ, X,
1408                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1409
1410             // (1 << X) >  -1 -> X != 31
1411             if (Pred == ICmpInst::ICMP_SGT)
1412               return new ICmpInst(ICmpInst::ICMP_NE, X,
1413                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1414           } else if (!RHSV) {
1415             // (1 << X) <  0 -> X == 31
1416             // (1 << X) <= 0 -> X == 31
1417             if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1418               return new ICmpInst(ICmpInst::ICMP_EQ, X,
1419                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1420
1421             // (1 << X) >= 0 -> X != 31
1422             // (1 << X) >  0 -> X != 31
1423             if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1424               return new ICmpInst(ICmpInst::ICMP_NE, X,
1425                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1426           }
1427         } else if (ICI.isEquality()) {
1428           if (RHSVIsPowerOf2)
1429             return new ICmpInst(
1430                 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1431
1432           return ReplaceInstUsesWith(
1433               ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1434                                              : Builder->getTrue());
1435         }
1436       }
1437       break;
1438     }
1439
1440     // Check that the shift amount is in range.  If not, don't perform
1441     // undefined shifts.  When the shift is visited it will be
1442     // simplified.
1443     if (ShAmt->uge(TypeBits))
1444       break;
1445
1446     if (ICI.isEquality()) {
1447       // If we are comparing against bits always shifted out, the
1448       // comparison cannot succeed.
1449       Constant *Comp =
1450         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1451                                                                  ShAmt);
1452       if (Comp != RHS) {// Comparing against a bit that we know is zero.
1453         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1454         Constant *Cst = Builder->getInt1(IsICMP_NE);
1455         return ReplaceInstUsesWith(ICI, Cst);
1456       }
1457
1458       // If the shift is NUW, then it is just shifting out zeros, no need for an
1459       // AND.
1460       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1461         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1462                             ConstantExpr::getLShr(RHS, ShAmt));
1463
1464       // If the shift is NSW and we compare to 0, then it is just shifting out
1465       // sign bits, no need for an AND either.
1466       if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1467         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1468                             ConstantExpr::getLShr(RHS, ShAmt));
1469
1470       if (LHSI->hasOneUse()) {
1471         // Otherwise strength reduce the shift into an and.
1472         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1473         Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1474                                                           TypeBits - ShAmtVal));
1475
1476         Value *And =
1477           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1478         return new ICmpInst(ICI.getPredicate(), And,
1479                             ConstantExpr::getLShr(RHS, ShAmt));
1480       }
1481     }
1482
1483     // If this is a signed comparison to 0 and the shift is sign preserving,
1484     // use the shift LHS operand instead.
1485     ICmpInst::Predicate pred = ICI.getPredicate();
1486     if (isSignTest(pred, RHS) &&
1487         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1488       return new ICmpInst(pred,
1489                           LHSI->getOperand(0),
1490                           Constant::getNullValue(RHS->getType()));
1491
1492     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1493     bool TrueIfSigned = false;
1494     if (LHSI->hasOneUse() &&
1495         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1496       // (X << 31) <s 0  --> (X&1) != 0
1497       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1498                                         APInt::getOneBitSet(TypeBits,
1499                                             TypeBits-ShAmt->getZExtValue()-1));
1500       Value *And =
1501         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1502       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1503                           And, Constant::getNullValue(And->getType()));
1504     }
1505
1506     // Transform (icmp pred iM (shl iM %v, N), CI)
1507     // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1508     // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1509     // This enables to get rid of the shift in favor of a trunc which can be
1510     // free on the target. It has the additional benefit of comparing to a
1511     // smaller constant, which will be target friendly.
1512     unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1513     if (LHSI->hasOneUse() &&
1514         Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1515       Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1516       Constant *NCI = ConstantExpr::getTrunc(
1517                         ConstantExpr::getAShr(RHS,
1518                           ConstantInt::get(RHS->getType(), Amt)),
1519                         NTy);
1520       return new ICmpInst(ICI.getPredicate(),
1521                           Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1522                           NCI);
1523     }
1524
1525     break;
1526   }
1527
1528   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1529   case Instruction::AShr: {
1530     // Handle equality comparisons of shift-by-constant.
1531     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1532     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1533       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1534         return Res;
1535     }
1536
1537     // Handle exact shr's.
1538     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1539       if (RHSV.isMinValue())
1540         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1541     }
1542     break;
1543   }
1544
1545   case Instruction::SDiv:
1546   case Instruction::UDiv:
1547     // Fold: icmp pred ([us]div X, C1), C2 -> range test
1548     // Fold this div into the comparison, producing a range check.
1549     // Determine, based on the divide type, what the range is being
1550     // checked.  If there is an overflow on the low or high side, remember
1551     // it, otherwise compute the range [low, hi) bounding the new value.
1552     // See: InsertRangeTest above for the kinds of replacements possible.
1553     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1554       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1555                                           DivRHS))
1556         return R;
1557     break;
1558
1559   case Instruction::Sub: {
1560     ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1561     if (!LHSC) break;
1562     const APInt &LHSV = LHSC->getValue();
1563
1564     // C1-X <u C2 -> (X|(C2-1)) == C1
1565     //   iff C1 & (C2-1) == C2-1
1566     //       C2 is a power of 2
1567     if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1568         RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1569       return new ICmpInst(ICmpInst::ICMP_EQ,
1570                           Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1571                           LHSC);
1572
1573     // C1-X >u C2 -> (X|C2) != C1
1574     //   iff C1 & C2 == C2
1575     //       C2+1 is a power of 2
1576     if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1577         (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1578       return new ICmpInst(ICmpInst::ICMP_NE,
1579                           Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1580     break;
1581   }
1582
1583   case Instruction::Add:
1584     // Fold: icmp pred (add X, C1), C2
1585     if (!ICI.isEquality()) {
1586       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1587       if (!LHSC) break;
1588       const APInt &LHSV = LHSC->getValue();
1589
1590       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1591                             .subtract(LHSV);
1592
1593       if (ICI.isSigned()) {
1594         if (CR.getLower().isSignBit()) {
1595           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1596                               Builder->getInt(CR.getUpper()));
1597         } else if (CR.getUpper().isSignBit()) {
1598           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1599                               Builder->getInt(CR.getLower()));
1600         }
1601       } else {
1602         if (CR.getLower().isMinValue()) {
1603           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1604                               Builder->getInt(CR.getUpper()));
1605         } else if (CR.getUpper().isMinValue()) {
1606           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1607                               Builder->getInt(CR.getLower()));
1608         }
1609       }
1610
1611       // X-C1 <u C2 -> (X & -C2) == C1
1612       //   iff C1 & (C2-1) == 0
1613       //       C2 is a power of 2
1614       if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1615           RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
1616         return new ICmpInst(ICmpInst::ICMP_EQ,
1617                             Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1618                             ConstantExpr::getNeg(LHSC));
1619
1620       // X-C1 >u C2 -> (X & ~C2) != C1
1621       //   iff C1 & C2 == 0
1622       //       C2+1 is a power of 2
1623       if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1624           (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1625         return new ICmpInst(ICmpInst::ICMP_NE,
1626                             Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1627                             ConstantExpr::getNeg(LHSC));
1628     }
1629     break;
1630   }
1631
1632   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1633   if (ICI.isEquality()) {
1634     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1635
1636     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1637     // the second operand is a constant, simplify a bit.
1638     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1639       switch (BO->getOpcode()) {
1640       case Instruction::SRem:
1641         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1642         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1643           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1644           if (V.sgt(1) && V.isPowerOf2()) {
1645             Value *NewRem =
1646               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1647                                   BO->getName());
1648             return new ICmpInst(ICI.getPredicate(), NewRem,
1649                                 Constant::getNullValue(BO->getType()));
1650           }
1651         }
1652         break;
1653       case Instruction::Add:
1654         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1655         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1656           if (BO->hasOneUse())
1657             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1658                                 ConstantExpr::getSub(RHS, BOp1C));
1659         } else if (RHSV == 0) {
1660           // Replace ((add A, B) != 0) with (A != -B) if A or B is
1661           // efficiently invertible, or if the add has just this one use.
1662           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1663
1664           if (Value *NegVal = dyn_castNegVal(BOp1))
1665             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1666           if (Value *NegVal = dyn_castNegVal(BOp0))
1667             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1668           if (BO->hasOneUse()) {
1669             Value *Neg = Builder->CreateNeg(BOp1);
1670             Neg->takeName(BO);
1671             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1672           }
1673         }
1674         break;
1675       case Instruction::Xor:
1676         // For the xor case, we can xor two constants together, eliminating
1677         // the explicit xor.
1678         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1679           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1680                               ConstantExpr::getXor(RHS, BOC));
1681         } else if (RHSV == 0) {
1682           // Replace ((xor A, B) != 0) with (A != B)
1683           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1684                               BO->getOperand(1));
1685         }
1686         break;
1687       case Instruction::Sub:
1688         // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1689         if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1690           if (BO->hasOneUse())
1691             return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1692                                 ConstantExpr::getSub(BOp0C, RHS));
1693         } else if (RHSV == 0) {
1694           // Replace ((sub A, B) != 0) with (A != B)
1695           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1696                               BO->getOperand(1));
1697         }
1698         break;
1699       case Instruction::Or:
1700         // If bits are being or'd in that are not present in the constant we
1701         // are comparing against, then the comparison could never succeed!
1702         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1703           Constant *NotCI = ConstantExpr::getNot(RHS);
1704           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1705             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1706         }
1707         break;
1708
1709       case Instruction::And:
1710         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1711           // If bits are being compared against that are and'd out, then the
1712           // comparison can never succeed!
1713           if ((RHSV & ~BOC->getValue()) != 0)
1714             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1715
1716           // If we have ((X & C) == C), turn it into ((X & C) != 0).
1717           if (RHS == BOC && RHSV.isPowerOf2())
1718             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1719                                 ICmpInst::ICMP_NE, LHSI,
1720                                 Constant::getNullValue(RHS->getType()));
1721
1722           // Don't perform the following transforms if the AND has multiple uses
1723           if (!BO->hasOneUse())
1724             break;
1725
1726           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1727           if (BOC->getValue().isSignBit()) {
1728             Value *X = BO->getOperand(0);
1729             Constant *Zero = Constant::getNullValue(X->getType());
1730             ICmpInst::Predicate pred = isICMP_NE ?
1731               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1732             return new ICmpInst(pred, X, Zero);
1733           }
1734
1735           // ((X & ~7) == 0) --> X < 8
1736           if (RHSV == 0 && isHighOnes(BOC)) {
1737             Value *X = BO->getOperand(0);
1738             Constant *NegX = ConstantExpr::getNeg(BOC);
1739             ICmpInst::Predicate pred = isICMP_NE ?
1740               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1741             return new ICmpInst(pred, X, NegX);
1742           }
1743         }
1744         break;
1745       case Instruction::Mul:
1746         if (RHSV == 0 && BO->hasNoSignedWrap()) {
1747           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1748             // The trivial case (mul X, 0) is handled by InstSimplify
1749             // General case : (mul X, C) != 0 iff X != 0
1750             //                (mul X, C) == 0 iff X == 0
1751             if (!BOC->isZero())
1752               return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1753                                   Constant::getNullValue(RHS->getType()));
1754           }
1755         }
1756         break;
1757       default: break;
1758       }
1759     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1760       // Handle icmp {eq|ne} <intrinsic>, intcst.
1761       switch (II->getIntrinsicID()) {
1762       case Intrinsic::bswap:
1763         Worklist.Add(II);
1764         ICI.setOperand(0, II->getArgOperand(0));
1765         ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1766         return &ICI;
1767       case Intrinsic::ctlz:
1768       case Intrinsic::cttz:
1769         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1770         if (RHSV == RHS->getType()->getBitWidth()) {
1771           Worklist.Add(II);
1772           ICI.setOperand(0, II->getArgOperand(0));
1773           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1774           return &ICI;
1775         }
1776         break;
1777       case Intrinsic::ctpop:
1778         // popcount(A) == 0  ->  A == 0 and likewise for !=
1779         if (RHS->isZero()) {
1780           Worklist.Add(II);
1781           ICI.setOperand(0, II->getArgOperand(0));
1782           ICI.setOperand(1, RHS);
1783           return &ICI;
1784         }
1785         break;
1786       default:
1787         break;
1788       }
1789     }
1790   }
1791   return 0;
1792 }
1793
1794 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1795 /// We only handle extending casts so far.
1796 ///
1797 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1798   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1799   Value *LHSCIOp        = LHSCI->getOperand(0);
1800   Type *SrcTy     = LHSCIOp->getType();
1801   Type *DestTy    = LHSCI->getType();
1802   Value *RHSCIOp;
1803
1804   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1805   // integer type is the same size as the pointer type.
1806   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1807       TD->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
1808     Value *RHSOp = 0;
1809     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1810       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1811     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1812       RHSOp = RHSC->getOperand(0);
1813       // If the pointer types don't match, insert a bitcast.
1814       if (LHSCIOp->getType() != RHSOp->getType())
1815         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1816     }
1817
1818     if (RHSOp)
1819       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1820   }
1821
1822   // The code below only handles extension cast instructions, so far.
1823   // Enforce this.
1824   if (LHSCI->getOpcode() != Instruction::ZExt &&
1825       LHSCI->getOpcode() != Instruction::SExt)
1826     return 0;
1827
1828   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1829   bool isSignedCmp = ICI.isSigned();
1830
1831   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1832     // Not an extension from the same type?
1833     RHSCIOp = CI->getOperand(0);
1834     if (RHSCIOp->getType() != LHSCIOp->getType())
1835       return 0;
1836
1837     // If the signedness of the two casts doesn't agree (i.e. one is a sext
1838     // and the other is a zext), then we can't handle this.
1839     if (CI->getOpcode() != LHSCI->getOpcode())
1840       return 0;
1841
1842     // Deal with equality cases early.
1843     if (ICI.isEquality())
1844       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1845
1846     // A signed comparison of sign extended values simplifies into a
1847     // signed comparison.
1848     if (isSignedCmp && isSignedExt)
1849       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1850
1851     // The other three cases all fold into an unsigned comparison.
1852     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1853   }
1854
1855   // If we aren't dealing with a constant on the RHS, exit early
1856   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1857   if (!CI)
1858     return 0;
1859
1860   // Compute the constant that would happen if we truncated to SrcTy then
1861   // reextended to DestTy.
1862   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1863   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1864                                                 Res1, DestTy);
1865
1866   // If the re-extended constant didn't change...
1867   if (Res2 == CI) {
1868     // Deal with equality cases early.
1869     if (ICI.isEquality())
1870       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1871
1872     // A signed comparison of sign extended values simplifies into a
1873     // signed comparison.
1874     if (isSignedExt && isSignedCmp)
1875       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1876
1877     // The other three cases all fold into an unsigned comparison.
1878     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1879   }
1880
1881   // The re-extended constant changed so the constant cannot be represented
1882   // in the shorter type. Consequently, we cannot emit a simple comparison.
1883   // All the cases that fold to true or false will have already been handled
1884   // by SimplifyICmpInst, so only deal with the tricky case.
1885
1886   if (isSignedCmp || !isSignedExt)
1887     return 0;
1888
1889   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1890   // should have been folded away previously and not enter in here.
1891
1892   // We're performing an unsigned comp with a sign extended value.
1893   // This is true if the input is >= 0. [aka >s -1]
1894   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1895   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1896
1897   // Finally, return the value computed.
1898   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1899     return ReplaceInstUsesWith(ICI, Result);
1900
1901   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1902   return BinaryOperator::CreateNot(Result);
1903 }
1904
1905 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1906 ///   I = icmp ugt (add (add A, B), CI2), CI1
1907 /// If this is of the form:
1908 ///   sum = a + b
1909 ///   if (sum+128 >u 255)
1910 /// Then replace it with llvm.sadd.with.overflow.i8.
1911 ///
1912 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1913                                           ConstantInt *CI2, ConstantInt *CI1,
1914                                           InstCombiner &IC) {
1915   // The transformation we're trying to do here is to transform this into an
1916   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1917   // with a narrower add, and discard the add-with-constant that is part of the
1918   // range check (if we can't eliminate it, this isn't profitable).
1919
1920   // In order to eliminate the add-with-constant, the compare can be its only
1921   // use.
1922   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1923   if (!AddWithCst->hasOneUse()) return 0;
1924
1925   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1926   if (!CI2->getValue().isPowerOf2()) return 0;
1927   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1928   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1929
1930   // The width of the new add formed is 1 more than the bias.
1931   ++NewWidth;
1932
1933   // Check to see that CI1 is an all-ones value with NewWidth bits.
1934   if (CI1->getBitWidth() == NewWidth ||
1935       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1936     return 0;
1937
1938   // This is only really a signed overflow check if the inputs have been
1939   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1940   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1941   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1942   if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1943       IC.ComputeNumSignBits(B) < NeededSignBits)
1944     return 0;
1945
1946   // In order to replace the original add with a narrower
1947   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1948   // and truncates that discard the high bits of the add.  Verify that this is
1949   // the case.
1950   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1951   for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1952        UI != E; ++UI) {
1953     if (*UI == AddWithCst) continue;
1954
1955     // Only accept truncates for now.  We would really like a nice recursive
1956     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1957     // chain to see which bits of a value are actually demanded.  If the
1958     // original add had another add which was then immediately truncated, we
1959     // could still do the transformation.
1960     TruncInst *TI = dyn_cast<TruncInst>(*UI);
1961     if (TI == 0 ||
1962         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1963   }
1964
1965   // If the pattern matches, truncate the inputs to the narrower type and
1966   // use the sadd_with_overflow intrinsic to efficiently compute both the
1967   // result and the overflow bit.
1968   Module *M = I.getParent()->getParent()->getParent();
1969
1970   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1971   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1972                                        NewType);
1973
1974   InstCombiner::BuilderTy *Builder = IC.Builder;
1975
1976   // Put the new code above the original add, in case there are any uses of the
1977   // add between the add and the compare.
1978   Builder->SetInsertPoint(OrigAdd);
1979
1980   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1981   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1982   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1983   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1984   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1985
1986   // The inner add was the result of the narrow add, zero extended to the
1987   // wider type.  Replace it with the result computed by the intrinsic.
1988   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1989
1990   // The original icmp gets replaced with the overflow value.
1991   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1992 }
1993
1994 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1995                                      InstCombiner &IC) {
1996   // Don't bother doing this transformation for pointers, don't do it for
1997   // vectors.
1998   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1999
2000   // If the add is a constant expr, then we don't bother transforming it.
2001   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
2002   if (OrigAdd == 0) return 0;
2003
2004   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
2005
2006   // Put the new code above the original add, in case there are any uses of the
2007   // add between the add and the compare.
2008   InstCombiner::BuilderTy *Builder = IC.Builder;
2009   Builder->SetInsertPoint(OrigAdd);
2010
2011   Module *M = I.getParent()->getParent()->getParent();
2012   Type *Ty = LHS->getType();
2013   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
2014   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2015   Value *Add = Builder->CreateExtractValue(Call, 0);
2016
2017   IC.ReplaceInstUsesWith(*OrigAdd, Add);
2018
2019   // The original icmp gets replaced with the overflow value.
2020   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2021 }
2022
2023 // DemandedBitsLHSMask - When performing a comparison against a constant,
2024 // it is possible that not all the bits in the LHS are demanded.  This helper
2025 // method computes the mask that IS demanded.
2026 static APInt DemandedBitsLHSMask(ICmpInst &I,
2027                                  unsigned BitWidth, bool isSignCheck) {
2028   if (isSignCheck)
2029     return APInt::getSignBit(BitWidth);
2030
2031   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2032   if (!CI) return APInt::getAllOnesValue(BitWidth);
2033   const APInt &RHS = CI->getValue();
2034
2035   switch (I.getPredicate()) {
2036   // For a UGT comparison, we don't care about any bits that
2037   // correspond to the trailing ones of the comparand.  The value of these
2038   // bits doesn't impact the outcome of the comparison, because any value
2039   // greater than the RHS must differ in a bit higher than these due to carry.
2040   case ICmpInst::ICMP_UGT: {
2041     unsigned trailingOnes = RHS.countTrailingOnes();
2042     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2043     return ~lowBitsSet;
2044   }
2045
2046   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2047   // Any value less than the RHS must differ in a higher bit because of carries.
2048   case ICmpInst::ICMP_ULT: {
2049     unsigned trailingZeros = RHS.countTrailingZeros();
2050     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2051     return ~lowBitsSet;
2052   }
2053
2054   default:
2055     return APInt::getAllOnesValue(BitWidth);
2056   }
2057
2058 }
2059
2060 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2061 /// should be swapped.
2062 /// The descision is based on how many times these two operands are reused
2063 /// as subtract operands and their positions in those instructions.
2064 /// The rational is that several architectures use the same instruction for
2065 /// both subtract and cmp, thus it is better if the order of those operands
2066 /// match.
2067 /// \return true if Op0 and Op1 should be swapped.
2068 static bool swapMayExposeCSEOpportunities(const Value * Op0,
2069                                           const Value * Op1) {
2070   // Filter out pointer value as those cannot appears directly in subtract.
2071   // FIXME: we may want to go through inttoptrs or bitcasts.
2072   if (Op0->getType()->isPointerTy())
2073     return false;
2074   // Count every uses of both Op0 and Op1 in a subtract.
2075   // Each time Op0 is the first operand, count -1: swapping is bad, the
2076   // subtract has already the same layout as the compare.
2077   // Each time Op0 is the second operand, count +1: swapping is good, the
2078   // subtract has a diffrent layout as the compare.
2079   // At the end, if the benefit is greater than 0, Op0 should come second to
2080   // expose more CSE opportunities.
2081   int GlobalSwapBenefits = 0;
2082   for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2083     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2084     if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2085       continue;
2086     // If Op0 is the first argument, this is not beneficial to swap the
2087     // arguments.
2088     int LocalSwapBenefits = -1;
2089     unsigned Op1Idx = 1;
2090     if (BinOp->getOperand(Op1Idx) == Op0) {
2091       Op1Idx = 0;
2092       LocalSwapBenefits = 1;
2093     }
2094     if (BinOp->getOperand(Op1Idx) != Op1)
2095       continue;
2096     GlobalSwapBenefits += LocalSwapBenefits;
2097   }
2098   return GlobalSwapBenefits > 0;
2099 }
2100
2101 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2102   bool Changed = false;
2103   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2104   unsigned Op0Cplxity = getComplexity(Op0);
2105   unsigned Op1Cplxity = getComplexity(Op1);
2106
2107   /// Orders the operands of the compare so that they are listed from most
2108   /// complex to least complex.  This puts constants before unary operators,
2109   /// before binary operators.
2110   if (Op0Cplxity < Op1Cplxity ||
2111         (Op0Cplxity == Op1Cplxity &&
2112          swapMayExposeCSEOpportunities(Op0, Op1))) {
2113     I.swapOperands();
2114     std::swap(Op0, Op1);
2115     Changed = true;
2116   }
2117
2118   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2119     return ReplaceInstUsesWith(I, V);
2120
2121   // comparing -val or val with non-zero is the same as just comparing val
2122   // ie, abs(val) != 0 -> val != 0
2123   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2124   {
2125     Value *Cond, *SelectTrue, *SelectFalse;
2126     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
2127                             m_Value(SelectFalse)))) {
2128       if (Value *V = dyn_castNegVal(SelectTrue)) {
2129         if (V == SelectFalse)
2130           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2131       }
2132       else if (Value *V = dyn_castNegVal(SelectFalse)) {
2133         if (V == SelectTrue)
2134           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2135       }
2136     }
2137   }
2138
2139   Type *Ty = Op0->getType();
2140
2141   // icmp's with boolean values can always be turned into bitwise operations
2142   if (Ty->isIntegerTy(1)) {
2143     switch (I.getPredicate()) {
2144     default: llvm_unreachable("Invalid icmp instruction!");
2145     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
2146       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2147       return BinaryOperator::CreateNot(Xor);
2148     }
2149     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
2150       return BinaryOperator::CreateXor(Op0, Op1);
2151
2152     case ICmpInst::ICMP_UGT:
2153       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
2154       // FALL THROUGH
2155     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
2156       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2157       return BinaryOperator::CreateAnd(Not, Op1);
2158     }
2159     case ICmpInst::ICMP_SGT:
2160       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
2161       // FALL THROUGH
2162     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
2163       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2164       return BinaryOperator::CreateAnd(Not, Op0);
2165     }
2166     case ICmpInst::ICMP_UGE:
2167       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
2168       // FALL THROUGH
2169     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
2170       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2171       return BinaryOperator::CreateOr(Not, Op1);
2172     }
2173     case ICmpInst::ICMP_SGE:
2174       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
2175       // FALL THROUGH
2176     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
2177       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2178       return BinaryOperator::CreateOr(Not, Op0);
2179     }
2180     }
2181   }
2182
2183   unsigned BitWidth = 0;
2184   if (Ty->isIntOrIntVectorTy())
2185     BitWidth = Ty->getScalarSizeInBits();
2186   else if (TD)  // Pointers require TD info to get their size.
2187     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
2188
2189   bool isSignBit = false;
2190
2191   // See if we are doing a comparison with a constant.
2192   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2193     Value *A = 0, *B = 0;
2194
2195     // Match the following pattern, which is a common idiom when writing
2196     // overflow-safe integer arithmetic function.  The source performs an
2197     // addition in wider type, and explicitly checks for overflow using
2198     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
2199     // sadd_with_overflow intrinsic.
2200     //
2201     // TODO: This could probably be generalized to handle other overflow-safe
2202     // operations if we worked out the formulas to compute the appropriate
2203     // magic constants.
2204     //
2205     // sum = a + b
2206     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
2207     {
2208     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
2209     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2210         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2211       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2212         return Res;
2213     }
2214
2215     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2216     if (I.isEquality() && CI->isZero() &&
2217         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2218       // (icmp cond A B) if cond is equality
2219       return new ICmpInst(I.getPredicate(), A, B);
2220     }
2221
2222     // If we have an icmp le or icmp ge instruction, turn it into the
2223     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
2224     // them being folded in the code below.  The SimplifyICmpInst code has
2225     // already handled the edge cases for us, so we just assert on them.
2226     switch (I.getPredicate()) {
2227     default: break;
2228     case ICmpInst::ICMP_ULE:
2229       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
2230       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2231                           Builder->getInt(CI->getValue()+1));
2232     case ICmpInst::ICMP_SLE:
2233       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
2234       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2235                           Builder->getInt(CI->getValue()+1));
2236     case ICmpInst::ICMP_UGE:
2237       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
2238       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2239                           Builder->getInt(CI->getValue()-1));
2240     case ICmpInst::ICMP_SGE:
2241       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
2242       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2243                           Builder->getInt(CI->getValue()-1));
2244     }
2245
2246     // If this comparison is a normal comparison, it demands all
2247     // bits, if it is a sign bit comparison, it only demands the sign bit.
2248     bool UnusedBit;
2249     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2250   }
2251
2252   // See if we can fold the comparison based on range information we can get
2253   // by checking whether bits are known to be zero or one in the input.
2254   if (BitWidth != 0) {
2255     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2256     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2257
2258     if (SimplifyDemandedBits(I.getOperandUse(0),
2259                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
2260                              Op0KnownZero, Op0KnownOne, 0))
2261       return &I;
2262     if (SimplifyDemandedBits(I.getOperandUse(1),
2263                              APInt::getAllOnesValue(BitWidth),
2264                              Op1KnownZero, Op1KnownOne, 0))
2265       return &I;
2266
2267     // Given the known and unknown bits, compute a range that the LHS could be
2268     // in.  Compute the Min, Max and RHS values based on the known bits. For the
2269     // EQ and NE we use unsigned values.
2270     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2271     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2272     if (I.isSigned()) {
2273       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2274                                              Op0Min, Op0Max);
2275       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2276                                              Op1Min, Op1Max);
2277     } else {
2278       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2279                                                Op0Min, Op0Max);
2280       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2281                                                Op1Min, Op1Max);
2282     }
2283
2284     // If Min and Max are known to be the same, then SimplifyDemandedBits
2285     // figured out that the LHS is a constant.  Just constant fold this now so
2286     // that code below can assume that Min != Max.
2287     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2288       return new ICmpInst(I.getPredicate(),
2289                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
2290     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2291       return new ICmpInst(I.getPredicate(), Op0,
2292                           ConstantInt::get(Op1->getType(), Op1Min));
2293
2294     // Based on the range information we know about the LHS, see if we can
2295     // simplify this comparison.  For example, (x&4) < 8 is always true.
2296     switch (I.getPredicate()) {
2297     default: llvm_unreachable("Unknown icmp opcode!");
2298     case ICmpInst::ICMP_EQ: {
2299       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2300         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2301
2302       // If all bits are known zero except for one, then we know at most one
2303       // bit is set.   If the comparison is against zero, then this is a check
2304       // to see if *that* bit is set.
2305       APInt Op0KnownZeroInverted = ~Op0KnownZero;
2306       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2307         // If the LHS is an AND with the same constant, look through it.
2308         Value *LHS = 0;
2309         ConstantInt *LHSC = 0;
2310         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2311             LHSC->getValue() != Op0KnownZeroInverted)
2312           LHS = Op0;
2313
2314         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2315         // then turn "((1 << x)&8) == 0" into "x != 3".
2316         Value *X = 0;
2317         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2318           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2319           return new ICmpInst(ICmpInst::ICMP_NE, X,
2320                               ConstantInt::get(X->getType(), CmpVal));
2321         }
2322
2323         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2324         // then turn "((8 >>u x)&1) == 0" into "x != 3".
2325         const APInt *CI;
2326         if (Op0KnownZeroInverted == 1 &&
2327             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2328           return new ICmpInst(ICmpInst::ICMP_NE, X,
2329                               ConstantInt::get(X->getType(),
2330                                                CI->countTrailingZeros()));
2331       }
2332
2333       break;
2334     }
2335     case ICmpInst::ICMP_NE: {
2336       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2337         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2338
2339       // If all bits are known zero except for one, then we know at most one
2340       // bit is set.   If the comparison is against zero, then this is a check
2341       // to see if *that* bit is set.
2342       APInt Op0KnownZeroInverted = ~Op0KnownZero;
2343       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2344         // If the LHS is an AND with the same constant, look through it.
2345         Value *LHS = 0;
2346         ConstantInt *LHSC = 0;
2347         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2348             LHSC->getValue() != Op0KnownZeroInverted)
2349           LHS = Op0;
2350
2351         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2352         // then turn "((1 << x)&8) != 0" into "x == 3".
2353         Value *X = 0;
2354         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2355           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2356           return new ICmpInst(ICmpInst::ICMP_EQ, X,
2357                               ConstantInt::get(X->getType(), CmpVal));
2358         }
2359
2360         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2361         // then turn "((8 >>u x)&1) != 0" into "x == 3".
2362         const APInt *CI;
2363         if (Op0KnownZeroInverted == 1 &&
2364             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2365           return new ICmpInst(ICmpInst::ICMP_EQ, X,
2366                               ConstantInt::get(X->getType(),
2367                                                CI->countTrailingZeros()));
2368       }
2369
2370       break;
2371     }
2372     case ICmpInst::ICMP_ULT:
2373       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2374         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2375       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2376         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2377       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2378         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2379       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2380         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2381           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2382                               Builder->getInt(CI->getValue()-1));
2383
2384         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2385         if (CI->isMinValue(true))
2386           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2387                            Constant::getAllOnesValue(Op0->getType()));
2388       }
2389       break;
2390     case ICmpInst::ICMP_UGT:
2391       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2392         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2393       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2394         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2395
2396       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2397         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2398       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2399         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2400           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2401                               Builder->getInt(CI->getValue()+1));
2402
2403         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2404         if (CI->isMaxValue(true))
2405           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2406                               Constant::getNullValue(Op0->getType()));
2407       }
2408       break;
2409     case ICmpInst::ICMP_SLT:
2410       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2411         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2412       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2413         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2414       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2415         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2416       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2417         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2418           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2419                               Builder->getInt(CI->getValue()-1));
2420       }
2421       break;
2422     case ICmpInst::ICMP_SGT:
2423       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2424         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2425       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2426         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2427
2428       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2429         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2430       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2431         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2432           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2433                               Builder->getInt(CI->getValue()+1));
2434       }
2435       break;
2436     case ICmpInst::ICMP_SGE:
2437       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2438       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2439         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2440       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2441         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2442       break;
2443     case ICmpInst::ICMP_SLE:
2444       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2445       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2446         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2447       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2448         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2449       break;
2450     case ICmpInst::ICMP_UGE:
2451       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2452       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2453         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2454       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2455         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2456       break;
2457     case ICmpInst::ICMP_ULE:
2458       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2459       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2460         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2461       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2462         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2463       break;
2464     }
2465
2466     // Turn a signed comparison into an unsigned one if both operands
2467     // are known to have the same sign.
2468     if (I.isSigned() &&
2469         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2470          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2471       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2472   }
2473
2474   // Test if the ICmpInst instruction is used exclusively by a select as
2475   // part of a minimum or maximum operation. If so, refrain from doing
2476   // any other folding. This helps out other analyses which understand
2477   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2478   // and CodeGen. And in this case, at least one of the comparison
2479   // operands has at least one user besides the compare (the select),
2480   // which would often largely negate the benefit of folding anyway.
2481   if (I.hasOneUse())
2482     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2483       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2484           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2485         return 0;
2486
2487   // See if we are doing a comparison between a constant and an instruction that
2488   // can be folded into the comparison.
2489   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2490     // Since the RHS is a ConstantInt (CI), if the left hand side is an
2491     // instruction, see if that instruction also has constants so that the
2492     // instruction can be folded into the icmp
2493     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2494       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2495         return Res;
2496   }
2497
2498   // Handle icmp with constant (but not simple integer constant) RHS
2499   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2500     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2501       switch (LHSI->getOpcode()) {
2502       case Instruction::GetElementPtr:
2503           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2504         if (RHSC->isNullValue() &&
2505             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2506           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2507                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
2508         break;
2509       case Instruction::PHI:
2510         // Only fold icmp into the PHI if the phi and icmp are in the same
2511         // block.  If in the same block, we're encouraging jump threading.  If
2512         // not, we are just pessimizing the code by making an i1 phi.
2513         if (LHSI->getParent() == I.getParent())
2514           if (Instruction *NV = FoldOpIntoPhi(I))
2515             return NV;
2516         break;
2517       case Instruction::Select: {
2518         // If either operand of the select is a constant, we can fold the
2519         // comparison into the select arms, which will cause one to be
2520         // constant folded and the select turned into a bitwise or.
2521         Value *Op1 = 0, *Op2 = 0;
2522         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2523           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2524         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2525           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2526
2527         // We only want to perform this transformation if it will not lead to
2528         // additional code. This is true if either both sides of the select
2529         // fold to a constant (in which case the icmp is replaced with a select
2530         // which will usually simplify) or this is the only user of the
2531         // select (in which case we are trading a select+icmp for a simpler
2532         // select+icmp).
2533         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2534           if (!Op1)
2535             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2536                                       RHSC, I.getName());
2537           if (!Op2)
2538             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2539                                       RHSC, I.getName());
2540           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2541         }
2542         break;
2543       }
2544       case Instruction::IntToPtr:
2545         // icmp pred inttoptr(X), null -> icmp pred X, 0
2546         if (RHSC->isNullValue() && TD &&
2547             TD->getIntPtrType(RHSC->getType()) ==
2548                LHSI->getOperand(0)->getType())
2549           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2550                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
2551         break;
2552
2553       case Instruction::Load:
2554         // Try to optimize things like "A[i] > 4" to index computations.
2555         if (GetElementPtrInst *GEP =
2556               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2557           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2558             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2559                 !cast<LoadInst>(LHSI)->isVolatile())
2560               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2561                 return Res;
2562         }
2563         break;
2564       }
2565   }
2566
2567   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2568   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2569     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2570       return NI;
2571   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2572     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2573                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2574       return NI;
2575
2576   // Test to see if the operands of the icmp are casted versions of other
2577   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2578   // now.
2579   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2580     if (Op0->getType()->isPointerTy() &&
2581         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2582       // We keep moving the cast from the left operand over to the right
2583       // operand, where it can often be eliminated completely.
2584       Op0 = CI->getOperand(0);
2585
2586       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2587       // so eliminate it as well.
2588       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2589         Op1 = CI2->getOperand(0);
2590
2591       // If Op1 is a constant, we can fold the cast into the constant.
2592       if (Op0->getType() != Op1->getType()) {
2593         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2594           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2595         } else {
2596           // Otherwise, cast the RHS right before the icmp
2597           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2598         }
2599       }
2600       return new ICmpInst(I.getPredicate(), Op0, Op1);
2601     }
2602   }
2603
2604   if (isa<CastInst>(Op0)) {
2605     // Handle the special case of: icmp (cast bool to X), <cst>
2606     // This comes up when you have code like
2607     //   int X = A < B;
2608     //   if (X) ...
2609     // For generality, we handle any zero-extension of any operand comparison
2610     // with a constant or another cast from the same type.
2611     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2612       if (Instruction *R = visitICmpInstWithCastAndCast(I))
2613         return R;
2614   }
2615
2616   // Special logic for binary operators.
2617   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2618   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2619   if (BO0 || BO1) {
2620     CmpInst::Predicate Pred = I.getPredicate();
2621     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2622     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2623       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2624         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2625         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2626     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2627       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2628         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2629         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2630
2631     // Analyze the case when either Op0 or Op1 is an add instruction.
2632     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2633     Value *A = 0, *B = 0, *C = 0, *D = 0;
2634     if (BO0 && BO0->getOpcode() == Instruction::Add)
2635       A = BO0->getOperand(0), B = BO0->getOperand(1);
2636     if (BO1 && BO1->getOpcode() == Instruction::Add)
2637       C = BO1->getOperand(0), D = BO1->getOperand(1);
2638
2639     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2640     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2641       return new ICmpInst(Pred, A == Op1 ? B : A,
2642                           Constant::getNullValue(Op1->getType()));
2643
2644     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2645     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2646       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2647                           C == Op0 ? D : C);
2648
2649     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2650     if (A && C && (A == C || A == D || B == C || B == D) &&
2651         NoOp0WrapProblem && NoOp1WrapProblem &&
2652         // Try not to increase register pressure.
2653         BO0->hasOneUse() && BO1->hasOneUse()) {
2654       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2655       Value *Y, *Z;
2656       if (A == C) {
2657         // C + B == C + D  ->  B == D
2658         Y = B;
2659         Z = D;
2660       } else if (A == D) {
2661         // D + B == C + D  ->  B == C
2662         Y = B;
2663         Z = C;
2664       } else if (B == C) {
2665         // A + C == C + D  ->  A == D
2666         Y = A;
2667         Z = D;
2668       } else {
2669         assert(B == D);
2670         // A + D == C + D  ->  A == C
2671         Y = A;
2672         Z = C;
2673       }
2674       return new ICmpInst(Pred, Y, Z);
2675     }
2676
2677     // icmp slt (X + -1), Y -> icmp sle X, Y
2678     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2679         match(B, m_AllOnes()))
2680       return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2681
2682     // icmp sge (X + -1), Y -> icmp sgt X, Y
2683     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2684         match(B, m_AllOnes()))
2685       return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2686
2687     // icmp sle (X + 1), Y -> icmp slt X, Y
2688     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2689         match(B, m_One()))
2690       return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2691
2692     // icmp sgt (X + 1), Y -> icmp sge X, Y
2693     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2694         match(B, m_One()))
2695       return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2696
2697     // if C1 has greater magnitude than C2:
2698     //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2699     //  s.t. C3 = C1 - C2
2700     //
2701     // if C2 has greater magnitude than C1:
2702     //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2703     //  s.t. C3 = C2 - C1
2704     if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2705         (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2706       if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2707         if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2708           const APInt &AP1 = C1->getValue();
2709           const APInt &AP2 = C2->getValue();
2710           if (AP1.isNegative() == AP2.isNegative()) {
2711             APInt AP1Abs = C1->getValue().abs();
2712             APInt AP2Abs = C2->getValue().abs();
2713             if (AP1Abs.uge(AP2Abs)) {
2714               ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2715               Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2716               return new ICmpInst(Pred, NewAdd, C);
2717             } else {
2718               ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2719               Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2720               return new ICmpInst(Pred, A, NewAdd);
2721             }
2722           }
2723         }
2724
2725
2726     // Analyze the case when either Op0 or Op1 is a sub instruction.
2727     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2728     A = 0; B = 0; C = 0; D = 0;
2729     if (BO0 && BO0->getOpcode() == Instruction::Sub)
2730       A = BO0->getOperand(0), B = BO0->getOperand(1);
2731     if (BO1 && BO1->getOpcode() == Instruction::Sub)
2732       C = BO1->getOperand(0), D = BO1->getOperand(1);
2733
2734     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2735     if (A == Op1 && NoOp0WrapProblem)
2736       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2737
2738     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2739     if (C == Op0 && NoOp1WrapProblem)
2740       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2741
2742     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2743     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2744         // Try not to increase register pressure.
2745         BO0->hasOneUse() && BO1->hasOneUse())
2746       return new ICmpInst(Pred, A, C);
2747
2748     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2749     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2750         // Try not to increase register pressure.
2751         BO0->hasOneUse() && BO1->hasOneUse())
2752       return new ICmpInst(Pred, D, B);
2753
2754     BinaryOperator *SRem = NULL;
2755     // icmp (srem X, Y), Y
2756     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2757         Op1 == BO0->getOperand(1))
2758       SRem = BO0;
2759     // icmp Y, (srem X, Y)
2760     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2761              Op0 == BO1->getOperand(1))
2762       SRem = BO1;
2763     if (SRem) {
2764       // We don't check hasOneUse to avoid increasing register pressure because
2765       // the value we use is the same value this instruction was already using.
2766       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2767         default: break;
2768         case ICmpInst::ICMP_EQ:
2769           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2770         case ICmpInst::ICMP_NE:
2771           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2772         case ICmpInst::ICMP_SGT:
2773         case ICmpInst::ICMP_SGE:
2774           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2775                               Constant::getAllOnesValue(SRem->getType()));
2776         case ICmpInst::ICMP_SLT:
2777         case ICmpInst::ICMP_SLE:
2778           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2779                               Constant::getNullValue(SRem->getType()));
2780       }
2781     }
2782
2783     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2784         BO0->hasOneUse() && BO1->hasOneUse() &&
2785         BO0->getOperand(1) == BO1->getOperand(1)) {
2786       switch (BO0->getOpcode()) {
2787       default: break;
2788       case Instruction::Add:
2789       case Instruction::Sub:
2790       case Instruction::Xor:
2791         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2792           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2793                               BO1->getOperand(0));
2794         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2795         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2796           if (CI->getValue().isSignBit()) {
2797             ICmpInst::Predicate Pred = I.isSigned()
2798                                            ? I.getUnsignedPredicate()
2799                                            : I.getSignedPredicate();
2800             return new ICmpInst(Pred, BO0->getOperand(0),
2801                                 BO1->getOperand(0));
2802           }
2803
2804           if (CI->isMaxValue(true)) {
2805             ICmpInst::Predicate Pred = I.isSigned()
2806                                            ? I.getUnsignedPredicate()
2807                                            : I.getSignedPredicate();
2808             Pred = I.getSwappedPredicate(Pred);
2809             return new ICmpInst(Pred, BO0->getOperand(0),
2810                                 BO1->getOperand(0));
2811           }
2812         }
2813         break;
2814       case Instruction::Mul:
2815         if (!I.isEquality())
2816           break;
2817
2818         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2819           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2820           // Mask = -1 >> count-trailing-zeros(Cst).
2821           if (!CI->isZero() && !CI->isOne()) {
2822             const APInt &AP = CI->getValue();
2823             ConstantInt *Mask = ConstantInt::get(I.getContext(),
2824                                     APInt::getLowBitsSet(AP.getBitWidth(),
2825                                                          AP.getBitWidth() -
2826                                                     AP.countTrailingZeros()));
2827             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2828             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2829             return new ICmpInst(I.getPredicate(), And1, And2);
2830           }
2831         }
2832         break;
2833       case Instruction::UDiv:
2834       case Instruction::LShr:
2835         if (I.isSigned())
2836           break;
2837         // fall-through
2838       case Instruction::SDiv:
2839       case Instruction::AShr:
2840         if (!BO0->isExact() || !BO1->isExact())
2841           break;
2842         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2843                             BO1->getOperand(0));
2844       case Instruction::Shl: {
2845         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2846         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2847         if (!NUW && !NSW)
2848           break;
2849         if (!NSW && I.isSigned())
2850           break;
2851         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2852                             BO1->getOperand(0));
2853       }
2854       }
2855     }
2856   }
2857
2858   { Value *A, *B;
2859     // Transform (A & ~B) == 0 --> (A & B) != 0
2860     // and       (A & ~B) != 0 --> (A & B) == 0
2861     // if A is a power of 2.
2862     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2863         match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2864       return new ICmpInst(I.getInversePredicate(),
2865                           Builder->CreateAnd(A, B),
2866                           Op1);
2867
2868     // ~x < ~y --> y < x
2869     // ~x < cst --> ~cst < x
2870     if (match(Op0, m_Not(m_Value(A)))) {
2871       if (match(Op1, m_Not(m_Value(B))))
2872         return new ICmpInst(I.getPredicate(), B, A);
2873       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2874         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2875     }
2876
2877     // (a+b) <u a  --> llvm.uadd.with.overflow.
2878     // (a+b) <u b  --> llvm.uadd.with.overflow.
2879     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2880         match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2881         (Op1 == A || Op1 == B))
2882       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2883         return R;
2884
2885     // a >u (a+b)  --> llvm.uadd.with.overflow.
2886     // b >u (a+b)  --> llvm.uadd.with.overflow.
2887     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2888         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2889         (Op0 == A || Op0 == B))
2890       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2891         return R;
2892   }
2893
2894   if (I.isEquality()) {
2895     Value *A, *B, *C, *D;
2896
2897     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2898       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2899         Value *OtherVal = A == Op1 ? B : A;
2900         return new ICmpInst(I.getPredicate(), OtherVal,
2901                             Constant::getNullValue(A->getType()));
2902       }
2903
2904       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2905         // A^c1 == C^c2 --> A == C^(c1^c2)
2906         ConstantInt *C1, *C2;
2907         if (match(B, m_ConstantInt(C1)) &&
2908             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2909           Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
2910           Value *Xor = Builder->CreateXor(C, NC);
2911           return new ICmpInst(I.getPredicate(), A, Xor);
2912         }
2913
2914         // A^B == A^D -> B == D
2915         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2916         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2917         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2918         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2919       }
2920     }
2921
2922     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2923         (A == Op0 || B == Op0)) {
2924       // A == (A^B)  ->  B == 0
2925       Value *OtherVal = A == Op0 ? B : A;
2926       return new ICmpInst(I.getPredicate(), OtherVal,
2927                           Constant::getNullValue(A->getType()));
2928     }
2929
2930     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2931     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2932         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2933       Value *X = 0, *Y = 0, *Z = 0;
2934
2935       if (A == C) {
2936         X = B; Y = D; Z = A;
2937       } else if (A == D) {
2938         X = B; Y = C; Z = A;
2939       } else if (B == C) {
2940         X = A; Y = D; Z = B;
2941       } else if (B == D) {
2942         X = A; Y = C; Z = B;
2943       }
2944
2945       if (X) {   // Build (X^Y) & Z
2946         Op1 = Builder->CreateXor(X, Y);
2947         Op1 = Builder->CreateAnd(Op1, Z);
2948         I.setOperand(0, Op1);
2949         I.setOperand(1, Constant::getNullValue(Op1->getType()));
2950         return &I;
2951       }
2952     }
2953
2954     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2955     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2956     ConstantInt *Cst1;
2957     if ((Op0->hasOneUse() &&
2958          match(Op0, m_ZExt(m_Value(A))) &&
2959          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2960         (Op1->hasOneUse() &&
2961          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2962          match(Op1, m_ZExt(m_Value(A))))) {
2963       APInt Pow2 = Cst1->getValue() + 1;
2964       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2965           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2966         return new ICmpInst(I.getPredicate(), A,
2967                             Builder->CreateTrunc(B, A->getType()));
2968     }
2969
2970     // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2971     // For lshr and ashr pairs.
2972     if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2973          match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2974         (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2975          match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2976       unsigned TypeBits = Cst1->getBitWidth();
2977       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2978       if (ShAmt < TypeBits && ShAmt != 0) {
2979         ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2980                                        ? ICmpInst::ICMP_UGE
2981                                        : ICmpInst::ICMP_ULT;
2982         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2983         APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2984         return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2985       }
2986     }
2987
2988     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2989     // "icmp (and X, mask), cst"
2990     uint64_t ShAmt = 0;
2991     if (Op0->hasOneUse() &&
2992         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2993                                            m_ConstantInt(ShAmt))))) &&
2994         match(Op1, m_ConstantInt(Cst1)) &&
2995         // Only do this when A has multiple uses.  This is most important to do
2996         // when it exposes other optimizations.
2997         !A->hasOneUse()) {
2998       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2999
3000       if (ShAmt < ASize) {
3001         APInt MaskV =
3002           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3003         MaskV <<= ShAmt;
3004
3005         APInt CmpV = Cst1->getValue().zext(ASize);
3006         CmpV <<= ShAmt;
3007
3008         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3009         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3010       }
3011     }
3012   }
3013
3014   {
3015     Value *X; ConstantInt *Cst;
3016     // icmp X+Cst, X
3017     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
3018       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
3019
3020     // icmp X, X+Cst
3021     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
3022       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
3023   }
3024   return Changed ? &I : 0;
3025 }
3026
3027 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3028 ///
3029 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3030                                                 Instruction *LHSI,
3031                                                 Constant *RHSC) {
3032   if (!isa<ConstantFP>(RHSC)) return 0;
3033   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
3034
3035   // Get the width of the mantissa.  We don't want to hack on conversions that
3036   // might lose information from the integer, e.g. "i64 -> float"
3037   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3038   if (MantissaWidth == -1) return 0;  // Unknown.
3039
3040   // Check to see that the input is converted from an integer type that is small
3041   // enough that preserves all bits.  TODO: check here for "known" sign bits.
3042   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3043   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
3044
3045   // If this is a uitofp instruction, we need an extra bit to hold the sign.
3046   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3047   if (LHSUnsigned)
3048     ++InputSize;
3049
3050   // If the conversion would lose info, don't hack on this.
3051   if ((int)InputSize > MantissaWidth)
3052     return 0;
3053
3054   // Otherwise, we can potentially simplify the comparison.  We know that it
3055   // will always come through as an integer value and we know the constant is
3056   // not a NAN (it would have been previously simplified).
3057   assert(!RHS.isNaN() && "NaN comparison not already folded!");
3058
3059   ICmpInst::Predicate Pred;
3060   switch (I.getPredicate()) {
3061   default: llvm_unreachable("Unexpected predicate!");
3062   case FCmpInst::FCMP_UEQ:
3063   case FCmpInst::FCMP_OEQ:
3064     Pred = ICmpInst::ICMP_EQ;
3065     break;
3066   case FCmpInst::FCMP_UGT:
3067   case FCmpInst::FCMP_OGT:
3068     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3069     break;
3070   case FCmpInst::FCMP_UGE:
3071   case FCmpInst::FCMP_OGE:
3072     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3073     break;
3074   case FCmpInst::FCMP_ULT:
3075   case FCmpInst::FCMP_OLT:
3076     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3077     break;
3078   case FCmpInst::FCMP_ULE:
3079   case FCmpInst::FCMP_OLE:
3080     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3081     break;
3082   case FCmpInst::FCMP_UNE:
3083   case FCmpInst::FCMP_ONE:
3084     Pred = ICmpInst::ICMP_NE;
3085     break;
3086   case FCmpInst::FCMP_ORD:
3087     return ReplaceInstUsesWith(I, Builder->getTrue());
3088   case FCmpInst::FCMP_UNO:
3089     return ReplaceInstUsesWith(I, Builder->getFalse());
3090   }
3091
3092   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3093
3094   // Now we know that the APFloat is a normal number, zero or inf.
3095
3096   // See if the FP constant is too large for the integer.  For example,
3097   // comparing an i8 to 300.0.
3098   unsigned IntWidth = IntTy->getScalarSizeInBits();
3099
3100   if (!LHSUnsigned) {
3101     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
3102     // and large values.
3103     APFloat SMax(RHS.getSemantics());
3104     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3105                           APFloat::rmNearestTiesToEven);
3106     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
3107       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
3108           Pred == ICmpInst::ICMP_SLE)
3109         return ReplaceInstUsesWith(I, Builder->getTrue());
3110       return ReplaceInstUsesWith(I, Builder->getFalse());
3111     }
3112   } else {
3113     // If the RHS value is > UnsignedMax, fold the comparison. This handles
3114     // +INF and large values.
3115     APFloat UMax(RHS.getSemantics());
3116     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3117                           APFloat::rmNearestTiesToEven);
3118     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
3119       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
3120           Pred == ICmpInst::ICMP_ULE)
3121         return ReplaceInstUsesWith(I, Builder->getTrue());
3122       return ReplaceInstUsesWith(I, Builder->getFalse());
3123     }
3124   }
3125
3126   if (!LHSUnsigned) {
3127     // See if the RHS value is < SignedMin.
3128     APFloat SMin(RHS.getSemantics());
3129     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3130                           APFloat::rmNearestTiesToEven);
3131     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3132       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3133           Pred == ICmpInst::ICMP_SGE)
3134         return ReplaceInstUsesWith(I, Builder->getTrue());
3135       return ReplaceInstUsesWith(I, Builder->getFalse());
3136     }
3137   } else {
3138     // See if the RHS value is < UnsignedMin.
3139     APFloat SMin(RHS.getSemantics());
3140     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3141                           APFloat::rmNearestTiesToEven);
3142     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3143       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3144           Pred == ICmpInst::ICMP_UGE)
3145         return ReplaceInstUsesWith(I, Builder->getTrue());
3146       return ReplaceInstUsesWith(I, Builder->getFalse());
3147     }
3148   }
3149
3150   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3151   // [0, UMAX], but it may still be fractional.  See if it is fractional by
3152   // casting the FP value to the integer value and back, checking for equality.
3153   // Don't do this for zero, because -0.0 is not fractional.
3154   Constant *RHSInt = LHSUnsigned
3155     ? ConstantExpr::getFPToUI(RHSC, IntTy)
3156     : ConstantExpr::getFPToSI(RHSC, IntTy);
3157   if (!RHS.isZero()) {
3158     bool Equal = LHSUnsigned
3159       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3160       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3161     if (!Equal) {
3162       // If we had a comparison against a fractional value, we have to adjust
3163       // the compare predicate and sometimes the value.  RHSC is rounded towards
3164       // zero at this point.
3165       switch (Pred) {
3166       default: llvm_unreachable("Unexpected integer comparison!");
3167       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
3168         return ReplaceInstUsesWith(I, Builder->getTrue());
3169       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
3170         return ReplaceInstUsesWith(I, Builder->getFalse());
3171       case ICmpInst::ICMP_ULE:
3172         // (float)int <= 4.4   --> int <= 4
3173         // (float)int <= -4.4  --> false
3174         if (RHS.isNegative())
3175           return ReplaceInstUsesWith(I, Builder->getFalse());
3176         break;
3177       case ICmpInst::ICMP_SLE:
3178         // (float)int <= 4.4   --> int <= 4
3179         // (float)int <= -4.4  --> int < -4
3180         if (RHS.isNegative())
3181           Pred = ICmpInst::ICMP_SLT;
3182         break;
3183       case ICmpInst::ICMP_ULT:
3184         // (float)int < -4.4   --> false
3185         // (float)int < 4.4    --> int <= 4
3186         if (RHS.isNegative())
3187           return ReplaceInstUsesWith(I, Builder->getFalse());
3188         Pred = ICmpInst::ICMP_ULE;
3189         break;
3190       case ICmpInst::ICMP_SLT:
3191         // (float)int < -4.4   --> int < -4
3192         // (float)int < 4.4    --> int <= 4
3193         if (!RHS.isNegative())
3194           Pred = ICmpInst::ICMP_SLE;
3195         break;
3196       case ICmpInst::ICMP_UGT:
3197         // (float)int > 4.4    --> int > 4
3198         // (float)int > -4.4   --> true
3199         if (RHS.isNegative())
3200           return ReplaceInstUsesWith(I, Builder->getTrue());
3201         break;
3202       case ICmpInst::ICMP_SGT:
3203         // (float)int > 4.4    --> int > 4
3204         // (float)int > -4.4   --> int >= -4
3205         if (RHS.isNegative())
3206           Pred = ICmpInst::ICMP_SGE;
3207         break;
3208       case ICmpInst::ICMP_UGE:
3209         // (float)int >= -4.4   --> true
3210         // (float)int >= 4.4    --> int > 4
3211         if (RHS.isNegative())
3212           return ReplaceInstUsesWith(I, Builder->getTrue());
3213         Pred = ICmpInst::ICMP_UGT;
3214         break;
3215       case ICmpInst::ICMP_SGE:
3216         // (float)int >= -4.4   --> int >= -4
3217         // (float)int >= 4.4    --> int > 4
3218         if (!RHS.isNegative())
3219           Pred = ICmpInst::ICMP_SGT;
3220         break;
3221       }
3222     }
3223   }
3224
3225   // Lower this FP comparison into an appropriate integer version of the
3226   // comparison.
3227   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3228 }
3229
3230 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3231   bool Changed = false;
3232
3233   /// Orders the operands of the compare so that they are listed from most
3234   /// complex to least complex.  This puts constants before unary operators,
3235   /// before binary operators.
3236   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3237     I.swapOperands();
3238     Changed = true;
3239   }
3240
3241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
3243   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3244     return ReplaceInstUsesWith(I, V);
3245
3246   // Simplify 'fcmp pred X, X'
3247   if (Op0 == Op1) {
3248     switch (I.getPredicate()) {
3249     default: llvm_unreachable("Unknown predicate!");
3250     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
3251     case FCmpInst::FCMP_ULT:    // True if unordered or less than
3252     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
3253     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
3254       // Canonicalize these to be 'fcmp uno %X, 0.0'.
3255       I.setPredicate(FCmpInst::FCMP_UNO);
3256       I.setOperand(1, Constant::getNullValue(Op0->getType()));
3257       return &I;
3258
3259     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
3260     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
3261     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
3262     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
3263       // Canonicalize these to be 'fcmp ord %X, 0.0'.
3264       I.setPredicate(FCmpInst::FCMP_ORD);
3265       I.setOperand(1, Constant::getNullValue(Op0->getType()));
3266       return &I;
3267     }
3268   }
3269
3270   // Handle fcmp with constant RHS
3271   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3272     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3273       switch (LHSI->getOpcode()) {
3274       case Instruction::FPExt: {
3275         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3276         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3277         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3278         if (!RHSF)
3279           break;
3280
3281         const fltSemantics *Sem;
3282         // FIXME: This shouldn't be here.
3283         if (LHSExt->getSrcTy()->isHalfTy())
3284           Sem = &APFloat::IEEEhalf;
3285         else if (LHSExt->getSrcTy()->isFloatTy())
3286           Sem = &APFloat::IEEEsingle;
3287         else if (LHSExt->getSrcTy()->isDoubleTy())
3288           Sem = &APFloat::IEEEdouble;
3289         else if (LHSExt->getSrcTy()->isFP128Ty())
3290           Sem = &APFloat::IEEEquad;
3291         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3292           Sem = &APFloat::x87DoubleExtended;
3293         else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3294           Sem = &APFloat::PPCDoubleDouble;
3295         else
3296           break;
3297
3298         bool Lossy;
3299         APFloat F = RHSF->getValueAPF();
3300         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3301
3302         // Avoid lossy conversions and denormals. Zero is a special case
3303         // that's OK to convert.
3304         APFloat Fabs = F;
3305         Fabs.clearSign();
3306         if (!Lossy &&
3307             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3308                  APFloat::cmpLessThan) || Fabs.isZero()))
3309
3310           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3311                               ConstantFP::get(RHSC->getContext(), F));
3312         break;
3313       }
3314       case Instruction::PHI:
3315         // Only fold fcmp into the PHI if the phi and fcmp are in the same
3316         // block.  If in the same block, we're encouraging jump threading.  If
3317         // not, we are just pessimizing the code by making an i1 phi.
3318         if (LHSI->getParent() == I.getParent())
3319           if (Instruction *NV = FoldOpIntoPhi(I))
3320             return NV;
3321         break;
3322       case Instruction::SIToFP:
3323       case Instruction::UIToFP:
3324         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3325           return NV;
3326         break;
3327       case Instruction::Select: {
3328         // If either operand of the select is a constant, we can fold the
3329         // comparison into the select arms, which will cause one to be
3330         // constant folded and the select turned into a bitwise or.
3331         Value *Op1 = 0, *Op2 = 0;
3332         if (LHSI->hasOneUse()) {
3333           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3334             // Fold the known value into the constant operand.
3335             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3336             // Insert a new FCmp of the other select operand.
3337             Op2 = Builder->CreateFCmp(I.getPredicate(),
3338                                       LHSI->getOperand(2), RHSC, I.getName());
3339           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3340             // Fold the known value into the constant operand.
3341             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3342             // Insert a new FCmp of the other select operand.
3343             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3344                                       RHSC, I.getName());
3345           }
3346         }
3347
3348         if (Op1)
3349           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3350         break;
3351       }
3352       case Instruction::FSub: {
3353         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3354         Value *Op;
3355         if (match(LHSI, m_FNeg(m_Value(Op))))
3356           return new FCmpInst(I.getSwappedPredicate(), Op,
3357                               ConstantExpr::getFNeg(RHSC));
3358         break;
3359       }
3360       case Instruction::Load:
3361         if (GetElementPtrInst *GEP =
3362             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3363           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3364             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3365                 !cast<LoadInst>(LHSI)->isVolatile())
3366               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3367                 return Res;
3368         }
3369         break;
3370       case Instruction::Call: {
3371         CallInst *CI = cast<CallInst>(LHSI);
3372         LibFunc::Func Func;
3373         // Various optimization for fabs compared with zero.
3374         if (RHSC->isNullValue() && CI->getCalledFunction() &&
3375             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3376             TLI->has(Func)) {
3377           if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3378               Func == LibFunc::fabsl) {
3379             switch (I.getPredicate()) {
3380             default: break;
3381             // fabs(x) < 0 --> false
3382             case FCmpInst::FCMP_OLT:
3383               return ReplaceInstUsesWith(I, Builder->getFalse());
3384             // fabs(x) > 0 --> x != 0
3385             case FCmpInst::FCMP_OGT:
3386               return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3387                                   RHSC);
3388             // fabs(x) <= 0 --> x == 0
3389             case FCmpInst::FCMP_OLE:
3390               return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3391                                   RHSC);
3392             // fabs(x) >= 0 --> !isnan(x)
3393             case FCmpInst::FCMP_OGE:
3394               return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3395                                   RHSC);
3396             // fabs(x) == 0 --> x == 0
3397             // fabs(x) != 0 --> x != 0
3398             case FCmpInst::FCMP_OEQ:
3399             case FCmpInst::FCMP_UEQ:
3400             case FCmpInst::FCMP_ONE:
3401             case FCmpInst::FCMP_UNE:
3402               return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3403                                   RHSC);
3404             }
3405           }
3406         }
3407       }
3408       }
3409   }
3410
3411   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3412   Value *X, *Y;
3413   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3414     return new FCmpInst(I.getSwappedPredicate(), X, Y);
3415
3416   // fcmp (fpext x), (fpext y) -> fcmp x, y
3417   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3418     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3419       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3420         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3421                             RHSExt->getOperand(0));
3422
3423   return Changed ? &I : 0;
3424 }