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