1 //===- InstCombineSelect.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 visitSelect function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/CmpInstAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/KnownBits.h"
41 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42 #include <cassert>
43 #include <utility>
44 
45 using namespace llvm;
46 using namespace PatternMatch;
47 
48 #define DEBUG_TYPE "instcombine"
49 
50 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
51                            SelectPatternFlavor SPF, Value *A, Value *B) {
52   CmpInst::Predicate Pred = getMinMaxPred(SPF);
53   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
54   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
55 }
56 
57 /// If one of the constants is zero (we know they can't both be) and we have an
58 /// icmp instruction with zero, and we have an 'and' with the non-constant value
59 /// and a power of two we can turn the select into a shift on the result of the
60 /// 'and'.
61 /// This folds:
62 ///  select (icmp eq (and X, C1)), C2, C3
63 ///    iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
64 /// To something like:
65 ///  (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
66 /// Or:
67 ///  (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
68 /// With some variations depending if C3 is larger than C2, or the shift
69 /// isn't needed, or the bit widths don't match.
70 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
71                                 APInt TrueVal, APInt FalseVal,
72                                 InstCombiner::BuilderTy &Builder) {
73   assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
74 
75   // If this is a vector select, we need a vector compare.
76   if (SelType->isVectorTy() != IC->getType()->isVectorTy())
77     return nullptr;
78 
79   Value *V;
80   APInt AndMask;
81   bool CreateAnd = false;
82   ICmpInst::Predicate Pred = IC->getPredicate();
83   if (ICmpInst::isEquality(Pred)) {
84     if (!match(IC->getOperand(1), m_Zero()))
85       return nullptr;
86 
87     V = IC->getOperand(0);
88 
89     const APInt *AndRHS;
90     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
91       return nullptr;
92 
93     AndMask = *AndRHS;
94   } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
95                                   Pred, V, AndMask)) {
96     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
97 
98     if (!AndMask.isPowerOf2())
99       return nullptr;
100 
101     CreateAnd = true;
102   } else {
103     return nullptr;
104   }
105 
106   // If both select arms are non-zero see if we have a select of the form
107   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
108   // for 'x ? 2^n : 0' and fix the thing up at the end.
109   APInt Offset(TrueVal.getBitWidth(), 0);
110   if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
111     if ((TrueVal - FalseVal).isPowerOf2())
112       Offset = FalseVal;
113     else if ((FalseVal - TrueVal).isPowerOf2())
114       Offset = TrueVal;
115     else
116       return nullptr;
117 
118     // Adjust TrueVal and FalseVal to the offset.
119     TrueVal -= Offset;
120     FalseVal -= Offset;
121   }
122 
123   // Make sure one of the select arms is a power of 2.
124   if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
125     return nullptr;
126 
127   // Determine which shift is needed to transform result of the 'and' into the
128   // desired result.
129   const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
130   unsigned ValZeros = ValC.logBase2();
131   unsigned AndZeros = AndMask.logBase2();
132 
133   if (CreateAnd) {
134     // Insert the AND instruction on the input to the truncate.
135     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
136   }
137 
138   // If types don't match we can still convert the select by introducing a zext
139   // or a trunc of the 'and'.
140   if (ValZeros > AndZeros) {
141     V = Builder.CreateZExtOrTrunc(V, SelType);
142     V = Builder.CreateShl(V, ValZeros - AndZeros);
143   } else if (ValZeros < AndZeros) {
144     V = Builder.CreateLShr(V, AndZeros - ValZeros);
145     V = Builder.CreateZExtOrTrunc(V, SelType);
146   } else
147     V = Builder.CreateZExtOrTrunc(V, SelType);
148 
149   // Okay, now we know that everything is set up, we just don't know whether we
150   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
151   bool ShouldNotVal = !TrueVal.isNullValue();
152   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
153   if (ShouldNotVal)
154     V = Builder.CreateXor(V, ValC);
155 
156   // Apply an offset if needed.
157   if (!Offset.isNullValue())
158     V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
159   return V;
160 }
161 
162 /// We want to turn code that looks like this:
163 ///   %C = or %A, %B
164 ///   %D = select %cond, %C, %A
165 /// into:
166 ///   %C = select %cond, %B, 0
167 ///   %D = or %A, %C
168 ///
169 /// Assuming that the specified instruction is an operand to the select, return
170 /// a bitmask indicating which operands of this instruction are foldable if they
171 /// equal the other incoming value of the select.
172 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
173   switch (I->getOpcode()) {
174   case Instruction::Add:
175   case Instruction::Mul:
176   case Instruction::And:
177   case Instruction::Or:
178   case Instruction::Xor:
179     return 3;              // Can fold through either operand.
180   case Instruction::Sub:   // Can only fold on the amount subtracted.
181   case Instruction::Shl:   // Can only fold on the shift amount.
182   case Instruction::LShr:
183   case Instruction::AShr:
184     return 1;
185   default:
186     return 0;              // Cannot fold
187   }
188 }
189 
190 /// For the same transformation as the previous function, return the identity
191 /// constant that goes into the select.
192 static APInt getSelectFoldableConstant(BinaryOperator *I) {
193   switch (I->getOpcode()) {
194   default: llvm_unreachable("This cannot happen!");
195   case Instruction::Add:
196   case Instruction::Sub:
197   case Instruction::Or:
198   case Instruction::Xor:
199   case Instruction::Shl:
200   case Instruction::LShr:
201   case Instruction::AShr:
202     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
203   case Instruction::And:
204     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
205   case Instruction::Mul:
206     return APInt(I->getType()->getScalarSizeInBits(), 1);
207   }
208 }
209 
210 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
211 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
212                                           Instruction *FI) {
213   // Don't break up min/max patterns. The hasOneUse checks below prevent that
214   // for most cases, but vector min/max with bitcasts can be transformed. If the
215   // one-use restrictions are eased for other patterns, we still don't want to
216   // obfuscate min/max.
217   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
218        match(&SI, m_SMax(m_Value(), m_Value())) ||
219        match(&SI, m_UMin(m_Value(), m_Value())) ||
220        match(&SI, m_UMax(m_Value(), m_Value()))))
221     return nullptr;
222 
223   // If this is a cast from the same type, merge.
224   if (TI->getNumOperands() == 1 && TI->isCast()) {
225     Type *FIOpndTy = FI->getOperand(0)->getType();
226     if (TI->getOperand(0)->getType() != FIOpndTy)
227       return nullptr;
228 
229     // The select condition may be a vector. We may only change the operand
230     // type if the vector width remains the same (and matches the condition).
231     Type *CondTy = SI.getCondition()->getType();
232     if (CondTy->isVectorTy()) {
233       if (!FIOpndTy->isVectorTy())
234         return nullptr;
235       if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
236         return nullptr;
237 
238       // TODO: If the backend knew how to deal with casts better, we could
239       // remove this limitation. For now, there's too much potential to create
240       // worse codegen by promoting the select ahead of size-altering casts
241       // (PR28160).
242       //
243       // Note that ValueTracking's matchSelectPattern() looks through casts
244       // without checking 'hasOneUse' when it matches min/max patterns, so this
245       // transform may end up happening anyway.
246       if (TI->getOpcode() != Instruction::BitCast &&
247           (!TI->hasOneUse() || !FI->hasOneUse()))
248         return nullptr;
249     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
250       // TODO: The one-use restrictions for a scalar select could be eased if
251       // the fold of a select in visitLoadInst() was enhanced to match a pattern
252       // that includes a cast.
253       return nullptr;
254     }
255 
256     // Fold this by inserting a select from the input values.
257     Value *NewSI =
258         Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
259                              FI->getOperand(0), SI.getName() + ".v", &SI);
260     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
261                             TI->getType());
262   }
263 
264   // Only handle binary operators (including two-operand getelementptr) with
265   // one-use here. As with the cast case above, it may be possible to relax the
266   // one-use constraint, but that needs be examined carefully since it may not
267   // reduce the total number of instructions.
268   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
269       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
270       !TI->hasOneUse() || !FI->hasOneUse())
271     return nullptr;
272 
273   // Figure out if the operations have any operands in common.
274   Value *MatchOp, *OtherOpT, *OtherOpF;
275   bool MatchIsOpZero;
276   if (TI->getOperand(0) == FI->getOperand(0)) {
277     MatchOp  = TI->getOperand(0);
278     OtherOpT = TI->getOperand(1);
279     OtherOpF = FI->getOperand(1);
280     MatchIsOpZero = true;
281   } else if (TI->getOperand(1) == FI->getOperand(1)) {
282     MatchOp  = TI->getOperand(1);
283     OtherOpT = TI->getOperand(0);
284     OtherOpF = FI->getOperand(0);
285     MatchIsOpZero = false;
286   } else if (!TI->isCommutative()) {
287     return nullptr;
288   } else if (TI->getOperand(0) == FI->getOperand(1)) {
289     MatchOp  = TI->getOperand(0);
290     OtherOpT = TI->getOperand(1);
291     OtherOpF = FI->getOperand(0);
292     MatchIsOpZero = true;
293   } else if (TI->getOperand(1) == FI->getOperand(0)) {
294     MatchOp  = TI->getOperand(1);
295     OtherOpT = TI->getOperand(0);
296     OtherOpF = FI->getOperand(1);
297     MatchIsOpZero = true;
298   } else {
299     return nullptr;
300   }
301 
302   // If we reach here, they do have operations in common.
303   Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
304                                       SI.getName() + ".v", &SI);
305   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
306   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
307   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
308     return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
309   }
310   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
311     auto *FGEP = cast<GetElementPtrInst>(FI);
312     Type *ElementType = TGEP->getResultElementType();
313     return TGEP->isInBounds() && FGEP->isInBounds()
314                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
315                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
316   }
317   llvm_unreachable("Expected BinaryOperator or GEP");
318   return nullptr;
319 }
320 
321 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
322   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
323     return false;
324   return C1I.isOneValue() || C1I.isAllOnesValue() ||
325          C2I.isOneValue() || C2I.isAllOnesValue();
326 }
327 
328 /// Try to fold the select into one of the operands to allow further
329 /// optimization.
330 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
331                                             Value *FalseVal) {
332   // See the comment above GetSelectFoldableOperands for a description of the
333   // transformation we are doing here.
334   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
335     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
336       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
337         unsigned OpToFold = 0;
338         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
339           OpToFold = 1;
340         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
341           OpToFold = 2;
342         }
343 
344         if (OpToFold) {
345           APInt CI = getSelectFoldableConstant(TVI);
346           Value *OOp = TVI->getOperand(2-OpToFold);
347           // Avoid creating select between 2 constants unless it's selecting
348           // between 0, 1 and -1.
349           const APInt *OOpC;
350           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
351           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
352             Value *C = ConstantInt::get(OOp->getType(), CI);
353             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
354             NewSel->takeName(TVI);
355             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
356                                                         FalseVal, NewSel);
357             BO->copyIRFlags(TVI);
358             return BO;
359           }
360         }
361       }
362     }
363   }
364 
365   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
366     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
367       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
368         unsigned OpToFold = 0;
369         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
370           OpToFold = 1;
371         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
372           OpToFold = 2;
373         }
374 
375         if (OpToFold) {
376           APInt CI = getSelectFoldableConstant(FVI);
377           Value *OOp = FVI->getOperand(2-OpToFold);
378           // Avoid creating select between 2 constants unless it's selecting
379           // between 0, 1 and -1.
380           const APInt *OOpC;
381           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
382           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
383             Value *C = ConstantInt::get(OOp->getType(), CI);
384             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
385             NewSel->takeName(FVI);
386             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
387                                                         TrueVal, NewSel);
388             BO->copyIRFlags(FVI);
389             return BO;
390           }
391         }
392       }
393     }
394   }
395 
396   return nullptr;
397 }
398 
399 /// We want to turn:
400 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
401 /// into:
402 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
403 /// Note:
404 ///   Z may be 0 if lshr is missing.
405 /// Worst case scenario is that we will replace 5 instructions with 5 different
406 /// instructions, but we got rid of select.
407 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *IC,
408                                          Value *TrueVal, Value *FalseVal,
409                                          InstCombiner::BuilderTy &Builder) {
410   if (!(IC->hasOneUse() && IC->getOperand(0)->hasOneUse()))
411     return nullptr;
412 
413   Value *X, *Y;
414   ICmpInst::Predicate EqPred;
415   if (!(match(IC, m_ICmp(EqPred, m_And(m_Value(X), m_Value(Y)), m_Zero())) &&
416         ICmpInst::Predicate::ICMP_EQ == EqPred && match(FalseVal, m_One())))
417     return nullptr;
418 
419   // The TrueVal has general form of:
420   //   and %B, 1
421   Value *B;
422   if (!match(TrueVal, m_OneUse(m_And(m_Value(B), m_One()))))
423     return nullptr;
424 
425   // Where %B can be one of:
426   //        %X
427   // or
428   //   lshr %X, %Z
429   // Where %Z may or may not be a constant.
430   Value *MaskB, *Z;
431   if (match(B, m_Specific(X))) {
432     MaskB = ConstantInt::get(SelType, 1);
433   } else if (match(B, m_OneUse(m_LShr(m_Specific(X), m_Value(Z))))) {
434     MaskB = Builder.CreateShl(ConstantInt::get(SelType, 1), Z);
435   } else
436     return nullptr;
437 
438   Value *FullMask = Builder.CreateOr(Y, MaskB);
439   Value *MaskedX = Builder.CreateAnd(X, FullMask);
440   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
441   return new ZExtInst(ICmpNeZero, SelType);
442 }
443 
444 /// We want to turn:
445 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
446 /// into:
447 ///   (or (shl (and X, C1), C3), Y)
448 /// iff:
449 ///   C1 and C2 are both powers of 2
450 /// where:
451 ///   C3 = Log(C2) - Log(C1)
452 ///
453 /// This transform handles cases where:
454 /// 1. The icmp predicate is inverted
455 /// 2. The select operands are reversed
456 /// 3. The magnitude of C2 and C1 are flipped
457 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
458                                   Value *FalseVal,
459                                   InstCombiner::BuilderTy &Builder) {
460   // Only handle integer compares. Also, if this is a vector select, we need a
461   // vector compare.
462   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
463       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
464     return nullptr;
465 
466   Value *CmpLHS = IC->getOperand(0);
467   Value *CmpRHS = IC->getOperand(1);
468 
469   Value *V;
470   unsigned C1Log;
471   bool IsEqualZero;
472   bool NeedAnd = false;
473   if (IC->isEquality()) {
474     if (!match(CmpRHS, m_Zero()))
475       return nullptr;
476 
477     const APInt *C1;
478     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
479       return nullptr;
480 
481     V = CmpLHS;
482     C1Log = C1->logBase2();
483     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
484   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
485              IC->getPredicate() == ICmpInst::ICMP_SGT) {
486     // We also need to recognize (icmp slt (trunc (X)), 0) and
487     // (icmp sgt (trunc (X)), -1).
488     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
489     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
490         (!IsEqualZero && !match(CmpRHS, m_Zero())))
491       return nullptr;
492 
493     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
494       return nullptr;
495 
496     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
497     NeedAnd = true;
498   } else {
499     return nullptr;
500   }
501 
502   const APInt *C2;
503   bool OrOnTrueVal = false;
504   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
505   if (!OrOnFalseVal)
506     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
507 
508   if (!OrOnFalseVal && !OrOnTrueVal)
509     return nullptr;
510 
511   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
512 
513   unsigned C2Log = C2->logBase2();
514 
515   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
516   bool NeedShift = C1Log != C2Log;
517   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
518                        V->getType()->getScalarSizeInBits();
519 
520   // Make sure we don't create more instructions than we save.
521   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
522   if ((NeedShift + NeedXor + NeedZExtTrunc) >
523       (IC->hasOneUse() + Or->hasOneUse()))
524     return nullptr;
525 
526   if (NeedAnd) {
527     // Insert the AND instruction on the input to the truncate.
528     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
529     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
530   }
531 
532   if (C2Log > C1Log) {
533     V = Builder.CreateZExtOrTrunc(V, Y->getType());
534     V = Builder.CreateShl(V, C2Log - C1Log);
535   } else if (C1Log > C2Log) {
536     V = Builder.CreateLShr(V, C1Log - C2Log);
537     V = Builder.CreateZExtOrTrunc(V, Y->getType());
538   } else
539     V = Builder.CreateZExtOrTrunc(V, Y->getType());
540 
541   if (NeedXor)
542     V = Builder.CreateXor(V, *C2);
543 
544   return Builder.CreateOr(V, Y);
545 }
546 
547 /// Transform patterns such as: (a > b) ? a - b : 0
548 /// into: ((a > b) ? a : b) - b)
549 /// This produces a canonical max pattern that is more easily recognized by the
550 /// backend and converted into saturated subtraction instructions if those
551 /// exist.
552 /// There are 8 commuted/swapped variants of this pattern.
553 /// TODO: Also support a - UMIN(a,b) patterns.
554 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
555                                             const Value *TrueVal,
556                                             const Value *FalseVal,
557                                             InstCombiner::BuilderTy &Builder) {
558   ICmpInst::Predicate Pred = ICI->getPredicate();
559   if (!ICmpInst::isUnsigned(Pred))
560     return nullptr;
561 
562   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
563   if (match(TrueVal, m_Zero())) {
564     Pred = ICmpInst::getInversePredicate(Pred);
565     std::swap(TrueVal, FalseVal);
566   }
567   if (!match(FalseVal, m_Zero()))
568     return nullptr;
569 
570   Value *A = ICI->getOperand(0);
571   Value *B = ICI->getOperand(1);
572   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
573     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
574     std::swap(A, B);
575     Pred = ICmpInst::getSwappedPredicate(Pred);
576   }
577 
578   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
579          "Unexpected isUnsigned predicate!");
580 
581   // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
582   bool IsNegative = false;
583   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
584     IsNegative = true;
585   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
586     return nullptr;
587 
588   // If sub is used anywhere else, we wouldn't be able to eliminate it
589   // afterwards.
590   if (!TrueVal->hasOneUse())
591     return nullptr;
592 
593   // All checks passed, convert to canonical unsigned saturated subtraction
594   // form: sub(max()).
595   // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
596   Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
597   return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
598 }
599 
600 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
601 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
602 ///
603 /// For example, we can fold the following code sequence:
604 /// \code
605 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
606 ///   %1 = icmp ne i32 %x, 0
607 ///   %2 = select i1 %1, i32 %0, i32 32
608 /// \code
609 ///
610 /// into:
611 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
612 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
613                                  InstCombiner::BuilderTy &Builder) {
614   ICmpInst::Predicate Pred = ICI->getPredicate();
615   Value *CmpLHS = ICI->getOperand(0);
616   Value *CmpRHS = ICI->getOperand(1);
617 
618   // Check if the condition value compares a value for equality against zero.
619   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
620     return nullptr;
621 
622   Value *Count = FalseVal;
623   Value *ValueOnZero = TrueVal;
624   if (Pred == ICmpInst::ICMP_NE)
625     std::swap(Count, ValueOnZero);
626 
627   // Skip zero extend/truncate.
628   Value *V = nullptr;
629   if (match(Count, m_ZExt(m_Value(V))) ||
630       match(Count, m_Trunc(m_Value(V))))
631     Count = V;
632 
633   // Check if the value propagated on zero is a constant number equal to the
634   // sizeof in bits of 'Count'.
635   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
636   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
637     return nullptr;
638 
639   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
640   // input to the cttz/ctlz is used as LHS for the compare instruction.
641   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
642       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
643     IntrinsicInst *II = cast<IntrinsicInst>(Count);
644     // Explicitly clear the 'undef_on_zero' flag.
645     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
646     NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
647     Builder.Insert(NewI);
648     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
649   }
650 
651   return nullptr;
652 }
653 
654 /// Return true if we find and adjust an icmp+select pattern where the compare
655 /// is with a constant that can be incremented or decremented to match the
656 /// minimum or maximum idiom.
657 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
658   ICmpInst::Predicate Pred = Cmp.getPredicate();
659   Value *CmpLHS = Cmp.getOperand(0);
660   Value *CmpRHS = Cmp.getOperand(1);
661   Value *TrueVal = Sel.getTrueValue();
662   Value *FalseVal = Sel.getFalseValue();
663 
664   // We may move or edit the compare, so make sure the select is the only user.
665   const APInt *CmpC;
666   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
667     return false;
668 
669   // These transforms only work for selects of integers or vector selects of
670   // integer vectors.
671   Type *SelTy = Sel.getType();
672   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
673   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
674     return false;
675 
676   Constant *AdjustedRHS;
677   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
678     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
679   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
680     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
681   else
682     return false;
683 
684   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
685   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
686   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
687       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
688     ; // Nothing to do here. Values match without any sign/zero extension.
689   }
690   // Types do not match. Instead of calculating this with mixed types, promote
691   // all to the larger type. This enables scalar evolution to analyze this
692   // expression.
693   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
694     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
695 
696     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
697     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
698     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
699     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
700     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
701       CmpLHS = TrueVal;
702       AdjustedRHS = SextRHS;
703     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
704                SextRHS == TrueVal) {
705       CmpLHS = FalseVal;
706       AdjustedRHS = SextRHS;
707     } else if (Cmp.isUnsigned()) {
708       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
709       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
710       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
711       // zext + signed compare cannot be changed:
712       //    0xff <s 0x00, but 0x00ff >s 0x0000
713       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
714         CmpLHS = TrueVal;
715         AdjustedRHS = ZextRHS;
716       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
717                  ZextRHS == TrueVal) {
718         CmpLHS = FalseVal;
719         AdjustedRHS = ZextRHS;
720       } else {
721         return false;
722       }
723     } else {
724       return false;
725     }
726   } else {
727     return false;
728   }
729 
730   Pred = ICmpInst::getSwappedPredicate(Pred);
731   CmpRHS = AdjustedRHS;
732   std::swap(FalseVal, TrueVal);
733   Cmp.setPredicate(Pred);
734   Cmp.setOperand(0, CmpLHS);
735   Cmp.setOperand(1, CmpRHS);
736   Sel.setOperand(1, TrueVal);
737   Sel.setOperand(2, FalseVal);
738   Sel.swapProfMetadata();
739 
740   // Move the compare instruction right before the select instruction. Otherwise
741   // the sext/zext value may be defined after the compare instruction uses it.
742   Cmp.moveBefore(&Sel);
743 
744   return true;
745 }
746 
747 /// If this is an integer min/max (icmp + select) with a constant operand,
748 /// create the canonical icmp for the min/max operation and canonicalize the
749 /// constant to the 'false' operand of the select:
750 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
751 /// Note: if C1 != C2, this will change the icmp constant to the existing
752 /// constant operand of the select.
753 static Instruction *
754 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
755                                InstCombiner::BuilderTy &Builder) {
756   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
757     return nullptr;
758 
759   // Canonicalize the compare predicate based on whether we have min or max.
760   Value *LHS, *RHS;
761   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
762   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
763     return nullptr;
764 
765   // Is this already canonical?
766   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
767   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
768       Cmp.getPredicate() == CanonicalPred)
769     return nullptr;
770 
771   // Create the canonical compare and plug it into the select.
772   Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
773 
774   // If the select operands did not change, we're done.
775   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
776     return &Sel;
777 
778   // If we are swapping the select operands, swap the metadata too.
779   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
780          "Unexpected results from matchSelectPattern");
781   Sel.setTrueValue(LHS);
782   Sel.setFalseValue(RHS);
783   Sel.swapProfMetadata();
784   return &Sel;
785 }
786 
787 /// Visit a SelectInst that has an ICmpInst as its first operand.
788 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
789                                                   ICmpInst *ICI) {
790   Value *TrueVal = SI.getTrueValue();
791   Value *FalseVal = SI.getFalseValue();
792 
793   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
794     return NewSel;
795 
796   bool Changed = adjustMinMax(SI, *ICI);
797 
798   ICmpInst::Predicate Pred = ICI->getPredicate();
799   Value *CmpLHS = ICI->getOperand(0);
800   Value *CmpRHS = ICI->getOperand(1);
801 
802   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
803   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
804   // FIXME: Type and constness constraints could be lifted, but we have to
805   //        watch code size carefully. We should consider xor instead of
806   //        sub/add when we decide to do that.
807   // TODO: Merge this with foldSelectICmpAnd somehow.
808   if (CmpLHS->getType()->isIntOrIntVectorTy() &&
809       CmpLHS->getType() == TrueVal->getType()) {
810     const APInt *C1, *C2;
811     if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
812       ICmpInst::Predicate Pred = ICI->getPredicate();
813       Value *X;
814       APInt Mask;
815       if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
816         if (Mask.isSignMask()) {
817           assert(X == CmpLHS && "Expected to use the compare input directly");
818           assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
819 
820           if (Pred == ICmpInst::ICMP_NE)
821             std::swap(C1, C2);
822 
823           // This shift results in either -1 or 0.
824           Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
825 
826           // Check if we can express the operation with a single or.
827           if (C2->isAllOnesValue())
828             return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
829 
830           Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
831           return replaceInstUsesWith(SI, Builder.CreateAdd(And,
832                                         ConstantInt::get(And->getType(), *C1)));
833         }
834       }
835     }
836   }
837 
838   {
839     const APInt *TrueValC, *FalseValC;
840     if (match(TrueVal, m_APInt(TrueValC)) &&
841         match(FalseVal, m_APInt(FalseValC)))
842       if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
843                                        *FalseValC, Builder))
844         return replaceInstUsesWith(SI, V);
845   }
846 
847   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
848 
849   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
850     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
851       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
852       SI.setOperand(1, CmpRHS);
853       Changed = true;
854     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
855       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
856       SI.setOperand(2, CmpRHS);
857       Changed = true;
858     }
859   }
860 
861   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
862   // decomposeBitTestICmp() might help.
863   {
864     unsigned BitWidth =
865         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
866     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
867     Value *X;
868     const APInt *Y, *C;
869     bool TrueWhenUnset;
870     bool IsBitTest = false;
871     if (ICmpInst::isEquality(Pred) &&
872         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
873         match(CmpRHS, m_Zero())) {
874       IsBitTest = true;
875       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
876     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
877       X = CmpLHS;
878       Y = &MinSignedValue;
879       IsBitTest = true;
880       TrueWhenUnset = false;
881     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
882       X = CmpLHS;
883       Y = &MinSignedValue;
884       IsBitTest = true;
885       TrueWhenUnset = true;
886     }
887     if (IsBitTest) {
888       Value *V = nullptr;
889       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
890       if (TrueWhenUnset && TrueVal == X &&
891           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
892         V = Builder.CreateAnd(X, ~(*Y));
893       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
894       else if (!TrueWhenUnset && FalseVal == X &&
895                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
896         V = Builder.CreateAnd(X, ~(*Y));
897       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
898       else if (TrueWhenUnset && FalseVal == X &&
899                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
900         V = Builder.CreateOr(X, *Y);
901       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
902       else if (!TrueWhenUnset && TrueVal == X &&
903                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
904         V = Builder.CreateOr(X, *Y);
905 
906       if (V)
907         return replaceInstUsesWith(SI, V);
908     }
909   }
910 
911   if (Instruction *V =
912           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
913     return V;
914 
915   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
916     return replaceInstUsesWith(SI, V);
917 
918   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
919     return replaceInstUsesWith(SI, V);
920 
921   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
922     return replaceInstUsesWith(SI, V);
923 
924   return Changed ? &SI : nullptr;
925 }
926 
927 /// SI is a select whose condition is a PHI node (but the two may be in
928 /// different blocks). See if the true/false values (V) are live in all of the
929 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
930 ///
931 ///   X = phi [ C1, BB1], [C2, BB2]
932 ///   Y = add
933 ///   Z = select X, Y, 0
934 ///
935 /// because Y is not live in BB1/BB2.
936 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
937                                                    const SelectInst &SI) {
938   // If the value is a non-instruction value like a constant or argument, it
939   // can always be mapped.
940   const Instruction *I = dyn_cast<Instruction>(V);
941   if (!I) return true;
942 
943   // If V is a PHI node defined in the same block as the condition PHI, we can
944   // map the arguments.
945   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
946 
947   if (const PHINode *VP = dyn_cast<PHINode>(I))
948     if (VP->getParent() == CondPHI->getParent())
949       return true;
950 
951   // Otherwise, if the PHI and select are defined in the same block and if V is
952   // defined in a different block, then we can transform it.
953   if (SI.getParent() == CondPHI->getParent() &&
954       I->getParent() != CondPHI->getParent())
955     return true;
956 
957   // Otherwise we have a 'hard' case and we can't tell without doing more
958   // detailed dominator based analysis, punt.
959   return false;
960 }
961 
962 /// We have an SPF (e.g. a min or max) of an SPF of the form:
963 ///   SPF2(SPF1(A, B), C)
964 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
965                                         SelectPatternFlavor SPF1,
966                                         Value *A, Value *B,
967                                         Instruction &Outer,
968                                         SelectPatternFlavor SPF2, Value *C) {
969   if (Outer.getType() != Inner->getType())
970     return nullptr;
971 
972   if (C == A || C == B) {
973     // MAX(MAX(A, B), B) -> MAX(A, B)
974     // MIN(MIN(a, b), a) -> MIN(a, b)
975     if (SPF1 == SPF2)
976       return replaceInstUsesWith(Outer, Inner);
977 
978     // MAX(MIN(a, b), a) -> a
979     // MIN(MAX(a, b), a) -> a
980     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
981         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
982         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
983         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
984       return replaceInstUsesWith(Outer, C);
985   }
986 
987   if (SPF1 == SPF2) {
988     const APInt *CB, *CC;
989     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
990       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
991       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
992       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
993           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
994           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
995           (SPF1 == SPF_SMAX && CB->sge(*CC)))
996         return replaceInstUsesWith(Outer, Inner);
997 
998       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
999       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1000       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1001           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1002           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1003           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1004         Outer.replaceUsesOfWith(Inner, A);
1005         return &Outer;
1006       }
1007     }
1008   }
1009 
1010   // ABS(ABS(X)) -> ABS(X)
1011   // NABS(NABS(X)) -> NABS(X)
1012   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1013     return replaceInstUsesWith(Outer, Inner);
1014   }
1015 
1016   // ABS(NABS(X)) -> ABS(X)
1017   // NABS(ABS(X)) -> NABS(X)
1018   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1019       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1020     SelectInst *SI = cast<SelectInst>(Inner);
1021     Value *NewSI =
1022         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1023                              SI->getTrueValue(), SI->getName(), SI);
1024     return replaceInstUsesWith(Outer, NewSI);
1025   }
1026 
1027   auto IsFreeOrProfitableToInvert =
1028       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1029     if (match(V, m_Not(m_Value(NotV)))) {
1030       // If V has at most 2 uses then we can get rid of the xor operation
1031       // entirely.
1032       ElidesXor |= !V->hasNUsesOrMore(3);
1033       return true;
1034     }
1035 
1036     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1037       NotV = nullptr;
1038       return true;
1039     }
1040 
1041     return false;
1042   };
1043 
1044   Value *NotA, *NotB, *NotC;
1045   bool ElidesXor = false;
1046 
1047   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1048   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1049   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1050   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1051   //
1052   // This transform is performance neutral if we can elide at least one xor from
1053   // the set of three operands, since we'll be tacking on an xor at the very
1054   // end.
1055   if (SelectPatternResult::isMinOrMax(SPF1) &&
1056       SelectPatternResult::isMinOrMax(SPF2) &&
1057       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1058       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1059       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1060     if (!NotA)
1061       NotA = Builder.CreateNot(A);
1062     if (!NotB)
1063       NotB = Builder.CreateNot(B);
1064     if (!NotC)
1065       NotC = Builder.CreateNot(C);
1066 
1067     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1068                                    NotB);
1069     Value *NewOuter = Builder.CreateNot(
1070         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1071     return replaceInstUsesWith(Outer, NewOuter);
1072   }
1073 
1074   return nullptr;
1075 }
1076 
1077 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1078 /// This is even legal for FP.
1079 static Instruction *foldAddSubSelect(SelectInst &SI,
1080                                      InstCombiner::BuilderTy &Builder) {
1081   Value *CondVal = SI.getCondition();
1082   Value *TrueVal = SI.getTrueValue();
1083   Value *FalseVal = SI.getFalseValue();
1084   auto *TI = dyn_cast<Instruction>(TrueVal);
1085   auto *FI = dyn_cast<Instruction>(FalseVal);
1086   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1087     return nullptr;
1088 
1089   Instruction *AddOp = nullptr, *SubOp = nullptr;
1090   if ((TI->getOpcode() == Instruction::Sub &&
1091        FI->getOpcode() == Instruction::Add) ||
1092       (TI->getOpcode() == Instruction::FSub &&
1093        FI->getOpcode() == Instruction::FAdd)) {
1094     AddOp = FI;
1095     SubOp = TI;
1096   } else if ((FI->getOpcode() == Instruction::Sub &&
1097               TI->getOpcode() == Instruction::Add) ||
1098              (FI->getOpcode() == Instruction::FSub &&
1099               TI->getOpcode() == Instruction::FAdd)) {
1100     AddOp = TI;
1101     SubOp = FI;
1102   }
1103 
1104   if (AddOp) {
1105     Value *OtherAddOp = nullptr;
1106     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1107       OtherAddOp = AddOp->getOperand(1);
1108     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1109       OtherAddOp = AddOp->getOperand(0);
1110     }
1111 
1112     if (OtherAddOp) {
1113       // So at this point we know we have (Y -> OtherAddOp):
1114       //        select C, (add X, Y), (sub X, Z)
1115       Value *NegVal; // Compute -Z
1116       if (SI.getType()->isFPOrFPVectorTy()) {
1117         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1118         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1119           FastMathFlags Flags = AddOp->getFastMathFlags();
1120           Flags &= SubOp->getFastMathFlags();
1121           NegInst->setFastMathFlags(Flags);
1122         }
1123       } else {
1124         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1125       }
1126 
1127       Value *NewTrueOp = OtherAddOp;
1128       Value *NewFalseOp = NegVal;
1129       if (AddOp != TI)
1130         std::swap(NewTrueOp, NewFalseOp);
1131       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1132                                            SI.getName() + ".p", &SI);
1133 
1134       if (SI.getType()->isFPOrFPVectorTy()) {
1135         Instruction *RI =
1136             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1137 
1138         FastMathFlags Flags = AddOp->getFastMathFlags();
1139         Flags &= SubOp->getFastMathFlags();
1140         RI->setFastMathFlags(Flags);
1141         return RI;
1142       } else
1143         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1144     }
1145   }
1146   return nullptr;
1147 }
1148 
1149 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1150   Instruction *ExtInst;
1151   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1152       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1153     return nullptr;
1154 
1155   auto ExtOpcode = ExtInst->getOpcode();
1156   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1157     return nullptr;
1158 
1159   // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1160   Value *X = ExtInst->getOperand(0);
1161   Type *SmallType = X->getType();
1162   if (!SmallType->isIntOrIntVectorTy(1))
1163     return nullptr;
1164 
1165   Constant *C;
1166   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1167       !match(Sel.getFalseValue(), m_Constant(C)))
1168     return nullptr;
1169 
1170   // If the constant is the same after truncation to the smaller type and
1171   // extension to the original type, we can narrow the select.
1172   Value *Cond = Sel.getCondition();
1173   Type *SelType = Sel.getType();
1174   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1175   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1176   if (ExtC == C) {
1177     Value *TruncCVal = cast<Value>(TruncC);
1178     if (ExtInst == Sel.getFalseValue())
1179       std::swap(X, TruncCVal);
1180 
1181     // select Cond, (ext X), C --> ext(select Cond, X, C')
1182     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1183     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1184     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1185   }
1186 
1187   // If one arm of the select is the extend of the condition, replace that arm
1188   // with the extension of the appropriate known bool value.
1189   if (Cond == X) {
1190     if (ExtInst == Sel.getTrueValue()) {
1191       // select X, (sext X), C --> select X, -1, C
1192       // select X, (zext X), C --> select X,  1, C
1193       Constant *One = ConstantInt::getTrue(SmallType);
1194       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1195       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1196     } else {
1197       // select X, C, (sext X) --> select X, C, 0
1198       // select X, C, (zext X) --> select X, C, 0
1199       Constant *Zero = ConstantInt::getNullValue(SelType);
1200       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1201     }
1202   }
1203 
1204   return nullptr;
1205 }
1206 
1207 /// Try to transform a vector select with a constant condition vector into a
1208 /// shuffle for easier combining with other shuffles and insert/extract.
1209 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1210   Value *CondVal = SI.getCondition();
1211   Constant *CondC;
1212   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1213     return nullptr;
1214 
1215   unsigned NumElts = CondVal->getType()->getVectorNumElements();
1216   SmallVector<Constant *, 16> Mask;
1217   Mask.reserve(NumElts);
1218   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1219   for (unsigned i = 0; i != NumElts; ++i) {
1220     Constant *Elt = CondC->getAggregateElement(i);
1221     if (!Elt)
1222       return nullptr;
1223 
1224     if (Elt->isOneValue()) {
1225       // If the select condition element is true, choose from the 1st vector.
1226       Mask.push_back(ConstantInt::get(Int32Ty, i));
1227     } else if (Elt->isNullValue()) {
1228       // If the select condition element is false, choose from the 2nd vector.
1229       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1230     } else if (isa<UndefValue>(Elt)) {
1231       // Undef in a select condition (choose one of the operands) does not mean
1232       // the same thing as undef in a shuffle mask (any value is acceptable), so
1233       // give up.
1234       return nullptr;
1235     } else {
1236       // Bail out on a constant expression.
1237       return nullptr;
1238     }
1239   }
1240 
1241   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1242                                ConstantVector::get(Mask));
1243 }
1244 
1245 /// Reuse bitcasted operands between a compare and select:
1246 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1247 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1248 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1249                                           InstCombiner::BuilderTy &Builder) {
1250   Value *Cond = Sel.getCondition();
1251   Value *TVal = Sel.getTrueValue();
1252   Value *FVal = Sel.getFalseValue();
1253 
1254   CmpInst::Predicate Pred;
1255   Value *A, *B;
1256   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1257     return nullptr;
1258 
1259   // The select condition is a compare instruction. If the select's true/false
1260   // values are already the same as the compare operands, there's nothing to do.
1261   if (TVal == A || TVal == B || FVal == A || FVal == B)
1262     return nullptr;
1263 
1264   Value *C, *D;
1265   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1266     return nullptr;
1267 
1268   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1269   Value *TSrc, *FSrc;
1270   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1271       !match(FVal, m_BitCast(m_Value(FSrc))))
1272     return nullptr;
1273 
1274   // If the select true/false values are *different bitcasts* of the same source
1275   // operands, make the select operands the same as the compare operands and
1276   // cast the result. This is the canonical select form for min/max.
1277   Value *NewSel;
1278   if (TSrc == C && FSrc == D) {
1279     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1280     // bitcast (select (cmp A, B), A, B)
1281     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1282   } else if (TSrc == D && FSrc == C) {
1283     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1284     // bitcast (select (cmp A, B), B, A)
1285     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1286   } else {
1287     return nullptr;
1288   }
1289   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1290 }
1291 
1292 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1293 /// instructions.
1294 ///
1295 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1296 /// selects between the returned value of the cmpxchg instruction its compare
1297 /// operand, the result of the select will always be equal to its false value.
1298 /// For example:
1299 ///
1300 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1301 ///   %1 = extractvalue { i64, i1 } %0, 1
1302 ///   %2 = extractvalue { i64, i1 } %0, 0
1303 ///   %3 = select i1 %1, i64 %compare, i64 %2
1304 ///   ret i64 %3
1305 ///
1306 /// The returned value of the cmpxchg instruction (%2) is the original value
1307 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1308 /// must have been equal to %compare. Thus, the result of the select is always
1309 /// equal to %2, and the code can be simplified to:
1310 ///
1311 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1312 ///   %1 = extractvalue { i64, i1 } %0, 0
1313 ///   ret i64 %1
1314 ///
1315 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1316   // A helper that determines if V is an extractvalue instruction whose
1317   // aggregate operand is a cmpxchg instruction and whose single index is equal
1318   // to I. If such conditions are true, the helper returns the cmpxchg
1319   // instruction; otherwise, a nullptr is returned.
1320   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1321     auto *Extract = dyn_cast<ExtractValueInst>(V);
1322     if (!Extract)
1323       return nullptr;
1324     if (Extract->getIndices()[0] != I)
1325       return nullptr;
1326     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1327   };
1328 
1329   // If the select has a single user, and this user is a select instruction that
1330   // we can simplify, skip the cmpxchg simplification for now.
1331   if (SI.hasOneUse())
1332     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1333       if (Select->getCondition() == SI.getCondition())
1334         if (Select->getFalseValue() == SI.getTrueValue() ||
1335             Select->getTrueValue() == SI.getFalseValue())
1336           return nullptr;
1337 
1338   // Ensure the select condition is the returned flag of a cmpxchg instruction.
1339   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1340   if (!CmpXchg)
1341     return nullptr;
1342 
1343   // Check the true value case: The true value of the select is the returned
1344   // value of the same cmpxchg used by the condition, and the false value is the
1345   // cmpxchg instruction's compare operand.
1346   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1347     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1348       SI.setTrueValue(SI.getFalseValue());
1349       return &SI;
1350     }
1351 
1352   // Check the false value case: The false value of the select is the returned
1353   // value of the same cmpxchg used by the condition, and the true value is the
1354   // cmpxchg instruction's compare operand.
1355   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1356     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1357       SI.setTrueValue(SI.getFalseValue());
1358       return &SI;
1359     }
1360 
1361   return nullptr;
1362 }
1363 
1364 /// Reduce a sequence of min/max with a common operand.
1365 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1366                                         Value *RHS,
1367                                         InstCombiner::BuilderTy &Builder) {
1368   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1369   // TODO: Allow FP min/max with nnan/nsz.
1370   if (!LHS->getType()->isIntOrIntVectorTy())
1371     return nullptr;
1372 
1373   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1374   Value *A, *B, *C, *D;
1375   SelectPatternResult L = matchSelectPattern(LHS, A, B);
1376   SelectPatternResult R = matchSelectPattern(RHS, C, D);
1377   if (SPF != L.Flavor || L.Flavor != R.Flavor)
1378     return nullptr;
1379 
1380   // Look for a common operand. The use checks are different than usual because
1381   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1382   // the select.
1383   Value *MinMaxOp = nullptr;
1384   Value *ThirdOp = nullptr;
1385   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
1386     // If the LHS is only used in this chain and the RHS is used outside of it,
1387     // reuse the RHS min/max because that will eliminate the LHS.
1388     if (D == A || C == A) {
1389       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1390       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1391       MinMaxOp = RHS;
1392       ThirdOp = B;
1393     } else if (D == B || C == B) {
1394       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1395       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1396       MinMaxOp = RHS;
1397       ThirdOp = A;
1398     }
1399   } else if (!RHS->hasNUsesOrMore(3)) {
1400     // Reuse the LHS. This will eliminate the RHS.
1401     if (D == A || D == B) {
1402       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1403       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1404       MinMaxOp = LHS;
1405       ThirdOp = C;
1406     } else if (C == A || C == B) {
1407       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1408       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1409       MinMaxOp = LHS;
1410       ThirdOp = D;
1411     }
1412   }
1413   if (!MinMaxOp || !ThirdOp)
1414     return nullptr;
1415 
1416   CmpInst::Predicate P = getMinMaxPred(SPF);
1417   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1418   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1419 }
1420 
1421 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1422   Value *CondVal = SI.getCondition();
1423   Value *TrueVal = SI.getTrueValue();
1424   Value *FalseVal = SI.getFalseValue();
1425   Type *SelType = SI.getType();
1426 
1427   // FIXME: Remove this workaround when freeze related patches are done.
1428   // For select with undef operand which feeds into an equality comparison,
1429   // don't simplify it so loop unswitch can know the equality comparison
1430   // may have an undef operand. This is a workaround for PR31652 caused by
1431   // descrepancy about branch on undef between LoopUnswitch and GVN.
1432   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1433     if (llvm::any_of(SI.users(), [&](User *U) {
1434           ICmpInst *CI = dyn_cast<ICmpInst>(U);
1435           if (CI && CI->isEquality())
1436             return true;
1437           return false;
1438         })) {
1439       return nullptr;
1440     }
1441   }
1442 
1443   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1444                                     SQ.getWithInstruction(&SI)))
1445     return replaceInstUsesWith(SI, V);
1446 
1447   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1448     return I;
1449 
1450   // Canonicalize a one-use integer compare with a non-canonical predicate by
1451   // inverting the predicate and swapping the select operands. This matches a
1452   // compare canonicalization for conditional branches.
1453   // TODO: Should we do the same for FP compares?
1454   CmpInst::Predicate Pred;
1455   if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1456       !isCanonicalPredicate(Pred)) {
1457     // Swap true/false values and condition.
1458     CmpInst *Cond = cast<CmpInst>(CondVal);
1459     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1460     SI.setOperand(1, FalseVal);
1461     SI.setOperand(2, TrueVal);
1462     SI.swapProfMetadata();
1463     Worklist.Add(Cond);
1464     return &SI;
1465   }
1466 
1467   if (SelType->isIntOrIntVectorTy(1) &&
1468       TrueVal->getType() == CondVal->getType()) {
1469     if (match(TrueVal, m_One())) {
1470       // Change: A = select B, true, C --> A = or B, C
1471       return BinaryOperator::CreateOr(CondVal, FalseVal);
1472     }
1473     if (match(TrueVal, m_Zero())) {
1474       // Change: A = select B, false, C --> A = and !B, C
1475       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1476       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1477     }
1478     if (match(FalseVal, m_Zero())) {
1479       // Change: A = select B, C, false --> A = and B, C
1480       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1481     }
1482     if (match(FalseVal, m_One())) {
1483       // Change: A = select B, C, true --> A = or !B, C
1484       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1485       return BinaryOperator::CreateOr(NotCond, TrueVal);
1486     }
1487 
1488     // select a, a, b  -> a | b
1489     // select a, b, a  -> a & b
1490     if (CondVal == TrueVal)
1491       return BinaryOperator::CreateOr(CondVal, FalseVal);
1492     if (CondVal == FalseVal)
1493       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1494 
1495     // select a, ~a, b -> (~a) & b
1496     // select a, b, ~a -> (~a) | b
1497     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1498       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1499     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1500       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1501   }
1502 
1503   // Selecting between two integer or vector splat integer constants?
1504   //
1505   // Note that we don't handle a scalar select of vectors:
1506   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1507   // because that may need 3 instructions to splat the condition value:
1508   // extend, insertelement, shufflevector.
1509   if (SelType->isIntOrIntVectorTy() &&
1510       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1511     // select C, 1, 0 -> zext C to int
1512     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1513       return new ZExtInst(CondVal, SelType);
1514 
1515     // select C, -1, 0 -> sext C to int
1516     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1517       return new SExtInst(CondVal, SelType);
1518 
1519     // select C, 0, 1 -> zext !C to int
1520     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1521       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1522       return new ZExtInst(NotCond, SelType);
1523     }
1524 
1525     // select C, 0, -1 -> sext !C to int
1526     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1527       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1528       return new SExtInst(NotCond, SelType);
1529     }
1530   }
1531 
1532   // See if we are selecting two values based on a comparison of the two values.
1533   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1534     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1535       // Transform (X == Y) ? X : Y  -> Y
1536       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1537         // This is not safe in general for floating point:
1538         // consider X== -0, Y== +0.
1539         // It becomes safe if either operand is a nonzero constant.
1540         ConstantFP *CFPt, *CFPf;
1541         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1542               !CFPt->getValueAPF().isZero()) ||
1543             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1544              !CFPf->getValueAPF().isZero()))
1545         return replaceInstUsesWith(SI, FalseVal);
1546       }
1547       // Transform (X une Y) ? X : Y  -> X
1548       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1549         // This is not safe in general for floating point:
1550         // consider X== -0, Y== +0.
1551         // It becomes safe if either operand is a nonzero constant.
1552         ConstantFP *CFPt, *CFPf;
1553         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1554               !CFPt->getValueAPF().isZero()) ||
1555             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1556              !CFPf->getValueAPF().isZero()))
1557         return replaceInstUsesWith(SI, TrueVal);
1558       }
1559 
1560       // Canonicalize to use ordered comparisons by swapping the select
1561       // operands.
1562       //
1563       // e.g.
1564       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1565       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1566         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1567         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1568         Builder.setFastMathFlags(FCI->getFastMathFlags());
1569         Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1570                                             FCI->getName() + ".inv");
1571 
1572         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1573                                   SI.getName() + ".p");
1574       }
1575 
1576       // NOTE: if we wanted to, this is where to detect MIN/MAX
1577     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1578       // Transform (X == Y) ? Y : X  -> X
1579       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1580         // This is not safe in general for floating point:
1581         // consider X== -0, Y== +0.
1582         // It becomes safe if either operand is a nonzero constant.
1583         ConstantFP *CFPt, *CFPf;
1584         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1585               !CFPt->getValueAPF().isZero()) ||
1586             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1587              !CFPf->getValueAPF().isZero()))
1588           return replaceInstUsesWith(SI, FalseVal);
1589       }
1590       // Transform (X une Y) ? Y : X  -> Y
1591       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1592         // This is not safe in general for floating point:
1593         // consider X== -0, Y== +0.
1594         // It becomes safe if either operand is a nonzero constant.
1595         ConstantFP *CFPt, *CFPf;
1596         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1597               !CFPt->getValueAPF().isZero()) ||
1598             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1599              !CFPf->getValueAPF().isZero()))
1600           return replaceInstUsesWith(SI, TrueVal);
1601       }
1602 
1603       // Canonicalize to use ordered comparisons by swapping the select
1604       // operands.
1605       //
1606       // e.g.
1607       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1608       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1609         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1610         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1611         Builder.setFastMathFlags(FCI->getFastMathFlags());
1612         Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1613                                             FCI->getName() + ".inv");
1614 
1615         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1616                                   SI.getName() + ".p");
1617       }
1618 
1619       // NOTE: if we wanted to, this is where to detect MIN/MAX
1620     }
1621 
1622     // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1623     // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1624     // also require nnan because we do not want to unintentionally change the
1625     // sign of a NaN value.
1626     Value *X = FCI->getOperand(0);
1627     FCmpInst::Predicate Pred = FCI->getPredicate();
1628     if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1629       // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1630       // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
1631       if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1632            match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1633           (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1634            match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
1635         Value *Fabs = Builder.CreateIntrinsic(Intrinsic::fabs, { X }, FCI);
1636         return replaceInstUsesWith(SI, Fabs);
1637       }
1638       // With nsz:
1639       // (X <  +/-0.0) ? -X : X --> fabs(X)
1640       // (X <= +/-0.0) ? -X : X --> fabs(X)
1641       // (X >  +/-0.0) ? X : -X --> fabs(X)
1642       // (X >= +/-0.0) ? X : -X --> fabs(X)
1643       if (FCI->hasNoSignedZeros() &&
1644           ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1645             (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1646            (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1647             (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1648         Value *Fabs = Builder.CreateIntrinsic(Intrinsic::fabs, { X }, FCI);
1649         return replaceInstUsesWith(SI, Fabs);
1650       }
1651     }
1652   }
1653 
1654   // See if we are selecting two values based on a comparison of the two values.
1655   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1656     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1657       return Result;
1658 
1659   if (Instruction *Add = foldAddSubSelect(SI, Builder))
1660     return Add;
1661 
1662   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1663   auto *TI = dyn_cast<Instruction>(TrueVal);
1664   auto *FI = dyn_cast<Instruction>(FalseVal);
1665   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1666     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1667       return IV;
1668 
1669   if (Instruction *I = foldSelectExtConst(SI))
1670     return I;
1671 
1672   // See if we can fold the select into one of our operands.
1673   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1674     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1675       return FoldI;
1676 
1677     Value *LHS, *RHS, *LHS2, *RHS2;
1678     Instruction::CastOps CastOp;
1679     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1680     auto SPF = SPR.Flavor;
1681 
1682     if (SelectPatternResult::isMinOrMax(SPF)) {
1683       // Canonicalize so that
1684       // - type casts are outside select patterns.
1685       // - float clamp is transformed to min/max pattern
1686 
1687       bool IsCastNeeded = LHS->getType() != SelType;
1688       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1689       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1690       if (IsCastNeeded ||
1691           (LHS->getType()->isFPOrFPVectorTy() &&
1692            ((CmpLHS != LHS && CmpLHS != RHS) ||
1693             (CmpRHS != LHS && CmpRHS != RHS)))) {
1694         CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1695 
1696         Value *Cmp;
1697         if (CmpInst::isIntPredicate(Pred)) {
1698           Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1699         } else {
1700           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1701           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1702           Builder.setFastMathFlags(FMF);
1703           Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1704         }
1705 
1706         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1707         if (!IsCastNeeded)
1708           return replaceInstUsesWith(SI, NewSI);
1709 
1710         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1711         return replaceInstUsesWith(SI, NewCast);
1712       }
1713 
1714       // MAX(~a, ~b) -> ~MIN(a, b)
1715       // MIN(~a, ~b) -> ~MAX(a, b)
1716       Value *A, *B;
1717       if (match(LHS, m_Not(m_Value(A))) && match(RHS, m_Not(m_Value(B))) &&
1718           (LHS->getNumUses() <= 2 || RHS->getNumUses() <= 2)) {
1719         CmpInst::Predicate InvertedPred = getInverseMinMaxPred(SPF);
1720         Value *InvertedCmp = Builder.CreateICmp(InvertedPred, A, B);
1721         Value *NewSel = Builder.CreateSelect(InvertedCmp, A, B);
1722         return BinaryOperator::CreateNot(NewSel);
1723       }
1724 
1725       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1726         return I;
1727     }
1728 
1729     if (SPF) {
1730       // MAX(MAX(a, b), a) -> MAX(a, b)
1731       // MIN(MIN(a, b), a) -> MIN(a, b)
1732       // MAX(MIN(a, b), a) -> a
1733       // MIN(MAX(a, b), a) -> a
1734       // ABS(ABS(a)) -> ABS(a)
1735       // NABS(NABS(a)) -> NABS(a)
1736       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1737         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1738                                           SI, SPF, RHS))
1739           return R;
1740       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1741         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1742                                           SI, SPF, LHS))
1743           return R;
1744     }
1745 
1746     // TODO.
1747     // ABS(-X) -> ABS(X)
1748   }
1749 
1750   // See if we can fold the select into a phi node if the condition is a select.
1751   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1752     // The true/false values have to be live in the PHI predecessor's blocks.
1753     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1754         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1755       if (Instruction *NV = foldOpIntoPhi(SI, PN))
1756         return NV;
1757 
1758   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1759     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1760       // select(C, select(C, a, b), c) -> select(C, a, c)
1761       if (TrueSI->getCondition() == CondVal) {
1762         if (SI.getTrueValue() == TrueSI->getTrueValue())
1763           return nullptr;
1764         SI.setOperand(1, TrueSI->getTrueValue());
1765         return &SI;
1766       }
1767       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1768       // We choose this as normal form to enable folding on the And and shortening
1769       // paths for the values (this helps GetUnderlyingObjects() for example).
1770       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1771         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1772         SI.setOperand(0, And);
1773         SI.setOperand(1, TrueSI->getTrueValue());
1774         return &SI;
1775       }
1776     }
1777   }
1778   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1779     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1780       // select(C, a, select(C, b, c)) -> select(C, a, c)
1781       if (FalseSI->getCondition() == CondVal) {
1782         if (SI.getFalseValue() == FalseSI->getFalseValue())
1783           return nullptr;
1784         SI.setOperand(2, FalseSI->getFalseValue());
1785         return &SI;
1786       }
1787       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1788       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1789         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1790         SI.setOperand(0, Or);
1791         SI.setOperand(2, FalseSI->getFalseValue());
1792         return &SI;
1793       }
1794     }
1795   }
1796 
1797   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1798     // The select might be preventing a division by 0.
1799     switch (BO->getOpcode()) {
1800     default:
1801       return true;
1802     case Instruction::SRem:
1803     case Instruction::URem:
1804     case Instruction::SDiv:
1805     case Instruction::UDiv:
1806       return false;
1807     }
1808   };
1809 
1810   // Try to simplify a binop sandwiched between 2 selects with the same
1811   // condition.
1812   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1813   BinaryOperator *TrueBO;
1814   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1815       canMergeSelectThroughBinop(TrueBO)) {
1816     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1817       if (TrueBOSI->getCondition() == CondVal) {
1818         TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1819         Worklist.Add(TrueBO);
1820         return &SI;
1821       }
1822     }
1823     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1824       if (TrueBOSI->getCondition() == CondVal) {
1825         TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1826         Worklist.Add(TrueBO);
1827         return &SI;
1828       }
1829     }
1830   }
1831 
1832   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1833   BinaryOperator *FalseBO;
1834   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1835       canMergeSelectThroughBinop(FalseBO)) {
1836     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1837       if (FalseBOSI->getCondition() == CondVal) {
1838         FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1839         Worklist.Add(FalseBO);
1840         return &SI;
1841       }
1842     }
1843     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1844       if (FalseBOSI->getCondition() == CondVal) {
1845         FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1846         Worklist.Add(FalseBO);
1847         return &SI;
1848       }
1849     }
1850   }
1851 
1852   if (BinaryOperator::isNot(CondVal)) {
1853     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1854     SI.setOperand(1, FalseVal);
1855     SI.setOperand(2, TrueVal);
1856     return &SI;
1857   }
1858 
1859   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1860     unsigned VWidth = VecTy->getNumElements();
1861     APInt UndefElts(VWidth, 0);
1862     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1863     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1864       if (V != &SI)
1865         return replaceInstUsesWith(SI, V);
1866       return &SI;
1867     }
1868   }
1869 
1870   // See if we can determine the result of this select based on a dominating
1871   // condition.
1872   BasicBlock *Parent = SI.getParent();
1873   if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1874     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1875     if (PBI && PBI->isConditional() &&
1876         PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1877         (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1878       bool CondIsTrue = PBI->getSuccessor(0) == Parent;
1879       Optional<bool> Implication = isImpliedCondition(
1880           PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
1881       if (Implication) {
1882         Value *V = *Implication ? TrueVal : FalseVal;
1883         return replaceInstUsesWith(SI, V);
1884       }
1885     }
1886   }
1887 
1888   // If we can compute the condition, there's no need for a select.
1889   // Like the above fold, we are attempting to reduce compile-time cost by
1890   // putting this fold here with limitations rather than in InstSimplify.
1891   // The motivation for this call into value tracking is to take advantage of
1892   // the assumption cache, so make sure that is populated.
1893   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1894     KnownBits Known(1);
1895     computeKnownBits(CondVal, Known, 0, &SI);
1896     if (Known.One.isOneValue())
1897       return replaceInstUsesWith(SI, TrueVal);
1898     if (Known.Zero.isOneValue())
1899       return replaceInstUsesWith(SI, FalseVal);
1900   }
1901 
1902   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
1903     return BitCastSel;
1904 
1905   // Simplify selects that test the returned flag of cmpxchg instructions.
1906   if (Instruction *Select = foldSelectCmpXchg(SI))
1907     return Select;
1908 
1909   return nullptr;
1910 }
1911