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