The sign of an srem instruction is the sign of its dividend (the first
[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, Instruction &I,
473                                           InstCombiner &IC) {
474   TargetData &TD = *IC.getTargetData();
475   gep_type_iterator GTI = gep_type_begin(GEP);
476   
477   // Check to see if this gep only has a single variable index.  If so, and if
478   // any constant indices are a multiple of its scale, then we can compute this
479   // in terms of the scale of the variable index.  For example, if the GEP
480   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
481   // because the expression will cross zero at the same point.
482   unsigned i, e = GEP->getNumOperands();
483   int64_t Offset = 0;
484   for (i = 1; i != e; ++i, ++GTI) {
485     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
486       // Compute the aggregate offset of constant indices.
487       if (CI->isZero()) continue;
488       
489       // Handle a struct index, which adds its field offset to the pointer.
490       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
491         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
492       } else {
493         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
494         Offset += Size*CI->getSExtValue();
495       }
496     } else {
497       // Found our variable index.
498       break;
499     }
500   }
501   
502   // If there are no variable indices, we must have a constant offset, just
503   // evaluate it the general way.
504   if (i == e) return 0;
505   
506   Value *VariableIdx = GEP->getOperand(i);
507   // Determine the scale factor of the variable element.  For example, this is
508   // 4 if the variable index is into an array of i32.
509   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
510   
511   // Verify that there are no other variable indices.  If so, emit the hard way.
512   for (++i, ++GTI; i != e; ++i, ++GTI) {
513     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
514     if (!CI) return 0;
515     
516     // Compute the aggregate offset of constant indices.
517     if (CI->isZero()) continue;
518     
519     // Handle a struct index, which adds its field offset to the pointer.
520     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
521       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
522     } else {
523       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
524       Offset += Size*CI->getSExtValue();
525     }
526   }
527   
528   // Okay, we know we have a single variable index, which must be a
529   // pointer/array/vector index.  If there is no offset, life is simple, return
530   // the index.
531   unsigned IntPtrWidth = TD.getPointerSizeInBits();
532   if (Offset == 0) {
533     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
534     // we don't need to bother extending: the extension won't affect where the
535     // computation crosses zero.
536     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
537       VariableIdx = new TruncInst(VariableIdx, 
538                                   TD.getIntPtrType(VariableIdx->getContext()),
539                                   VariableIdx->getName(), &I);
540     return VariableIdx;
541   }
542   
543   // Otherwise, there is an index.  The computation we will do will be modulo
544   // the pointer size, so get it.
545   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
546   
547   Offset &= PtrSizeMask;
548   VariableScale &= PtrSizeMask;
549   
550   // To do this transformation, any constant index must be a multiple of the
551   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
552   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
553   // multiple of the variable scale.
554   int64_t NewOffs = Offset / (int64_t)VariableScale;
555   if (Offset != NewOffs*(int64_t)VariableScale)
556     return 0;
557   
558   // Okay, we can do this evaluation.  Start by converting the index to intptr.
559   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
560   if (VariableIdx->getType() != IntPtrTy)
561     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
562                                               true /*SExt*/, 
563                                               VariableIdx->getName(), &I);
564   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
565   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
566 }
567
568 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
569 /// else.  At this point we know that the GEP is on the LHS of the comparison.
570 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
571                                        ICmpInst::Predicate Cond,
572                                        Instruction &I) {
573   // Look through bitcasts.
574   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
575     RHS = BCI->getOperand(0);
576
577   Value *PtrBase = GEPLHS->getOperand(0);
578   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
579     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
580     // This transformation (ignoring the base and scales) is valid because we
581     // know pointers can't overflow since the gep is inbounds.  See if we can
582     // output an optimized form.
583     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
584     
585     // If not, synthesize the offset the hard way.
586     if (Offset == 0)
587       Offset = EmitGEPOffset(GEPLHS);
588     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
589                         Constant::getNullValue(Offset->getType()));
590   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
591     // If the base pointers are different, but the indices are the same, just
592     // compare the base pointer.
593     if (PtrBase != GEPRHS->getOperand(0)) {
594       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
595       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
596                         GEPRHS->getOperand(0)->getType();
597       if (IndicesTheSame)
598         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
599           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
600             IndicesTheSame = false;
601             break;
602           }
603
604       // If all indices are the same, just compare the base pointers.
605       if (IndicesTheSame)
606         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
607                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
608
609       // Otherwise, the base pointers are different and the indices are
610       // different, bail out.
611       return 0;
612     }
613
614     // If one of the GEPs has all zero indices, recurse.
615     bool AllZeros = true;
616     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
617       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
618           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
619         AllZeros = false;
620         break;
621       }
622     if (AllZeros)
623       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
624                           ICmpInst::getSwappedPredicate(Cond), I);
625
626     // If the other GEP has all zero indices, recurse.
627     AllZeros = true;
628     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
629       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
630           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
631         AllZeros = false;
632         break;
633       }
634     if (AllZeros)
635       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
636
637     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
638       // If the GEPs only differ by one index, compare it.
639       unsigned NumDifferences = 0;  // Keep track of # differences.
640       unsigned DiffOperand = 0;     // The operand that differs.
641       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
642         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
643           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
644                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
645             // Irreconcilable differences.
646             NumDifferences = 2;
647             break;
648           } else {
649             if (NumDifferences++) break;
650             DiffOperand = i;
651           }
652         }
653
654       if (NumDifferences == 0)   // SAME GEP?
655         return ReplaceInstUsesWith(I, // No comparison is needed here.
656                                ConstantInt::get(Type::getInt1Ty(I.getContext()),
657                                              ICmpInst::isTrueWhenEqual(Cond)));
658
659       else if (NumDifferences == 1) {
660         Value *LHSV = GEPLHS->getOperand(DiffOperand);
661         Value *RHSV = GEPRHS->getOperand(DiffOperand);
662         // Make sure we do a signed comparison here.
663         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
664       }
665     }
666
667     // Only lower this if the icmp is the only user of the GEP or if we expect
668     // the result to fold to a constant!
669     if (TD &&
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.  Similiarly 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 all exact ashr's are equivalent to a udiv/sdiv by
923     // a power of 2.  Since we already have logic to simplify these, transform
924     // to div and then simplify the resultant comparison.
925     if (Shr->getOpcode() == Instruction::AShr &&
926         !Shr->isExact())
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 (Cast->hasOneUse() &&
1091             (ICI.isEquality() ||
1092              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
1093           uint32_t BitWidth = 
1094             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
1095           APInt NewCST = AndCST->getValue().zext(BitWidth);
1096           APInt NewCI = RHSV.zext(BitWidth);
1097           Value *NewAnd = 
1098             Builder->CreateAnd(Cast->getOperand(0),
1099                            ConstantInt::get(ICI.getContext(), NewCST),
1100                                LHSI->getName());
1101           return new ICmpInst(ICI.getPredicate(), NewAnd,
1102                               ConstantInt::get(ICI.getContext(), NewCI));
1103         }
1104       }
1105       
1106       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1107       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1108       // happens a LOT in code produced by the C front-end, for bitfield
1109       // access.
1110       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1111       if (Shift && !Shift->isShift())
1112         Shift = 0;
1113       
1114       ConstantInt *ShAmt;
1115       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1116       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1117       const Type *AndTy = AndCST->getType();          // Type of the and.
1118       
1119       // We can fold this as long as we can't shift unknown bits
1120       // into the mask.  This can only happen with signed shift
1121       // rights, as they sign-extend.
1122       if (ShAmt) {
1123         bool CanFold = Shift->isLogicalShift();
1124         if (!CanFold) {
1125           // To test for the bad case of the signed shr, see if any
1126           // of the bits shifted in could be tested after the mask.
1127           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1128           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1129           
1130           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1131           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
1132                AndCST->getValue()) == 0)
1133             CanFold = true;
1134         }
1135         
1136         if (CanFold) {
1137           Constant *NewCst;
1138           if (Shift->getOpcode() == Instruction::Shl)
1139             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1140           else
1141             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1142           
1143           // Check to see if we are shifting out any of the bits being
1144           // compared.
1145           if (ConstantExpr::get(Shift->getOpcode(),
1146                                        NewCst, ShAmt) != RHS) {
1147             // If we shifted bits out, the fold is not going to work out.
1148             // As a special case, check to see if this means that the
1149             // result is always true or false now.
1150             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1151               return ReplaceInstUsesWith(ICI,
1152                                        ConstantInt::getFalse(ICI.getContext()));
1153             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1154               return ReplaceInstUsesWith(ICI,
1155                                        ConstantInt::getTrue(ICI.getContext()));
1156           } else {
1157             ICI.setOperand(1, NewCst);
1158             Constant *NewAndCST;
1159             if (Shift->getOpcode() == Instruction::Shl)
1160               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1161             else
1162               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1163             LHSI->setOperand(1, NewAndCST);
1164             LHSI->setOperand(0, Shift->getOperand(0));
1165             Worklist.Add(Shift); // Shift is dead.
1166             return &ICI;
1167           }
1168         }
1169       }
1170       
1171       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1172       // preferable because it allows the C<<Y expression to be hoisted out
1173       // of a loop if Y is invariant and X is not.
1174       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1175           ICI.isEquality() && !Shift->isArithmeticShift() &&
1176           !isa<Constant>(Shift->getOperand(0))) {
1177         // Compute C << Y.
1178         Value *NS;
1179         if (Shift->getOpcode() == Instruction::LShr) {
1180           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
1181         } else {
1182           // Insert a logical shift.
1183           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
1184         }
1185         
1186         // Compute X & (C << Y).
1187         Value *NewAnd = 
1188           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1189         
1190         ICI.setOperand(0, NewAnd);
1191         return &ICI;
1192       }
1193     }
1194       
1195     // Try to optimize things like "A[i]&42 == 0" to index computations.
1196     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1197       if (GetElementPtrInst *GEP =
1198           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1199         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1200           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1201               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1202             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1203             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1204               return Res;
1205           }
1206     }
1207     break;
1208
1209   case Instruction::Or: {
1210     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1211       break;
1212     Value *P, *Q;
1213     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1214       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1215       // -> and (icmp eq P, null), (icmp eq Q, null).
1216       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1217                                         Constant::getNullValue(P->getType()));
1218       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1219                                         Constant::getNullValue(Q->getType()));
1220       Instruction *Op;
1221       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1222         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1223       else
1224         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1225       return Op;
1226     }
1227     break;
1228   }
1229     
1230   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1231     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1232     if (!ShAmt) break;
1233     
1234     uint32_t TypeBits = RHSV.getBitWidth();
1235     
1236     // Check that the shift amount is in range.  If not, don't perform
1237     // undefined shifts.  When the shift is visited it will be
1238     // simplified.
1239     if (ShAmt->uge(TypeBits))
1240       break;
1241     
1242     if (ICI.isEquality()) {
1243       // If we are comparing against bits always shifted out, the
1244       // comparison cannot succeed.
1245       Constant *Comp =
1246         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1247                                                                  ShAmt);
1248       if (Comp != RHS) {// Comparing against a bit that we know is zero.
1249         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1250         Constant *Cst =
1251           ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1252         return ReplaceInstUsesWith(ICI, Cst);
1253       }
1254       
1255       // If the shift is NUW, then it is just shifting out zeros, no need for an
1256       // AND.
1257       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1258         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1259                             ConstantExpr::getLShr(RHS, ShAmt));
1260       
1261       if (LHSI->hasOneUse()) {
1262         // Otherwise strength reduce the shift into an and.
1263         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1264         Constant *Mask =
1265           ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits, 
1266                                                        TypeBits-ShAmtVal));
1267         
1268         Value *And =
1269           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1270         return new ICmpInst(ICI.getPredicate(), And,
1271                             ConstantExpr::getLShr(RHS, ShAmt));
1272       }
1273     }
1274     
1275     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1276     bool TrueIfSigned = false;
1277     if (LHSI->hasOneUse() &&
1278         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1279       // (X << 31) <s 0  --> (X&1) != 0
1280       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1281                                         APInt::getOneBitSet(TypeBits, 
1282                                             TypeBits-ShAmt->getZExtValue()-1));
1283       Value *And =
1284         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1285       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1286                           And, Constant::getNullValue(And->getType()));
1287     }
1288     break;
1289   }
1290     
1291   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1292   case Instruction::AShr:
1293     // Only handle equality comparisons of shift-by-constant.
1294     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1295       if (Instruction *Res = FoldICmpShrCst(ICI, cast<BinaryOperator>(LHSI),
1296                                             ShAmt))
1297         return Res;
1298     break;
1299     
1300   case Instruction::SDiv:
1301   case Instruction::UDiv:
1302     // Fold: icmp pred ([us]div X, C1), C2 -> range test
1303     // Fold this div into the comparison, producing a range check. 
1304     // Determine, based on the divide type, what the range is being 
1305     // checked.  If there is an overflow on the low or high side, remember 
1306     // it, otherwise compute the range [low, hi) bounding the new value.
1307     // See: InsertRangeTest above for the kinds of replacements possible.
1308     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1309       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1310                                           DivRHS))
1311         return R;
1312     break;
1313
1314   case Instruction::Add:
1315     // Fold: icmp pred (add X, C1), C2
1316     if (!ICI.isEquality()) {
1317       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1318       if (!LHSC) break;
1319       const APInt &LHSV = LHSC->getValue();
1320
1321       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1322                             .subtract(LHSV);
1323
1324       if (ICI.isSigned()) {
1325         if (CR.getLower().isSignBit()) {
1326           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1327                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1328         } else if (CR.getUpper().isSignBit()) {
1329           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1330                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1331         }
1332       } else {
1333         if (CR.getLower().isMinValue()) {
1334           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1335                               ConstantInt::get(ICI.getContext(),CR.getUpper()));
1336         } else if (CR.getUpper().isMinValue()) {
1337           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1338                               ConstantInt::get(ICI.getContext(),CR.getLower()));
1339         }
1340       }
1341     }
1342     break;
1343
1344   case Instruction::SRem: {
1345     bool TrueIfSigned;
1346     if (LHSI->hasOneUse() &&
1347         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1348       // srem has the same sign as its dividend so the divisor is irrelevant.
1349       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), RHS);
1350     }
1351     break;
1352   }
1353   }
1354   
1355   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1356   if (ICI.isEquality()) {
1357     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1358     
1359     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
1360     // the second operand is a constant, simplify a bit.
1361     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1362       switch (BO->getOpcode()) {
1363       case Instruction::SRem:
1364         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1365         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1366           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1367           if (V.sgt(1) && V.isPowerOf2()) {
1368             Value *NewRem =
1369               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1370                                   BO->getName());
1371             return new ICmpInst(ICI.getPredicate(), NewRem,
1372                                 Constant::getNullValue(BO->getType()));
1373           }
1374         }
1375         break;
1376       case Instruction::Add:
1377         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1378         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1379           if (BO->hasOneUse())
1380             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1381                                 ConstantExpr::getSub(RHS, BOp1C));
1382         } else if (RHSV == 0) {
1383           // Replace ((add A, B) != 0) with (A != -B) if A or B is
1384           // efficiently invertible, or if the add has just this one use.
1385           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1386           
1387           if (Value *NegVal = dyn_castNegVal(BOp1))
1388             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1389           else if (Value *NegVal = dyn_castNegVal(BOp0))
1390             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1391           else if (BO->hasOneUse()) {
1392             Value *Neg = Builder->CreateNeg(BOp1);
1393             Neg->takeName(BO);
1394             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1395           }
1396         }
1397         break;
1398       case Instruction::Xor:
1399         // For the xor case, we can xor two constants together, eliminating
1400         // the explicit xor.
1401         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1402           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
1403                               ConstantExpr::getXor(RHS, BOC));
1404         
1405         // FALLTHROUGH
1406       case Instruction::Sub:
1407         // Replace (([sub|xor] A, B) != 0) with (A != B)
1408         if (RHSV == 0)
1409           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1410                               BO->getOperand(1));
1411         break;
1412         
1413       case Instruction::Or:
1414         // If bits are being or'd in that are not present in the constant we
1415         // are comparing against, then the comparison could never succeed!
1416         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1417           Constant *NotCI = ConstantExpr::getNot(RHS);
1418           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1419             return ReplaceInstUsesWith(ICI,
1420                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()), 
1421                                        isICMP_NE));
1422         }
1423         break;
1424         
1425       case Instruction::And:
1426         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1427           // If bits are being compared against that are and'd out, then the
1428           // comparison can never succeed!
1429           if ((RHSV & ~BOC->getValue()) != 0)
1430             return ReplaceInstUsesWith(ICI,
1431                              ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1432                                        isICMP_NE));
1433           
1434           // If we have ((X & C) == C), turn it into ((X & C) != 0).
1435           if (RHS == BOC && RHSV.isPowerOf2())
1436             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1437                                 ICmpInst::ICMP_NE, LHSI,
1438                                 Constant::getNullValue(RHS->getType()));
1439           
1440           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1441           if (BOC->getValue().isSignBit()) {
1442             Value *X = BO->getOperand(0);
1443             Constant *Zero = Constant::getNullValue(X->getType());
1444             ICmpInst::Predicate pred = isICMP_NE ? 
1445               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1446             return new ICmpInst(pred, X, Zero);
1447           }
1448           
1449           // ((X & ~7) == 0) --> X < 8
1450           if (RHSV == 0 && isHighOnes(BOC)) {
1451             Value *X = BO->getOperand(0);
1452             Constant *NegX = ConstantExpr::getNeg(BOC);
1453             ICmpInst::Predicate pred = isICMP_NE ? 
1454               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1455             return new ICmpInst(pred, X, NegX);
1456           }
1457         }
1458       default: break;
1459       }
1460     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1461       // Handle icmp {eq|ne} <intrinsic>, intcst.
1462       switch (II->getIntrinsicID()) {
1463       case Intrinsic::bswap:
1464         Worklist.Add(II);
1465         ICI.setOperand(0, II->getArgOperand(0));
1466         ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1467         return &ICI;
1468       case Intrinsic::ctlz:
1469       case Intrinsic::cttz:
1470         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1471         if (RHSV == RHS->getType()->getBitWidth()) {
1472           Worklist.Add(II);
1473           ICI.setOperand(0, II->getArgOperand(0));
1474           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1475           return &ICI;
1476         }
1477         break;
1478       case Intrinsic::ctpop:
1479         // popcount(A) == 0  ->  A == 0 and likewise for !=
1480         if (RHS->isZero()) {
1481           Worklist.Add(II);
1482           ICI.setOperand(0, II->getArgOperand(0));
1483           ICI.setOperand(1, RHS);
1484           return &ICI;
1485         }
1486         break;
1487       default:
1488         break;
1489       }
1490     }
1491   }
1492   return 0;
1493 }
1494
1495 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1496 /// We only handle extending casts so far.
1497 ///
1498 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1499   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1500   Value *LHSCIOp        = LHSCI->getOperand(0);
1501   const Type *SrcTy     = LHSCIOp->getType();
1502   const Type *DestTy    = LHSCI->getType();
1503   Value *RHSCIOp;
1504
1505   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
1506   // integer type is the same size as the pointer type.
1507   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1508       TD->getPointerSizeInBits() ==
1509          cast<IntegerType>(DestTy)->getBitWidth()) {
1510     Value *RHSOp = 0;
1511     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1512       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1513     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1514       RHSOp = RHSC->getOperand(0);
1515       // If the pointer types don't match, insert a bitcast.
1516       if (LHSCIOp->getType() != RHSOp->getType())
1517         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1518     }
1519
1520     if (RHSOp)
1521       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1522   }
1523   
1524   // The code below only handles extension cast instructions, so far.
1525   // Enforce this.
1526   if (LHSCI->getOpcode() != Instruction::ZExt &&
1527       LHSCI->getOpcode() != Instruction::SExt)
1528     return 0;
1529
1530   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1531   bool isSignedCmp = ICI.isSigned();
1532
1533   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1534     // Not an extension from the same type?
1535     RHSCIOp = CI->getOperand(0);
1536     if (RHSCIOp->getType() != LHSCIOp->getType()) 
1537       return 0;
1538     
1539     // If the signedness of the two casts doesn't agree (i.e. one is a sext
1540     // and the other is a zext), then we can't handle this.
1541     if (CI->getOpcode() != LHSCI->getOpcode())
1542       return 0;
1543
1544     // Deal with equality cases early.
1545     if (ICI.isEquality())
1546       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1547
1548     // A signed comparison of sign extended values simplifies into a
1549     // signed comparison.
1550     if (isSignedCmp && isSignedExt)
1551       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1552
1553     // The other three cases all fold into an unsigned comparison.
1554     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1555   }
1556
1557   // If we aren't dealing with a constant on the RHS, exit early
1558   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1559   if (!CI)
1560     return 0;
1561
1562   // Compute the constant that would happen if we truncated to SrcTy then
1563   // reextended to DestTy.
1564   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1565   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1566                                                 Res1, DestTy);
1567
1568   // If the re-extended constant didn't change...
1569   if (Res2 == CI) {
1570     // Deal with equality cases early.
1571     if (ICI.isEquality())
1572       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1573
1574     // A signed comparison of sign extended values simplifies into a
1575     // signed comparison.
1576     if (isSignedExt && isSignedCmp)
1577       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1578
1579     // The other three cases all fold into an unsigned comparison.
1580     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1581   }
1582
1583   // The re-extended constant changed so the constant cannot be represented 
1584   // in the shorter type. Consequently, we cannot emit a simple comparison.
1585   // All the cases that fold to true or false will have already been handled
1586   // by SimplifyICmpInst, so only deal with the tricky case.
1587
1588   if (isSignedCmp || !isSignedExt)
1589     return 0;
1590
1591   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1592   // should have been folded away previously and not enter in here.
1593
1594   // We're performing an unsigned comp with a sign extended value.
1595   // This is true if the input is >= 0. [aka >s -1]
1596   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1597   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1598
1599   // Finally, return the value computed.
1600   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1601     return ReplaceInstUsesWith(ICI, Result);
1602
1603   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1604   return BinaryOperator::CreateNot(Result);
1605 }
1606
1607 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1608 ///   I = icmp ugt (add (add A, B), CI2), CI1
1609 /// If this is of the form:
1610 ///   sum = a + b
1611 ///   if (sum+128 >u 255)
1612 /// Then replace it with llvm.sadd.with.overflow.i8.
1613 ///
1614 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1615                                           ConstantInt *CI2, ConstantInt *CI1,
1616                                           InstCombiner &IC) {
1617   // The transformation we're trying to do here is to transform this into an
1618   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1619   // with a narrower add, and discard the add-with-constant that is part of the
1620   // range check (if we can't eliminate it, this isn't profitable).
1621   
1622   // In order to eliminate the add-with-constant, the compare can be its only
1623   // use.
1624   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1625   if (!AddWithCst->hasOneUse()) return 0;
1626   
1627   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1628   if (!CI2->getValue().isPowerOf2()) return 0;
1629   unsigned NewWidth = CI2->getValue().countTrailingZeros();
1630   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1631     
1632   // The width of the new add formed is 1 more than the bias.
1633   ++NewWidth;
1634   
1635   // Check to see that CI1 is an all-ones value with NewWidth bits.
1636   if (CI1->getBitWidth() == NewWidth ||
1637       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1638     return 0;
1639   
1640   // In order to replace the original add with a narrower 
1641   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1642   // and truncates that discard the high bits of the add.  Verify that this is
1643   // the case.
1644   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1645   for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1646        UI != E; ++UI) {
1647     if (*UI == AddWithCst) continue;
1648     
1649     // Only accept truncates for now.  We would really like a nice recursive
1650     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1651     // chain to see which bits of a value are actually demanded.  If the
1652     // original add had another add which was then immediately truncated, we
1653     // could still do the transformation.
1654     TruncInst *TI = dyn_cast<TruncInst>(*UI);
1655     if (TI == 0 ||
1656         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1657   }
1658   
1659   // If the pattern matches, truncate the inputs to the narrower type and
1660   // use the sadd_with_overflow intrinsic to efficiently compute both the
1661   // result and the overflow bit.
1662   Module *M = I.getParent()->getParent()->getParent();
1663   
1664   const Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1665   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1666                                        &NewType, 1);
1667
1668   InstCombiner::BuilderTy *Builder = IC.Builder;
1669   
1670   // Put the new code above the original add, in case there are any uses of the
1671   // add between the add and the compare.
1672   Builder->SetInsertPoint(OrigAdd);
1673   
1674   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1675   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1676   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1677   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1678   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1679   
1680   // The inner add was the result of the narrow add, zero extended to the
1681   // wider type.  Replace it with the result computed by the intrinsic.
1682   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1683   
1684   // The original icmp gets replaced with the overflow value.
1685   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1686 }
1687
1688 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1689                                      InstCombiner &IC) {
1690   // Don't bother doing this transformation for pointers, don't do it for
1691   // vectors.
1692   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1693   
1694   // If the add is a constant expr, then we don't bother transforming it.
1695   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1696   if (OrigAdd == 0) return 0;
1697   
1698   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1699   
1700   // Put the new code above the original add, in case there are any uses of the
1701   // add between the add and the compare.
1702   InstCombiner::BuilderTy *Builder = IC.Builder;
1703   Builder->SetInsertPoint(OrigAdd);
1704
1705   Module *M = I.getParent()->getParent()->getParent();
1706   const Type *Ty = LHS->getType();
1707   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, &Ty,1);
1708   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1709   Value *Add = Builder->CreateExtractValue(Call, 0);
1710
1711   IC.ReplaceInstUsesWith(*OrigAdd, Add);
1712
1713   // The original icmp gets replaced with the overflow value.
1714   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1715 }
1716
1717 // DemandedBitsLHSMask - When performing a comparison against a constant,
1718 // it is possible that not all the bits in the LHS are demanded.  This helper
1719 // method computes the mask that IS demanded.
1720 static APInt DemandedBitsLHSMask(ICmpInst &I,
1721                                  unsigned BitWidth, bool isSignCheck) {
1722   if (isSignCheck)
1723     return APInt::getSignBit(BitWidth);
1724   
1725   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1726   if (!CI) return APInt::getAllOnesValue(BitWidth);
1727   const APInt &RHS = CI->getValue();
1728   
1729   switch (I.getPredicate()) {
1730   // For a UGT comparison, we don't care about any bits that 
1731   // correspond to the trailing ones of the comparand.  The value of these
1732   // bits doesn't impact the outcome of the comparison, because any value
1733   // greater than the RHS must differ in a bit higher than these due to carry.
1734   case ICmpInst::ICMP_UGT: {
1735     unsigned trailingOnes = RHS.countTrailingOnes();
1736     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1737     return ~lowBitsSet;
1738   }
1739   
1740   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1741   // Any value less than the RHS must differ in a higher bit because of carries.
1742   case ICmpInst::ICMP_ULT: {
1743     unsigned trailingZeros = RHS.countTrailingZeros();
1744     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1745     return ~lowBitsSet;
1746   }
1747   
1748   default:
1749     return APInt::getAllOnesValue(BitWidth);
1750   }
1751   
1752 }
1753
1754 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1755   bool Changed = false;
1756   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1757   
1758   /// Orders the operands of the compare so that they are listed from most
1759   /// complex to least complex.  This puts constants before unary operators,
1760   /// before binary operators.
1761   if (getComplexity(Op0) < getComplexity(Op1)) {
1762     I.swapOperands();
1763     std::swap(Op0, Op1);
1764     Changed = true;
1765   }
1766   
1767   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1768     return ReplaceInstUsesWith(I, V);
1769   
1770   const Type *Ty = Op0->getType();
1771
1772   // icmp's with boolean values can always be turned into bitwise operations
1773   if (Ty->isIntegerTy(1)) {
1774     switch (I.getPredicate()) {
1775     default: llvm_unreachable("Invalid icmp instruction!");
1776     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
1777       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1778       return BinaryOperator::CreateNot(Xor);
1779     }
1780     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
1781       return BinaryOperator::CreateXor(Op0, Op1);
1782
1783     case ICmpInst::ICMP_UGT:
1784       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
1785       // FALL THROUGH
1786     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
1787       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1788       return BinaryOperator::CreateAnd(Not, Op1);
1789     }
1790     case ICmpInst::ICMP_SGT:
1791       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
1792       // FALL THROUGH
1793     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
1794       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1795       return BinaryOperator::CreateAnd(Not, Op0);
1796     }
1797     case ICmpInst::ICMP_UGE:
1798       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
1799       // FALL THROUGH
1800     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
1801       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1802       return BinaryOperator::CreateOr(Not, Op1);
1803     }
1804     case ICmpInst::ICMP_SGE:
1805       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
1806       // FALL THROUGH
1807     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
1808       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1809       return BinaryOperator::CreateOr(Not, Op0);
1810     }
1811     }
1812   }
1813
1814   unsigned BitWidth = 0;
1815   if (Ty->isIntOrIntVectorTy())
1816     BitWidth = Ty->getScalarSizeInBits();
1817   else if (TD)  // Pointers require TD info to get their size.
1818     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
1819   
1820   bool isSignBit = false;
1821
1822   // See if we are doing a comparison with a constant.
1823   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1824     Value *A = 0, *B = 0;
1825     
1826     // Match the following pattern, which is a common idiom when writing
1827     // overflow-safe integer arithmetic function.  The source performs an
1828     // addition in wider type, and explicitly checks for overflow using
1829     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
1830     // sadd_with_overflow intrinsic.
1831     //
1832     // TODO: This could probably be generalized to handle other overflow-safe
1833     // operations if we worked out the formulas to compute the appropriate 
1834     // magic constants.
1835     // 
1836     // sum = a + b
1837     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
1838     {
1839     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
1840     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
1841         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1842       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
1843         return Res;
1844     }
1845     
1846     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1847     if (I.isEquality() && CI->isZero() &&
1848         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1849       // (icmp cond A B) if cond is equality
1850       return new ICmpInst(I.getPredicate(), A, B);
1851     }
1852     
1853     // If we have an icmp le or icmp ge instruction, turn it into the
1854     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1855     // them being folded in the code below.  The SimplifyICmpInst code has
1856     // already handled the edge cases for us, so we just assert on them.
1857     switch (I.getPredicate()) {
1858     default: break;
1859     case ICmpInst::ICMP_ULE:
1860       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
1861       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1862                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1863     case ICmpInst::ICMP_SLE:
1864       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
1865       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1866                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
1867     case ICmpInst::ICMP_UGE:
1868       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
1869       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1870                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1871     case ICmpInst::ICMP_SGE:
1872       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
1873       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1874                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
1875     }
1876     
1877     // If this comparison is a normal comparison, it demands all
1878     // bits, if it is a sign bit comparison, it only demands the sign bit.
1879     bool UnusedBit;
1880     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1881   }
1882
1883   // See if we can fold the comparison based on range information we can get
1884   // by checking whether bits are known to be zero or one in the input.
1885   if (BitWidth != 0) {
1886     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1887     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1888
1889     if (SimplifyDemandedBits(I.getOperandUse(0),
1890                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
1891                              Op0KnownZero, Op0KnownOne, 0))
1892       return &I;
1893     if (SimplifyDemandedBits(I.getOperandUse(1),
1894                              APInt::getAllOnesValue(BitWidth),
1895                              Op1KnownZero, Op1KnownOne, 0))
1896       return &I;
1897
1898     // Given the known and unknown bits, compute a range that the LHS could be
1899     // in.  Compute the Min, Max and RHS values based on the known bits. For the
1900     // EQ and NE we use unsigned values.
1901     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1902     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1903     if (I.isSigned()) {
1904       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1905                                              Op0Min, Op0Max);
1906       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1907                                              Op1Min, Op1Max);
1908     } else {
1909       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1910                                                Op0Min, Op0Max);
1911       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1912                                                Op1Min, Op1Max);
1913     }
1914
1915     // If Min and Max are known to be the same, then SimplifyDemandedBits
1916     // figured out that the LHS is a constant.  Just constant fold this now so
1917     // that code below can assume that Min != Max.
1918     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1919       return new ICmpInst(I.getPredicate(),
1920                           ConstantInt::get(I.getContext(), Op0Min), Op1);
1921     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1922       return new ICmpInst(I.getPredicate(), Op0,
1923                           ConstantInt::get(I.getContext(), Op1Min));
1924
1925     // Based on the range information we know about the LHS, see if we can
1926     // simplify this comparison.  For example, (x&4) < 8 is always true.
1927     switch (I.getPredicate()) {
1928     default: llvm_unreachable("Unknown icmp opcode!");
1929     case ICmpInst::ICMP_EQ: {
1930       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1931         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
1932         
1933       // If all bits are known zero except for one, then we know at most one
1934       // bit is set.   If the comparison is against zero, then this is a check
1935       // to see if *that* bit is set.
1936       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1937       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1938         // If the LHS is an AND with the same constant, look through it.
1939         Value *LHS = 0;
1940         ConstantInt *LHSC = 0;
1941         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1942             LHSC->getValue() != Op0KnownZeroInverted)
1943           LHS = Op0;
1944         
1945         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1946         // then turn "((1 << x)&8) == 0" into "x != 3".
1947         Value *X = 0;
1948         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1949           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1950           return new ICmpInst(ICmpInst::ICMP_NE, X,
1951                               ConstantInt::get(X->getType(), CmpVal));
1952         }
1953         
1954         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1955         // then turn "((8 >>u x)&1) == 0" into "x != 3".
1956         const APInt *CI;
1957         if (Op0KnownZeroInverted == 1 &&
1958             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1959           return new ICmpInst(ICmpInst::ICMP_NE, X,
1960                               ConstantInt::get(X->getType(),
1961                                                CI->countTrailingZeros()));
1962       }
1963         
1964       break;
1965     }
1966     case ICmpInst::ICMP_NE: {
1967       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
1968         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1969       
1970       // If all bits are known zero except for one, then we know at most one
1971       // bit is set.   If the comparison is against zero, then this is a check
1972       // to see if *that* bit is set.
1973       APInt Op0KnownZeroInverted = ~Op0KnownZero;
1974       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
1975         // If the LHS is an AND with the same constant, look through it.
1976         Value *LHS = 0;
1977         ConstantInt *LHSC = 0;
1978         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
1979             LHSC->getValue() != Op0KnownZeroInverted)
1980           LHS = Op0;
1981         
1982         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
1983         // then turn "((1 << x)&8) != 0" into "x == 3".
1984         Value *X = 0;
1985         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
1986           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
1987           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1988                               ConstantInt::get(X->getType(), CmpVal));
1989         }
1990         
1991         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
1992         // then turn "((8 >>u x)&1) != 0" into "x == 3".
1993         const APInt *CI;
1994         if (Op0KnownZeroInverted == 1 &&
1995             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
1996           return new ICmpInst(ICmpInst::ICMP_EQ, X,
1997                               ConstantInt::get(X->getType(),
1998                                                CI->countTrailingZeros()));
1999       }
2000       
2001       break;
2002     }
2003     case ICmpInst::ICMP_ULT:
2004       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2005         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2006       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2007         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2008       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2009         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2010       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2011         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2012           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2013                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2014
2015         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2016         if (CI->isMinValue(true))
2017           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2018                            Constant::getAllOnesValue(Op0->getType()));
2019       }
2020       break;
2021     case ICmpInst::ICMP_UGT:
2022       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2023         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2024       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2025         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2026
2027       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2028         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2029       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2030         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2031           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2032                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2033
2034         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2035         if (CI->isMaxValue(true))
2036           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2037                               Constant::getNullValue(Op0->getType()));
2038       }
2039       break;
2040     case ICmpInst::ICMP_SLT:
2041       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2042         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2043       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2044         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2045       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2046         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2047       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2048         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2049           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2050                           ConstantInt::get(CI->getContext(), CI->getValue()-1));
2051       }
2052       break;
2053     case ICmpInst::ICMP_SGT:
2054       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2055         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2056       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2057         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2058
2059       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2060         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2061       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2062         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2063           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2064                           ConstantInt::get(CI->getContext(), CI->getValue()+1));
2065       }
2066       break;
2067     case ICmpInst::ICMP_SGE:
2068       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2069       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2070         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2071       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2072         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2073       break;
2074     case ICmpInst::ICMP_SLE:
2075       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2076       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2077         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2078       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2079         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2080       break;
2081     case ICmpInst::ICMP_UGE:
2082       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2083       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2084         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2085       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2086         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2087       break;
2088     case ICmpInst::ICMP_ULE:
2089       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2090       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2091         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2092       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2093         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2094       break;
2095     }
2096
2097     // Turn a signed comparison into an unsigned one if both operands
2098     // are known to have the same sign.
2099     if (I.isSigned() &&
2100         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2101          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2102       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2103   }
2104
2105   // Test if the ICmpInst instruction is used exclusively by a select as
2106   // part of a minimum or maximum operation. If so, refrain from doing
2107   // any other folding. This helps out other analyses which understand
2108   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2109   // and CodeGen. And in this case, at least one of the comparison
2110   // operands has at least one user besides the compare (the select),
2111   // which would often largely negate the benefit of folding anyway.
2112   if (I.hasOneUse())
2113     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2114       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2115           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2116         return 0;
2117
2118   // See if we are doing a comparison between a constant and an instruction that
2119   // can be folded into the comparison.
2120   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2121     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
2122     // instruction, see if that instruction also has constants so that the 
2123     // instruction can be folded into the icmp 
2124     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2125       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2126         return Res;
2127   }
2128
2129   // Handle icmp with constant (but not simple integer constant) RHS
2130   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2131     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2132       switch (LHSI->getOpcode()) {
2133       case Instruction::GetElementPtr:
2134           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2135         if (RHSC->isNullValue() &&
2136             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2137           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2138                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
2139         break;
2140       case Instruction::PHI:
2141         // Only fold icmp into the PHI if the phi and icmp are in the same
2142         // block.  If in the same block, we're encouraging jump threading.  If
2143         // not, we are just pessimizing the code by making an i1 phi.
2144         if (LHSI->getParent() == I.getParent())
2145           if (Instruction *NV = FoldOpIntoPhi(I))
2146             return NV;
2147         break;
2148       case Instruction::Select: {
2149         // If either operand of the select is a constant, we can fold the
2150         // comparison into the select arms, which will cause one to be
2151         // constant folded and the select turned into a bitwise or.
2152         Value *Op1 = 0, *Op2 = 0;
2153         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2154           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2155         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2156           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2157
2158         // We only want to perform this transformation if it will not lead to
2159         // additional code. This is true if either both sides of the select
2160         // fold to a constant (in which case the icmp is replaced with a select
2161         // which will usually simplify) or this is the only user of the
2162         // select (in which case we are trading a select+icmp for a simpler
2163         // select+icmp).
2164         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2165           if (!Op1)
2166             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2167                                       RHSC, I.getName());
2168           if (!Op2)
2169             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2170                                       RHSC, I.getName());
2171           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2172         }
2173         break;
2174       }
2175       case Instruction::IntToPtr:
2176         // icmp pred inttoptr(X), null -> icmp pred X, 0
2177         if (RHSC->isNullValue() && TD &&
2178             TD->getIntPtrType(RHSC->getContext()) == 
2179                LHSI->getOperand(0)->getType())
2180           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2181                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
2182         break;
2183
2184       case Instruction::Load:
2185         // Try to optimize things like "A[i] > 4" to index computations.
2186         if (GetElementPtrInst *GEP =
2187               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2188           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2189             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2190                 !cast<LoadInst>(LHSI)->isVolatile())
2191               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2192                 return Res;
2193         }
2194         break;
2195       }
2196   }
2197
2198   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2199   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2200     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2201       return NI;
2202   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2203     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2204                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2205       return NI;
2206
2207   // Test to see if the operands of the icmp are casted versions of other
2208   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2209   // now.
2210   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2211     if (Op0->getType()->isPointerTy() && 
2212         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
2213       // We keep moving the cast from the left operand over to the right
2214       // operand, where it can often be eliminated completely.
2215       Op0 = CI->getOperand(0);
2216
2217       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2218       // so eliminate it as well.
2219       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2220         Op1 = CI2->getOperand(0);
2221
2222       // If Op1 is a constant, we can fold the cast into the constant.
2223       if (Op0->getType() != Op1->getType()) {
2224         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2225           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2226         } else {
2227           // Otherwise, cast the RHS right before the icmp
2228           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2229         }
2230       }
2231       return new ICmpInst(I.getPredicate(), Op0, Op1);
2232     }
2233   }
2234   
2235   if (isa<CastInst>(Op0)) {
2236     // Handle the special case of: icmp (cast bool to X), <cst>
2237     // This comes up when you have code like
2238     //   int X = A < B;
2239     //   if (X) ...
2240     // For generality, we handle any zero-extension of any operand comparison
2241     // with a constant or another cast from the same type.
2242     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2243       if (Instruction *R = visitICmpInstWithCastAndCast(I))
2244         return R;
2245   }
2246
2247   // Special logic for binary operators.
2248   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2249   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2250   if (BO0 || BO1) {
2251     CmpInst::Predicate Pred = I.getPredicate();
2252     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2253     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2254       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2255         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2256         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2257     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2258       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2259         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2260         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2261
2262     // Analyze the case when either Op0 or Op1 is an add instruction.
2263     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2264     Value *A = 0, *B = 0, *C = 0, *D = 0;
2265     if (BO0 && BO0->getOpcode() == Instruction::Add)
2266       A = BO0->getOperand(0), B = BO0->getOperand(1);
2267     if (BO1 && BO1->getOpcode() == Instruction::Add)
2268       C = BO1->getOperand(0), D = BO1->getOperand(1);
2269
2270     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2271     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2272       return new ICmpInst(Pred, A == Op1 ? B : A,
2273                           Constant::getNullValue(Op1->getType()));
2274
2275     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2276     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2277       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2278                           C == Op0 ? D : C);
2279
2280     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2281     if (A && C && (A == C || A == D || B == C || B == D) &&
2282         NoOp0WrapProblem && NoOp1WrapProblem &&
2283         // Try not to increase register pressure.
2284         BO0->hasOneUse() && BO1->hasOneUse()) {
2285       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2286       Value *Y = (A == C || A == D) ? B : A;
2287       Value *Z = (C == A || C == B) ? D : C;
2288       return new ICmpInst(Pred, Y, Z);
2289     }
2290
2291     // Analyze the case when either Op0 or Op1 is a sub instruction.
2292     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2293     A = 0; B = 0; C = 0; D = 0;
2294     if (BO0 && BO0->getOpcode() == Instruction::Sub)
2295       A = BO0->getOperand(0), B = BO0->getOperand(1);
2296     if (BO1 && BO1->getOpcode() == Instruction::Sub)
2297       C = BO1->getOperand(0), D = BO1->getOperand(1);
2298
2299     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2300     if (A == Op1 && NoOp0WrapProblem)
2301       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2302
2303     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2304     if (C == Op0 && NoOp1WrapProblem)
2305       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2306
2307     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2308     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2309         // Try not to increase register pressure.
2310         BO0->hasOneUse() && BO1->hasOneUse())
2311       return new ICmpInst(Pred, A, C);
2312
2313     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2314     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2315         // Try not to increase register pressure.
2316         BO0->hasOneUse() && BO1->hasOneUse())
2317       return new ICmpInst(Pred, D, B);
2318
2319     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2320         BO0->hasOneUse() && BO1->hasOneUse() &&
2321         BO0->getOperand(1) == BO1->getOperand(1)) {
2322       switch (BO0->getOpcode()) {
2323       default: break;
2324       case Instruction::Add:
2325       case Instruction::Sub:
2326       case Instruction::Xor:
2327         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2328           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2329                               BO1->getOperand(0));
2330         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2331         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2332           if (CI->getValue().isSignBit()) {
2333             ICmpInst::Predicate Pred = I.isSigned()
2334                                            ? I.getUnsignedPredicate()
2335                                            : I.getSignedPredicate();
2336             return new ICmpInst(Pred, BO0->getOperand(0),
2337                                 BO1->getOperand(0));
2338           }
2339           
2340           if (CI->getValue().isMaxSignedValue()) {
2341             ICmpInst::Predicate Pred = I.isSigned()
2342                                            ? I.getUnsignedPredicate()
2343                                            : I.getSignedPredicate();
2344             Pred = I.getSwappedPredicate(Pred);
2345             return new ICmpInst(Pred, BO0->getOperand(0),
2346                                 BO1->getOperand(0));
2347           }
2348         }
2349         break;
2350       case Instruction::Mul:
2351         if (!I.isEquality())
2352           break;
2353
2354         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2355           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2356           // Mask = -1 >> count-trailing-zeros(Cst).
2357           if (!CI->isZero() && !CI->isOne()) {
2358             const APInt &AP = CI->getValue();
2359             ConstantInt *Mask = ConstantInt::get(I.getContext(), 
2360                                     APInt::getLowBitsSet(AP.getBitWidth(),
2361                                                          AP.getBitWidth() -
2362                                                     AP.countTrailingZeros()));
2363             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2364             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2365             return new ICmpInst(I.getPredicate(), And1, And2);
2366           }
2367         }
2368         break;
2369       }
2370     }
2371   }
2372   
2373   { Value *A, *B;
2374     // ~x < ~y --> y < x
2375     // ~x < cst --> ~cst < x
2376     if (match(Op0, m_Not(m_Value(A)))) {
2377       if (match(Op1, m_Not(m_Value(B))))
2378         return new ICmpInst(I.getPredicate(), B, A);
2379       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2380         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2381     }
2382
2383     // (a+b) <u a  --> llvm.uadd.with.overflow.
2384     // (a+b) <u b  --> llvm.uadd.with.overflow.
2385     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2386         match(Op0, m_Add(m_Value(A), m_Value(B))) && 
2387         (Op1 == A || Op1 == B))
2388       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2389         return R;
2390                                  
2391     // a >u (a+b)  --> llvm.uadd.with.overflow.
2392     // b >u (a+b)  --> llvm.uadd.with.overflow.
2393     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2394         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2395         (Op0 == A || Op0 == B))
2396       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2397         return R;
2398   }
2399   
2400   if (I.isEquality()) {
2401     Value *A, *B, *C, *D;
2402
2403     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2404       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2405         Value *OtherVal = A == Op1 ? B : A;
2406         return new ICmpInst(I.getPredicate(), OtherVal,
2407                             Constant::getNullValue(A->getType()));
2408       }
2409
2410       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2411         // A^c1 == C^c2 --> A == C^(c1^c2)
2412         ConstantInt *C1, *C2;
2413         if (match(B, m_ConstantInt(C1)) &&
2414             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2415           Constant *NC = ConstantInt::get(I.getContext(),
2416                                           C1->getValue() ^ C2->getValue());
2417           Value *Xor = Builder->CreateXor(C, NC, "tmp");
2418           return new ICmpInst(I.getPredicate(), A, Xor);
2419         }
2420         
2421         // A^B == A^D -> B == D
2422         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2423         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2424         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2425         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2426       }
2427     }
2428     
2429     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2430         (A == Op0 || B == Op0)) {
2431       // A == (A^B)  ->  B == 0
2432       Value *OtherVal = A == Op0 ? B : A;
2433       return new ICmpInst(I.getPredicate(), OtherVal,
2434                           Constant::getNullValue(A->getType()));
2435     }
2436
2437     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2438     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2439         match(Op0, m_And(m_Value(A), m_Value(B))) && 
2440         match(Op1, m_And(m_Value(C), m_Value(D)))) {
2441       Value *X = 0, *Y = 0, *Z = 0;
2442       
2443       if (A == C) {
2444         X = B; Y = D; Z = A;
2445       } else if (A == D) {
2446         X = B; Y = C; Z = A;
2447       } else if (B == C) {
2448         X = A; Y = D; Z = B;
2449       } else if (B == D) {
2450         X = A; Y = C; Z = B;
2451       }
2452       
2453       if (X) {   // Build (X^Y) & Z
2454         Op1 = Builder->CreateXor(X, Y, "tmp");
2455         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
2456         I.setOperand(0, Op1);
2457         I.setOperand(1, Constant::getNullValue(Op1->getType()));
2458         return &I;
2459       }
2460     }
2461   }
2462   
2463   {
2464     Value *X; ConstantInt *Cst;
2465     // icmp X+Cst, X
2466     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2467       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2468
2469     // icmp X, X+Cst
2470     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2471       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2472   }
2473   return Changed ? &I : 0;
2474 }
2475
2476
2477
2478
2479
2480
2481 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2482 ///
2483 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2484                                                 Instruction *LHSI,
2485                                                 Constant *RHSC) {
2486   if (!isa<ConstantFP>(RHSC)) return 0;
2487   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
2488   
2489   // Get the width of the mantissa.  We don't want to hack on conversions that
2490   // might lose information from the integer, e.g. "i64 -> float"
2491   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2492   if (MantissaWidth == -1) return 0;  // Unknown.
2493   
2494   // Check to see that the input is converted from an integer type that is small
2495   // enough that preserves all bits.  TODO: check here for "known" sign bits.
2496   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2497   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
2498   
2499   // If this is a uitofp instruction, we need an extra bit to hold the sign.
2500   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2501   if (LHSUnsigned)
2502     ++InputSize;
2503   
2504   // If the conversion would lose info, don't hack on this.
2505   if ((int)InputSize > MantissaWidth)
2506     return 0;
2507   
2508   // Otherwise, we can potentially simplify the comparison.  We know that it
2509   // will always come through as an integer value and we know the constant is
2510   // not a NAN (it would have been previously simplified).
2511   assert(!RHS.isNaN() && "NaN comparison not already folded!");
2512   
2513   ICmpInst::Predicate Pred;
2514   switch (I.getPredicate()) {
2515   default: llvm_unreachable("Unexpected predicate!");
2516   case FCmpInst::FCMP_UEQ:
2517   case FCmpInst::FCMP_OEQ:
2518     Pred = ICmpInst::ICMP_EQ;
2519     break;
2520   case FCmpInst::FCMP_UGT:
2521   case FCmpInst::FCMP_OGT:
2522     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2523     break;
2524   case FCmpInst::FCMP_UGE:
2525   case FCmpInst::FCMP_OGE:
2526     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2527     break;
2528   case FCmpInst::FCMP_ULT:
2529   case FCmpInst::FCMP_OLT:
2530     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2531     break;
2532   case FCmpInst::FCMP_ULE:
2533   case FCmpInst::FCMP_OLE:
2534     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2535     break;
2536   case FCmpInst::FCMP_UNE:
2537   case FCmpInst::FCMP_ONE:
2538     Pred = ICmpInst::ICMP_NE;
2539     break;
2540   case FCmpInst::FCMP_ORD:
2541     return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2542   case FCmpInst::FCMP_UNO:
2543     return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2544   }
2545   
2546   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
2547   
2548   // Now we know that the APFloat is a normal number, zero or inf.
2549   
2550   // See if the FP constant is too large for the integer.  For example,
2551   // comparing an i8 to 300.0.
2552   unsigned IntWidth = IntTy->getScalarSizeInBits();
2553   
2554   if (!LHSUnsigned) {
2555     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
2556     // and large values.
2557     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2558     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2559                           APFloat::rmNearestTiesToEven);
2560     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
2561       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
2562           Pred == ICmpInst::ICMP_SLE)
2563         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2564       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2565     }
2566   } else {
2567     // If the RHS value is > UnsignedMax, fold the comparison. This handles
2568     // +INF and large values.
2569     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2570     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2571                           APFloat::rmNearestTiesToEven);
2572     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
2573       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
2574           Pred == ICmpInst::ICMP_ULE)
2575         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2576       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2577     }
2578   }
2579   
2580   if (!LHSUnsigned) {
2581     // See if the RHS value is < SignedMin.
2582     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2583     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2584                           APFloat::rmNearestTiesToEven);
2585     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2586       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2587           Pred == ICmpInst::ICMP_SGE)
2588         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2589       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2590     }
2591   }
2592
2593   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2594   // [0, UMAX], but it may still be fractional.  See if it is fractional by
2595   // casting the FP value to the integer value and back, checking for equality.
2596   // Don't do this for zero, because -0.0 is not fractional.
2597   Constant *RHSInt = LHSUnsigned
2598     ? ConstantExpr::getFPToUI(RHSC, IntTy)
2599     : ConstantExpr::getFPToSI(RHSC, IntTy);
2600   if (!RHS.isZero()) {
2601     bool Equal = LHSUnsigned
2602       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2603       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2604     if (!Equal) {
2605       // If we had a comparison against a fractional value, we have to adjust
2606       // the compare predicate and sometimes the value.  RHSC is rounded towards
2607       // zero at this point.
2608       switch (Pred) {
2609       default: llvm_unreachable("Unexpected integer comparison!");
2610       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
2611         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2612       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
2613         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2614       case ICmpInst::ICMP_ULE:
2615         // (float)int <= 4.4   --> int <= 4
2616         // (float)int <= -4.4  --> false
2617         if (RHS.isNegative())
2618           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2619         break;
2620       case ICmpInst::ICMP_SLE:
2621         // (float)int <= 4.4   --> int <= 4
2622         // (float)int <= -4.4  --> int < -4
2623         if (RHS.isNegative())
2624           Pred = ICmpInst::ICMP_SLT;
2625         break;
2626       case ICmpInst::ICMP_ULT:
2627         // (float)int < -4.4   --> false
2628         // (float)int < 4.4    --> int <= 4
2629         if (RHS.isNegative())
2630           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2631         Pred = ICmpInst::ICMP_ULE;
2632         break;
2633       case ICmpInst::ICMP_SLT:
2634         // (float)int < -4.4   --> int < -4
2635         // (float)int < 4.4    --> int <= 4
2636         if (!RHS.isNegative())
2637           Pred = ICmpInst::ICMP_SLE;
2638         break;
2639       case ICmpInst::ICMP_UGT:
2640         // (float)int > 4.4    --> int > 4
2641         // (float)int > -4.4   --> true
2642         if (RHS.isNegative())
2643           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2644         break;
2645       case ICmpInst::ICMP_SGT:
2646         // (float)int > 4.4    --> int > 4
2647         // (float)int > -4.4   --> int >= -4
2648         if (RHS.isNegative())
2649           Pred = ICmpInst::ICMP_SGE;
2650         break;
2651       case ICmpInst::ICMP_UGE:
2652         // (float)int >= -4.4   --> true
2653         // (float)int >= 4.4    --> int > 4
2654         if (!RHS.isNegative())
2655           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2656         Pred = ICmpInst::ICMP_UGT;
2657         break;
2658       case ICmpInst::ICMP_SGE:
2659         // (float)int >= -4.4   --> int >= -4
2660         // (float)int >= 4.4    --> int > 4
2661         if (!RHS.isNegative())
2662           Pred = ICmpInst::ICMP_SGT;
2663         break;
2664       }
2665     }
2666   }
2667
2668   // Lower this FP comparison into an appropriate integer version of the
2669   // comparison.
2670   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2671 }
2672
2673 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2674   bool Changed = false;
2675   
2676   /// Orders the operands of the compare so that they are listed from most
2677   /// complex to least complex.  This puts constants before unary operators,
2678   /// before binary operators.
2679   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2680     I.swapOperands();
2681     Changed = true;
2682   }
2683
2684   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2685   
2686   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2687     return ReplaceInstUsesWith(I, V);
2688
2689   // Simplify 'fcmp pred X, X'
2690   if (Op0 == Op1) {
2691     switch (I.getPredicate()) {
2692     default: llvm_unreachable("Unknown predicate!");
2693     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
2694     case FCmpInst::FCMP_ULT:    // True if unordered or less than
2695     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
2696     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
2697       // Canonicalize these to be 'fcmp uno %X, 0.0'.
2698       I.setPredicate(FCmpInst::FCMP_UNO);
2699       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2700       return &I;
2701       
2702     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
2703     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
2704     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
2705     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
2706       // Canonicalize these to be 'fcmp ord %X, 0.0'.
2707       I.setPredicate(FCmpInst::FCMP_ORD);
2708       I.setOperand(1, Constant::getNullValue(Op0->getType()));
2709       return &I;
2710     }
2711   }
2712     
2713   // Handle fcmp with constant RHS
2714   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2715     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2716       switch (LHSI->getOpcode()) {
2717       case Instruction::PHI:
2718         // Only fold fcmp into the PHI if the phi and fcmp are in the same
2719         // block.  If in the same block, we're encouraging jump threading.  If
2720         // not, we are just pessimizing the code by making an i1 phi.
2721         if (LHSI->getParent() == I.getParent())
2722           if (Instruction *NV = FoldOpIntoPhi(I))
2723             return NV;
2724         break;
2725       case Instruction::SIToFP:
2726       case Instruction::UIToFP:
2727         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2728           return NV;
2729         break;
2730       case Instruction::Select: {
2731         // If either operand of the select is a constant, we can fold the
2732         // comparison into the select arms, which will cause one to be
2733         // constant folded and the select turned into a bitwise or.
2734         Value *Op1 = 0, *Op2 = 0;
2735         if (LHSI->hasOneUse()) {
2736           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2737             // Fold the known value into the constant operand.
2738             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2739             // Insert a new FCmp of the other select operand.
2740             Op2 = Builder->CreateFCmp(I.getPredicate(),
2741                                       LHSI->getOperand(2), RHSC, I.getName());
2742           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2743             // Fold the known value into the constant operand.
2744             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2745             // Insert a new FCmp of the other select operand.
2746             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2747                                       RHSC, I.getName());
2748           }
2749         }
2750
2751         if (Op1)
2752           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2753         break;
2754       }
2755       case Instruction::Load:
2756         if (GetElementPtrInst *GEP =
2757             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2758           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2759             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2760                 !cast<LoadInst>(LHSI)->isVolatile())
2761               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2762                 return Res;
2763         }
2764         break;
2765       }
2766   }
2767
2768   return Changed ? &I : 0;
2769 }