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