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