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