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