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