xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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/OverflowInstAnalysis.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/InstCombiner.h"
42 #include <cassert>
43 #include <utility>
44 
45 #define DEBUG_TYPE "instcombine"
46 #include "llvm/Transforms/Utils/InstructionWorklist.h"
47 
48 using namespace llvm;
49 using namespace PatternMatch;
50 
51 
52 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
53                            SelectPatternFlavor SPF, Value *A, Value *B) {
54   CmpInst::Predicate Pred = getMinMaxPred(SPF);
55   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
56   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
57 }
58 
59 /// Replace a select operand based on an equality comparison with the identity
60 /// constant of a binop.
61 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
62                                             const TargetLibraryInfo &TLI,
63                                             InstCombinerImpl &IC) {
64   // The select condition must be an equality compare with a constant operand.
65   Value *X;
66   Constant *C;
67   CmpInst::Predicate Pred;
68   if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
69     return nullptr;
70 
71   bool IsEq;
72   if (ICmpInst::isEquality(Pred))
73     IsEq = Pred == ICmpInst::ICMP_EQ;
74   else if (Pred == FCmpInst::FCMP_OEQ)
75     IsEq = true;
76   else if (Pred == FCmpInst::FCMP_UNE)
77     IsEq = false;
78   else
79     return nullptr;
80 
81   // A select operand must be a binop.
82   BinaryOperator *BO;
83   if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
84     return nullptr;
85 
86   // The compare constant must be the identity constant for that binop.
87   // If this a floating-point compare with 0.0, any zero constant will do.
88   Type *Ty = BO->getType();
89   Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
90   if (IdC != C) {
91     if (!IdC || !CmpInst::isFPPredicate(Pred))
92       return nullptr;
93     if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
94       return nullptr;
95   }
96 
97   // Last, match the compare variable operand with a binop operand.
98   Value *Y;
99   if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
100     return nullptr;
101   if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
102     return nullptr;
103 
104   // +0.0 compares equal to -0.0, and so it does not behave as required for this
105   // transform. Bail out if we can not exclude that possibility.
106   if (isa<FPMathOperator>(BO))
107     if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
108       return nullptr;
109 
110   // BO = binop Y, X
111   // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
112   // =>
113   // S = { select (cmp eq X, C),  Y, ? } or { select (cmp ne X, C), ?,  Y }
114   return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
115 }
116 
117 /// This folds:
118 ///  select (icmp eq (and X, C1)), TC, FC
119 ///    iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
120 /// To something like:
121 ///  (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
122 /// Or:
123 ///  (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
124 /// With some variations depending if FC is larger than TC, or the shift
125 /// isn't needed, or the bit widths don't match.
126 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
127                                 InstCombiner::BuilderTy &Builder) {
128   const APInt *SelTC, *SelFC;
129   if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
130       !match(Sel.getFalseValue(), m_APInt(SelFC)))
131     return nullptr;
132 
133   // If this is a vector select, we need a vector compare.
134   Type *SelType = Sel.getType();
135   if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
136     return nullptr;
137 
138   Value *V;
139   APInt AndMask;
140   bool CreateAnd = false;
141   ICmpInst::Predicate Pred = Cmp->getPredicate();
142   if (ICmpInst::isEquality(Pred)) {
143     if (!match(Cmp->getOperand(1), m_Zero()))
144       return nullptr;
145 
146     V = Cmp->getOperand(0);
147     const APInt *AndRHS;
148     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
149       return nullptr;
150 
151     AndMask = *AndRHS;
152   } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
153                                   Pred, V, AndMask)) {
154     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
155     if (!AndMask.isPowerOf2())
156       return nullptr;
157 
158     CreateAnd = true;
159   } else {
160     return nullptr;
161   }
162 
163   // In general, when both constants are non-zero, we would need an offset to
164   // replace the select. This would require more instructions than we started
165   // with. But there's one special-case that we handle here because it can
166   // simplify/reduce the instructions.
167   APInt TC = *SelTC;
168   APInt FC = *SelFC;
169   if (!TC.isZero() && !FC.isZero()) {
170     // If the select constants differ by exactly one bit and that's the same
171     // bit that is masked and checked by the select condition, the select can
172     // be replaced by bitwise logic to set/clear one bit of the constant result.
173     if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
174       return nullptr;
175     if (CreateAnd) {
176       // If we have to create an 'and', then we must kill the cmp to not
177       // increase the instruction count.
178       if (!Cmp->hasOneUse())
179         return nullptr;
180       V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
181     }
182     bool ExtraBitInTC = TC.ugt(FC);
183     if (Pred == ICmpInst::ICMP_EQ) {
184       // If the masked bit in V is clear, clear or set the bit in the result:
185       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
186       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
187       Constant *C = ConstantInt::get(SelType, TC);
188       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
189     }
190     if (Pred == ICmpInst::ICMP_NE) {
191       // If the masked bit in V is set, set or clear the bit in the result:
192       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
193       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
194       Constant *C = ConstantInt::get(SelType, FC);
195       return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
196     }
197     llvm_unreachable("Only expecting equality predicates");
198   }
199 
200   // Make sure one of the select arms is a power-of-2.
201   if (!TC.isPowerOf2() && !FC.isPowerOf2())
202     return nullptr;
203 
204   // Determine which shift is needed to transform result of the 'and' into the
205   // desired result.
206   const APInt &ValC = !TC.isZero() ? TC : FC;
207   unsigned ValZeros = ValC.logBase2();
208   unsigned AndZeros = AndMask.logBase2();
209 
210   // Insert the 'and' instruction on the input to the truncate.
211   if (CreateAnd)
212     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
213 
214   // If types don't match, we can still convert the select by introducing a zext
215   // or a trunc of the 'and'.
216   if (ValZeros > AndZeros) {
217     V = Builder.CreateZExtOrTrunc(V, SelType);
218     V = Builder.CreateShl(V, ValZeros - AndZeros);
219   } else if (ValZeros < AndZeros) {
220     V = Builder.CreateLShr(V, AndZeros - ValZeros);
221     V = Builder.CreateZExtOrTrunc(V, SelType);
222   } else {
223     V = Builder.CreateZExtOrTrunc(V, SelType);
224   }
225 
226   // Okay, now we know that everything is set up, we just don't know whether we
227   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
228   bool ShouldNotVal = !TC.isZero();
229   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
230   if (ShouldNotVal)
231     V = Builder.CreateXor(V, ValC);
232 
233   return V;
234 }
235 
236 /// We want to turn code that looks like this:
237 ///   %C = or %A, %B
238 ///   %D = select %cond, %C, %A
239 /// into:
240 ///   %C = select %cond, %B, 0
241 ///   %D = or %A, %C
242 ///
243 /// Assuming that the specified instruction is an operand to the select, return
244 /// a bitmask indicating which operands of this instruction are foldable if they
245 /// equal the other incoming value of the select.
246 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
247   switch (I->getOpcode()) {
248   case Instruction::Add:
249   case Instruction::Mul:
250   case Instruction::And:
251   case Instruction::Or:
252   case Instruction::Xor:
253     return 3;              // Can fold through either operand.
254   case Instruction::Sub:   // Can only fold on the amount subtracted.
255   case Instruction::Shl:   // Can only fold on the shift amount.
256   case Instruction::LShr:
257   case Instruction::AShr:
258     return 1;
259   default:
260     return 0;              // Cannot fold
261   }
262 }
263 
264 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
265 Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
266                                               Instruction *FI) {
267   // Don't break up min/max patterns. The hasOneUse checks below prevent that
268   // for most cases, but vector min/max with bitcasts can be transformed. If the
269   // one-use restrictions are eased for other patterns, we still don't want to
270   // obfuscate min/max.
271   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
272        match(&SI, m_SMax(m_Value(), m_Value())) ||
273        match(&SI, m_UMin(m_Value(), m_Value())) ||
274        match(&SI, m_UMax(m_Value(), m_Value()))))
275     return nullptr;
276 
277   // If this is a cast from the same type, merge.
278   Value *Cond = SI.getCondition();
279   Type *CondTy = Cond->getType();
280   if (TI->getNumOperands() == 1 && TI->isCast()) {
281     Type *FIOpndTy = FI->getOperand(0)->getType();
282     if (TI->getOperand(0)->getType() != FIOpndTy)
283       return nullptr;
284 
285     // The select condition may be a vector. We may only change the operand
286     // type if the vector width remains the same (and matches the condition).
287     if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
288       if (!FIOpndTy->isVectorTy() ||
289           CondVTy->getElementCount() !=
290               cast<VectorType>(FIOpndTy)->getElementCount())
291         return nullptr;
292 
293       // TODO: If the backend knew how to deal with casts better, we could
294       // remove this limitation. For now, there's too much potential to create
295       // worse codegen by promoting the select ahead of size-altering casts
296       // (PR28160).
297       //
298       // Note that ValueTracking's matchSelectPattern() looks through casts
299       // without checking 'hasOneUse' when it matches min/max patterns, so this
300       // transform may end up happening anyway.
301       if (TI->getOpcode() != Instruction::BitCast &&
302           (!TI->hasOneUse() || !FI->hasOneUse()))
303         return nullptr;
304     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
305       // TODO: The one-use restrictions for a scalar select could be eased if
306       // the fold of a select in visitLoadInst() was enhanced to match a pattern
307       // that includes a cast.
308       return nullptr;
309     }
310 
311     // Fold this by inserting a select from the input values.
312     Value *NewSI =
313         Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
314                              SI.getName() + ".v", &SI);
315     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
316                             TI->getType());
317   }
318 
319   // Cond ? -X : -Y --> -(Cond ? X : Y)
320   Value *X, *Y;
321   if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
322       (TI->hasOneUse() || FI->hasOneUse())) {
323     // Intersect FMF from the fneg instructions and union those with the select.
324     FastMathFlags FMF = TI->getFastMathFlags();
325     FMF &= FI->getFastMathFlags();
326     FMF |= SI.getFastMathFlags();
327     Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
328     if (auto *NewSelI = dyn_cast<Instruction>(NewSel))
329       NewSelI->setFastMathFlags(FMF);
330     Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewSel);
331     NewFNeg->setFastMathFlags(FMF);
332     return NewFNeg;
333   }
334 
335   // Min/max intrinsic with a common operand can have the common operand pulled
336   // after the select. This is the same transform as below for binops, but
337   // specialized for intrinsic matching and without the restrictive uses clause.
338   auto *TII = dyn_cast<IntrinsicInst>(TI);
339   auto *FII = dyn_cast<IntrinsicInst>(FI);
340   if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID() &&
341       (TII->hasOneUse() || FII->hasOneUse())) {
342     Value *T0, *T1, *F0, *F1;
343     if (match(TII, m_MaxOrMin(m_Value(T0), m_Value(T1))) &&
344         match(FII, m_MaxOrMin(m_Value(F0), m_Value(F1)))) {
345       if (T0 == F0) {
346         Value *NewSel = Builder.CreateSelect(Cond, T1, F1, "minmaxop", &SI);
347         return CallInst::Create(TII->getCalledFunction(), {NewSel, T0});
348       }
349       if (T0 == F1) {
350         Value *NewSel = Builder.CreateSelect(Cond, T1, F0, "minmaxop", &SI);
351         return CallInst::Create(TII->getCalledFunction(), {NewSel, T0});
352       }
353       if (T1 == F0) {
354         Value *NewSel = Builder.CreateSelect(Cond, T0, F1, "minmaxop", &SI);
355         return CallInst::Create(TII->getCalledFunction(), {NewSel, T1});
356       }
357       if (T1 == F1) {
358         Value *NewSel = Builder.CreateSelect(Cond, T0, F0, "minmaxop", &SI);
359         return CallInst::Create(TII->getCalledFunction(), {NewSel, T1});
360       }
361     }
362   }
363 
364   // Only handle binary operators (including two-operand getelementptr) with
365   // one-use here. As with the cast case above, it may be possible to relax the
366   // one-use constraint, but that needs be examined carefully since it may not
367   // reduce the total number of instructions.
368   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
369       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
370       !TI->hasOneUse() || !FI->hasOneUse())
371     return nullptr;
372 
373   // Figure out if the operations have any operands in common.
374   Value *MatchOp, *OtherOpT, *OtherOpF;
375   bool MatchIsOpZero;
376   if (TI->getOperand(0) == FI->getOperand(0)) {
377     MatchOp  = TI->getOperand(0);
378     OtherOpT = TI->getOperand(1);
379     OtherOpF = FI->getOperand(1);
380     MatchIsOpZero = true;
381   } else if (TI->getOperand(1) == FI->getOperand(1)) {
382     MatchOp  = TI->getOperand(1);
383     OtherOpT = TI->getOperand(0);
384     OtherOpF = FI->getOperand(0);
385     MatchIsOpZero = false;
386   } else if (!TI->isCommutative()) {
387     return nullptr;
388   } else if (TI->getOperand(0) == FI->getOperand(1)) {
389     MatchOp  = TI->getOperand(0);
390     OtherOpT = TI->getOperand(1);
391     OtherOpF = FI->getOperand(0);
392     MatchIsOpZero = true;
393   } else if (TI->getOperand(1) == FI->getOperand(0)) {
394     MatchOp  = TI->getOperand(1);
395     OtherOpT = TI->getOperand(0);
396     OtherOpF = FI->getOperand(1);
397     MatchIsOpZero = true;
398   } else {
399     return nullptr;
400   }
401 
402   // If the select condition is a vector, the operands of the original select's
403   // operands also must be vectors. This may not be the case for getelementptr
404   // for example.
405   if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
406                                !OtherOpF->getType()->isVectorTy()))
407     return nullptr;
408 
409   // If we reach here, they do have operations in common.
410   Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
411                                       SI.getName() + ".v", &SI);
412   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
413   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
414   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
415     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
416     NewBO->copyIRFlags(TI);
417     NewBO->andIRFlags(FI);
418     return NewBO;
419   }
420   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
421     auto *FGEP = cast<GetElementPtrInst>(FI);
422     Type *ElementType = TGEP->getResultElementType();
423     return TGEP->isInBounds() && FGEP->isInBounds()
424                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
425                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
426   }
427   llvm_unreachable("Expected BinaryOperator or GEP");
428   return nullptr;
429 }
430 
431 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
432   if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
433     return false;
434   return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
435 }
436 
437 /// Try to fold the select into one of the operands to allow further
438 /// optimization.
439 Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
440                                                 Value *FalseVal) {
441   // See the comment above GetSelectFoldableOperands for a description of the
442   // transformation we are doing here.
443   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
444     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
445       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
446         unsigned OpToFold = 0;
447         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
448           OpToFold = 1;
449         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
450           OpToFold = 2;
451         }
452 
453         if (OpToFold) {
454           Constant *C = ConstantExpr::getBinOpIdentity(TVI->getOpcode(),
455                                                        TVI->getType(), true);
456           Value *OOp = TVI->getOperand(2-OpToFold);
457           // Avoid creating select between 2 constants unless it's selecting
458           // between 0, 1 and -1.
459           const APInt *OOpC;
460           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
461           if (!isa<Constant>(OOp) ||
462               (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
463             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
464             NewSel->takeName(TVI);
465             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
466                                                         FalseVal, NewSel);
467             BO->copyIRFlags(TVI);
468             return BO;
469           }
470         }
471       }
472     }
473   }
474 
475   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
476     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
477       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
478         unsigned OpToFold = 0;
479         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
480           OpToFold = 1;
481         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
482           OpToFold = 2;
483         }
484 
485         if (OpToFold) {
486           Constant *C = ConstantExpr::getBinOpIdentity(FVI->getOpcode(),
487                                                        FVI->getType(), true);
488           Value *OOp = FVI->getOperand(2-OpToFold);
489           // Avoid creating select between 2 constants unless it's selecting
490           // between 0, 1 and -1.
491           const APInt *OOpC;
492           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
493           if (!isa<Constant>(OOp) ||
494               (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
495             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
496             NewSel->takeName(FVI);
497             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
498                                                         TrueVal, NewSel);
499             BO->copyIRFlags(FVI);
500             return BO;
501           }
502         }
503       }
504     }
505   }
506 
507   return nullptr;
508 }
509 
510 /// We want to turn:
511 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
512 /// into:
513 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
514 /// Note:
515 ///   Z may be 0 if lshr is missing.
516 /// Worst-case scenario is that we will replace 5 instructions with 5 different
517 /// instructions, but we got rid of select.
518 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
519                                          Value *TVal, Value *FVal,
520                                          InstCombiner::BuilderTy &Builder) {
521   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
522         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
523         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
524     return nullptr;
525 
526   // The TrueVal has general form of:  and %B, 1
527   Value *B;
528   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
529     return nullptr;
530 
531   // Where %B may be optionally shifted:  lshr %X, %Z.
532   Value *X, *Z;
533   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
534   if (!HasShift)
535     X = B;
536 
537   Value *Y;
538   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
539     return nullptr;
540 
541   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
542   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
543   Constant *One = ConstantInt::get(SelType, 1);
544   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
545   Value *FullMask = Builder.CreateOr(Y, MaskB);
546   Value *MaskedX = Builder.CreateAnd(X, FullMask);
547   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
548   return new ZExtInst(ICmpNeZero, SelType);
549 }
550 
551 /// We want to turn:
552 ///   (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
553 ///   (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
554 /// into:
555 ///   ashr (X, Y)
556 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
557                                      Value *FalseVal,
558                                      InstCombiner::BuilderTy &Builder) {
559   ICmpInst::Predicate Pred = IC->getPredicate();
560   Value *CmpLHS = IC->getOperand(0);
561   Value *CmpRHS = IC->getOperand(1);
562   if (!CmpRHS->getType()->isIntOrIntVectorTy())
563     return nullptr;
564 
565   Value *X, *Y;
566   unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
567   if ((Pred != ICmpInst::ICMP_SGT ||
568        !match(CmpRHS,
569               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
570       (Pred != ICmpInst::ICMP_SLT ||
571        !match(CmpRHS,
572               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
573     return nullptr;
574 
575   // Canonicalize so that ashr is in FalseVal.
576   if (Pred == ICmpInst::ICMP_SLT)
577     std::swap(TrueVal, FalseVal);
578 
579   if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
580       match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
581       match(CmpLHS, m_Specific(X))) {
582     const auto *Ashr = cast<Instruction>(FalseVal);
583     // if lshr is not exact and ashr is, this new ashr must not be exact.
584     bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
585     return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
586   }
587 
588   return nullptr;
589 }
590 
591 /// We want to turn:
592 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
593 /// into:
594 ///   (or (shl (and X, C1), C3), Y)
595 /// iff:
596 ///   C1 and C2 are both powers of 2
597 /// where:
598 ///   C3 = Log(C2) - Log(C1)
599 ///
600 /// This transform handles cases where:
601 /// 1. The icmp predicate is inverted
602 /// 2. The select operands are reversed
603 /// 3. The magnitude of C2 and C1 are flipped
604 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
605                                   Value *FalseVal,
606                                   InstCombiner::BuilderTy &Builder) {
607   // Only handle integer compares. Also, if this is a vector select, we need a
608   // vector compare.
609   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
610       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
611     return nullptr;
612 
613   Value *CmpLHS = IC->getOperand(0);
614   Value *CmpRHS = IC->getOperand(1);
615 
616   Value *V;
617   unsigned C1Log;
618   bool IsEqualZero;
619   bool NeedAnd = false;
620   if (IC->isEquality()) {
621     if (!match(CmpRHS, m_Zero()))
622       return nullptr;
623 
624     const APInt *C1;
625     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
626       return nullptr;
627 
628     V = CmpLHS;
629     C1Log = C1->logBase2();
630     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
631   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
632              IC->getPredicate() == ICmpInst::ICMP_SGT) {
633     // We also need to recognize (icmp slt (trunc (X)), 0) and
634     // (icmp sgt (trunc (X)), -1).
635     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
636     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
637         (!IsEqualZero && !match(CmpRHS, m_Zero())))
638       return nullptr;
639 
640     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
641       return nullptr;
642 
643     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
644     NeedAnd = true;
645   } else {
646     return nullptr;
647   }
648 
649   const APInt *C2;
650   bool OrOnTrueVal = false;
651   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
652   if (!OrOnFalseVal)
653     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
654 
655   if (!OrOnFalseVal && !OrOnTrueVal)
656     return nullptr;
657 
658   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
659 
660   unsigned C2Log = C2->logBase2();
661 
662   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
663   bool NeedShift = C1Log != C2Log;
664   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
665                        V->getType()->getScalarSizeInBits();
666 
667   // Make sure we don't create more instructions than we save.
668   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
669   if ((NeedShift + NeedXor + NeedZExtTrunc) >
670       (IC->hasOneUse() + Or->hasOneUse()))
671     return nullptr;
672 
673   if (NeedAnd) {
674     // Insert the AND instruction on the input to the truncate.
675     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
676     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
677   }
678 
679   if (C2Log > C1Log) {
680     V = Builder.CreateZExtOrTrunc(V, Y->getType());
681     V = Builder.CreateShl(V, C2Log - C1Log);
682   } else if (C1Log > C2Log) {
683     V = Builder.CreateLShr(V, C1Log - C2Log);
684     V = Builder.CreateZExtOrTrunc(V, Y->getType());
685   } else
686     V = Builder.CreateZExtOrTrunc(V, Y->getType());
687 
688   if (NeedXor)
689     V = Builder.CreateXor(V, *C2);
690 
691   return Builder.CreateOr(V, Y);
692 }
693 
694 /// Canonicalize a set or clear of a masked set of constant bits to
695 /// select-of-constants form.
696 static Instruction *foldSetClearBits(SelectInst &Sel,
697                                      InstCombiner::BuilderTy &Builder) {
698   Value *Cond = Sel.getCondition();
699   Value *T = Sel.getTrueValue();
700   Value *F = Sel.getFalseValue();
701   Type *Ty = Sel.getType();
702   Value *X;
703   const APInt *NotC, *C;
704 
705   // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
706   if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
707       match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
708     Constant *Zero = ConstantInt::getNullValue(Ty);
709     Constant *OrC = ConstantInt::get(Ty, *C);
710     Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
711     return BinaryOperator::CreateOr(T, NewSel);
712   }
713 
714   // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
715   if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
716       match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
717     Constant *Zero = ConstantInt::getNullValue(Ty);
718     Constant *OrC = ConstantInt::get(Ty, *C);
719     Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
720     return BinaryOperator::CreateOr(F, NewSel);
721   }
722 
723   return nullptr;
724 }
725 
726 //   select (x == 0), 0, x * y --> freeze(y) * x
727 //   select (y == 0), 0, x * y --> freeze(x) * y
728 //   select (x == 0), undef, x * y --> freeze(y) * x
729 //   select (x == undef), 0, x * y --> freeze(y) * x
730 // Usage of mul instead of 0 will make the result more poisonous,
731 // so the operand that was not checked in the condition should be frozen.
732 // The latter folding is applied only when a constant compared with x is
733 // is a vector consisting of 0 and undefs. If a constant compared with x
734 // is a scalar undefined value or undefined vector then an expression
735 // should be already folded into a constant.
736 static Instruction *foldSelectZeroOrMul(SelectInst &SI, InstCombinerImpl &IC) {
737   auto *CondVal = SI.getCondition();
738   auto *TrueVal = SI.getTrueValue();
739   auto *FalseVal = SI.getFalseValue();
740   Value *X, *Y;
741   ICmpInst::Predicate Predicate;
742 
743   // Assuming that constant compared with zero is not undef (but it may be
744   // a vector with some undef elements). Otherwise (when a constant is undef)
745   // the select expression should be already simplified.
746   if (!match(CondVal, m_ICmp(Predicate, m_Value(X), m_Zero())) ||
747       !ICmpInst::isEquality(Predicate))
748     return nullptr;
749 
750   if (Predicate == ICmpInst::ICMP_NE)
751     std::swap(TrueVal, FalseVal);
752 
753   // Check that TrueVal is a constant instead of matching it with m_Zero()
754   // to handle the case when it is a scalar undef value or a vector containing
755   // non-zero elements that are masked by undef elements in the compare
756   // constant.
757   auto *TrueValC = dyn_cast<Constant>(TrueVal);
758   if (TrueValC == nullptr ||
759       !match(FalseVal, m_c_Mul(m_Specific(X), m_Value(Y))) ||
760       !isa<Instruction>(FalseVal))
761     return nullptr;
762 
763   auto *ZeroC = cast<Constant>(cast<Instruction>(CondVal)->getOperand(1));
764   auto *MergedC = Constant::mergeUndefsWith(TrueValC, ZeroC);
765   // If X is compared with 0 then TrueVal could be either zero or undef.
766   // m_Zero match vectors containing some undef elements, but for scalars
767   // m_Undef should be used explicitly.
768   if (!match(MergedC, m_Zero()) && !match(MergedC, m_Undef()))
769     return nullptr;
770 
771   auto *FalseValI = cast<Instruction>(FalseVal);
772   auto *FrY = IC.InsertNewInstBefore(new FreezeInst(Y, Y->getName() + ".fr"),
773                                      *FalseValI);
774   IC.replaceOperand(*FalseValI, FalseValI->getOperand(0) == Y ? 0 : 1, FrY);
775   return IC.replaceInstUsesWith(SI, FalseValI);
776 }
777 
778 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
779 /// There are 8 commuted/swapped variants of this pattern.
780 /// TODO: Also support a - UMIN(a,b) patterns.
781 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
782                                             const Value *TrueVal,
783                                             const Value *FalseVal,
784                                             InstCombiner::BuilderTy &Builder) {
785   ICmpInst::Predicate Pred = ICI->getPredicate();
786   if (!ICmpInst::isUnsigned(Pred))
787     return nullptr;
788 
789   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
790   if (match(TrueVal, m_Zero())) {
791     Pred = ICmpInst::getInversePredicate(Pred);
792     std::swap(TrueVal, FalseVal);
793   }
794   if (!match(FalseVal, m_Zero()))
795     return nullptr;
796 
797   Value *A = ICI->getOperand(0);
798   Value *B = ICI->getOperand(1);
799   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
800     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
801     std::swap(A, B);
802     Pred = ICmpInst::getSwappedPredicate(Pred);
803   }
804 
805   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
806          "Unexpected isUnsigned predicate!");
807 
808   // Ensure the sub is of the form:
809   //  (a > b) ? a - b : 0 -> usub.sat(a, b)
810   //  (a > b) ? b - a : 0 -> -usub.sat(a, b)
811   // Checking for both a-b and a+(-b) as a constant.
812   bool IsNegative = false;
813   const APInt *C;
814   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
815       (match(A, m_APInt(C)) &&
816        match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
817     IsNegative = true;
818   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
819            !(match(B, m_APInt(C)) &&
820              match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
821     return nullptr;
822 
823   // If we are adding a negate and the sub and icmp are used anywhere else, we
824   // would end up with more instructions.
825   if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
826     return nullptr;
827 
828   // (a > b) ? a - b : 0 -> usub.sat(a, b)
829   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
830   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
831   if (IsNegative)
832     Result = Builder.CreateNeg(Result);
833   return Result;
834 }
835 
836 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
837                                        InstCombiner::BuilderTy &Builder) {
838   if (!Cmp->hasOneUse())
839     return nullptr;
840 
841   // Match unsigned saturated add with constant.
842   Value *Cmp0 = Cmp->getOperand(0);
843   Value *Cmp1 = Cmp->getOperand(1);
844   ICmpInst::Predicate Pred = Cmp->getPredicate();
845   Value *X;
846   const APInt *C, *CmpC;
847   if (Pred == ICmpInst::ICMP_ULT &&
848       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
849       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
850     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
851     return Builder.CreateBinaryIntrinsic(
852         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
853   }
854 
855   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
856   // There are 8 commuted variants.
857   // Canonicalize -1 (saturated result) to true value of the select.
858   if (match(FVal, m_AllOnes())) {
859     std::swap(TVal, FVal);
860     Pred = CmpInst::getInversePredicate(Pred);
861   }
862   if (!match(TVal, m_AllOnes()))
863     return nullptr;
864 
865   // Canonicalize predicate to less-than or less-or-equal-than.
866   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
867     std::swap(Cmp0, Cmp1);
868     Pred = CmpInst::getSwappedPredicate(Pred);
869   }
870   if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
871     return nullptr;
872 
873   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
874   // Strictness of the comparison is irrelevant.
875   Value *Y;
876   if (match(Cmp0, m_Not(m_Value(X))) &&
877       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
878     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
879     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
880     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
881   }
882   // The 'not' op may be included in the sum but not the compare.
883   // Strictness of the comparison is irrelevant.
884   X = Cmp0;
885   Y = Cmp1;
886   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
887     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
888     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
889     BinaryOperator *BO = cast<BinaryOperator>(FVal);
890     return Builder.CreateBinaryIntrinsic(
891         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
892   }
893   // The overflow may be detected via the add wrapping round.
894   // This is only valid for strict comparison!
895   if (Pred == ICmpInst::ICMP_ULT &&
896       match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
897       match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
898     // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
899     // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
900     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
901   }
902 
903   return nullptr;
904 }
905 
906 /// Fold the following code sequence:
907 /// \code
908 ///   int a = ctlz(x & -x);
909 //    x ? 31 - a : a;
910 /// \code
911 ///
912 /// into:
913 ///   cttz(x)
914 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
915                                          Value *FalseVal,
916                                          InstCombiner::BuilderTy &Builder) {
917   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
918   if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
919     return nullptr;
920 
921   if (ICI->getPredicate() == ICmpInst::ICMP_NE)
922     std::swap(TrueVal, FalseVal);
923 
924   if (!match(FalseVal,
925              m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
926     return nullptr;
927 
928   if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
929     return nullptr;
930 
931   Value *X = ICI->getOperand(0);
932   auto *II = cast<IntrinsicInst>(TrueVal);
933   if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
934     return nullptr;
935 
936   Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
937                                           II->getType());
938   return CallInst::Create(F, {X, II->getArgOperand(1)});
939 }
940 
941 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
942 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
943 ///
944 /// For example, we can fold the following code sequence:
945 /// \code
946 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
947 ///   %1 = icmp ne i32 %x, 0
948 ///   %2 = select i1 %1, i32 %0, i32 32
949 /// \code
950 ///
951 /// into:
952 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
953 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
954                                  InstCombiner::BuilderTy &Builder) {
955   ICmpInst::Predicate Pred = ICI->getPredicate();
956   Value *CmpLHS = ICI->getOperand(0);
957   Value *CmpRHS = ICI->getOperand(1);
958 
959   // Check if the condition value compares a value for equality against zero.
960   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
961     return nullptr;
962 
963   Value *SelectArg = FalseVal;
964   Value *ValueOnZero = TrueVal;
965   if (Pred == ICmpInst::ICMP_NE)
966     std::swap(SelectArg, ValueOnZero);
967 
968   // Skip zero extend/truncate.
969   Value *Count = nullptr;
970   if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
971       !match(SelectArg, m_Trunc(m_Value(Count))))
972     Count = SelectArg;
973 
974   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
975   // input to the cttz/ctlz is used as LHS for the compare instruction.
976   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
977       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
978     return nullptr;
979 
980   IntrinsicInst *II = cast<IntrinsicInst>(Count);
981 
982   // Check if the value propagated on zero is a constant number equal to the
983   // sizeof in bits of 'Count'.
984   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
985   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
986     // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
987     // true to false on this flag, so we can replace it for all users.
988     II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
989     return SelectArg;
990   }
991 
992   // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
993   // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
994   // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
995   if (II->hasOneUse() && SelectArg->hasOneUse() &&
996       !match(II->getArgOperand(1), m_One()))
997     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
998 
999   return nullptr;
1000 }
1001 
1002 /// Return true if we find and adjust an icmp+select pattern where the compare
1003 /// is with a constant that can be incremented or decremented to match the
1004 /// minimum or maximum idiom.
1005 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
1006   ICmpInst::Predicate Pred = Cmp.getPredicate();
1007   Value *CmpLHS = Cmp.getOperand(0);
1008   Value *CmpRHS = Cmp.getOperand(1);
1009   Value *TrueVal = Sel.getTrueValue();
1010   Value *FalseVal = Sel.getFalseValue();
1011 
1012   // We may move or edit the compare, so make sure the select is the only user.
1013   const APInt *CmpC;
1014   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
1015     return false;
1016 
1017   // These transforms only work for selects of integers or vector selects of
1018   // integer vectors.
1019   Type *SelTy = Sel.getType();
1020   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
1021   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
1022     return false;
1023 
1024   Constant *AdjustedRHS;
1025   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
1026     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
1027   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
1028     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
1029   else
1030     return false;
1031 
1032   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
1033   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
1034   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
1035       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
1036     ; // Nothing to do here. Values match without any sign/zero extension.
1037   }
1038   // Types do not match. Instead of calculating this with mixed types, promote
1039   // all to the larger type. This enables scalar evolution to analyze this
1040   // expression.
1041   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
1042     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
1043 
1044     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
1045     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
1046     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
1047     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
1048     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
1049       CmpLHS = TrueVal;
1050       AdjustedRHS = SextRHS;
1051     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
1052                SextRHS == TrueVal) {
1053       CmpLHS = FalseVal;
1054       AdjustedRHS = SextRHS;
1055     } else if (Cmp.isUnsigned()) {
1056       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
1057       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
1058       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
1059       // zext + signed compare cannot be changed:
1060       //    0xff <s 0x00, but 0x00ff >s 0x0000
1061       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
1062         CmpLHS = TrueVal;
1063         AdjustedRHS = ZextRHS;
1064       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
1065                  ZextRHS == TrueVal) {
1066         CmpLHS = FalseVal;
1067         AdjustedRHS = ZextRHS;
1068       } else {
1069         return false;
1070       }
1071     } else {
1072       return false;
1073     }
1074   } else {
1075     return false;
1076   }
1077 
1078   Pred = ICmpInst::getSwappedPredicate(Pred);
1079   CmpRHS = AdjustedRHS;
1080   std::swap(FalseVal, TrueVal);
1081   Cmp.setPredicate(Pred);
1082   Cmp.setOperand(0, CmpLHS);
1083   Cmp.setOperand(1, CmpRHS);
1084   Sel.setOperand(1, TrueVal);
1085   Sel.setOperand(2, FalseVal);
1086   Sel.swapProfMetadata();
1087 
1088   // Move the compare instruction right before the select instruction. Otherwise
1089   // the sext/zext value may be defined after the compare instruction uses it.
1090   Cmp.moveBefore(&Sel);
1091 
1092   return true;
1093 }
1094 
1095 /// If this is an integer min/max (icmp + select) with a constant operand,
1096 /// create the canonical icmp for the min/max operation and canonicalize the
1097 /// constant to the 'false' operand of the select:
1098 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1099 /// Note: if C1 != C2, this will change the icmp constant to the existing
1100 /// constant operand of the select.
1101 static Instruction *canonicalizeMinMaxWithConstant(SelectInst &Sel,
1102                                                    ICmpInst &Cmp,
1103                                                    InstCombinerImpl &IC) {
1104   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1105     return nullptr;
1106 
1107   // Canonicalize the compare predicate based on whether we have min or max.
1108   Value *LHS, *RHS;
1109   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1110   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1111     return nullptr;
1112 
1113   // Is this already canonical?
1114   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1115   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1116       Cmp.getPredicate() == CanonicalPred)
1117     return nullptr;
1118 
1119   // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1120   // as this may cause an infinite combine loop. Let the sub be folded first.
1121   if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1122       match(RHS, m_Sub(m_Value(), m_Zero())))
1123     return nullptr;
1124 
1125   // Create the canonical compare and plug it into the select.
1126   IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1127 
1128   // If the select operands did not change, we're done.
1129   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1130     return &Sel;
1131 
1132   // If we are swapping the select operands, swap the metadata too.
1133   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1134          "Unexpected results from matchSelectPattern");
1135   Sel.swapValues();
1136   Sel.swapProfMetadata();
1137   return &Sel;
1138 }
1139 
1140 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1141                                         InstCombinerImpl &IC) {
1142   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1143     return nullptr;
1144 
1145   Value *LHS, *RHS;
1146   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1147   if (SPF != SelectPatternFlavor::SPF_ABS &&
1148       SPF != SelectPatternFlavor::SPF_NABS)
1149     return nullptr;
1150 
1151   // Note that NSW flag can only be propagated for normal, non-negated abs!
1152   bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
1153                         match(RHS, m_NSWNeg(m_Specific(LHS)));
1154   Constant *IntMinIsPoisonC =
1155       ConstantInt::get(Type::getInt1Ty(Sel.getContext()), IntMinIsPoison);
1156   Instruction *Abs =
1157       IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC);
1158 
1159   if (SPF == SelectPatternFlavor::SPF_NABS)
1160     return BinaryOperator::CreateNeg(Abs); // Always without NSW flag!
1161 
1162   return IC.replaceInstUsesWith(Sel, Abs);
1163 }
1164 
1165 /// If we have a select with an equality comparison, then we know the value in
1166 /// one of the arms of the select. See if substituting this value into an arm
1167 /// and simplifying the result yields the same value as the other arm.
1168 ///
1169 /// To make this transform safe, we must drop poison-generating flags
1170 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1171 /// that poison from propagating. If the existing binop already had no
1172 /// poison-generating flags, then this transform can be done by instsimplify.
1173 ///
1174 /// Consider:
1175 ///   %cmp = icmp eq i32 %x, 2147483647
1176 ///   %add = add nsw i32 %x, 1
1177 ///   %sel = select i1 %cmp, i32 -2147483648, i32 %add
1178 ///
1179 /// We can't replace %sel with %add unless we strip away the flags.
1180 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1181 Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1182                                                           ICmpInst &Cmp) {
1183   // Value equivalence substitution requires an all-or-nothing replacement.
1184   // It does not make sense for a vector compare where each lane is chosen
1185   // independently.
1186   if (!Cmp.isEquality() || Cmp.getType()->isVectorTy())
1187     return nullptr;
1188 
1189   // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1190   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1191   bool Swapped = false;
1192   if (Cmp.getPredicate() == ICmpInst::ICMP_NE) {
1193     std::swap(TrueVal, FalseVal);
1194     Swapped = true;
1195   }
1196 
1197   // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1198   // Make sure Y cannot be undef though, as we might pick different values for
1199   // undef in the icmp and in f(Y). Additionally, take care to avoid replacing
1200   // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite
1201   // replacement cycle.
1202   Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1203   if (TrueVal != CmpLHS &&
1204       isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT)) {
1205     if (Value *V = simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ,
1206                                           /* AllowRefinement */ true))
1207       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1208 
1209     // Even if TrueVal does not simplify, we can directly replace a use of
1210     // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
1211     // else and is safe to speculatively execute (we may end up executing it
1212     // with different operands, which should not cause side-effects or trigger
1213     // undefined behavior). Only do this if CmpRHS is a constant, as
1214     // profitability is not clear for other cases.
1215     // FIXME: The replacement could be performed recursively.
1216     if (match(CmpRHS, m_ImmConstant()) && !match(CmpLHS, m_ImmConstant()))
1217       if (auto *I = dyn_cast<Instruction>(TrueVal))
1218         if (I->hasOneUse() && isSafeToSpeculativelyExecute(I))
1219           for (Use &U : I->operands())
1220             if (U == CmpLHS) {
1221               replaceUse(U, CmpRHS);
1222               return &Sel;
1223             }
1224   }
1225   if (TrueVal != CmpRHS &&
1226       isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT))
1227     if (Value *V = simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ,
1228                                           /* AllowRefinement */ true))
1229       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1230 
1231   auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1232   if (!FalseInst)
1233     return nullptr;
1234 
1235   // InstSimplify already performed this fold if it was possible subject to
1236   // current poison-generating flags. Try the transform again with
1237   // poison-generating flags temporarily dropped.
1238   bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false;
1239   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
1240     WasNUW = OBO->hasNoUnsignedWrap();
1241     WasNSW = OBO->hasNoSignedWrap();
1242     FalseInst->setHasNoUnsignedWrap(false);
1243     FalseInst->setHasNoSignedWrap(false);
1244   }
1245   if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
1246     WasExact = PEO->isExact();
1247     FalseInst->setIsExact(false);
1248   }
1249   if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) {
1250     WasInBounds = GEP->isInBounds();
1251     GEP->setIsInBounds(false);
1252   }
1253 
1254   // Try each equivalence substitution possibility.
1255   // We have an 'EQ' comparison, so the select's false value will propagate.
1256   // Example:
1257   // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1258   if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
1259                              /* AllowRefinement */ false) == TrueVal ||
1260       simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
1261                              /* AllowRefinement */ false) == TrueVal) {
1262     return replaceInstUsesWith(Sel, FalseVal);
1263   }
1264 
1265   // Restore poison-generating flags if the transform did not apply.
1266   if (WasNUW)
1267     FalseInst->setHasNoUnsignedWrap();
1268   if (WasNSW)
1269     FalseInst->setHasNoSignedWrap();
1270   if (WasExact)
1271     FalseInst->setIsExact();
1272   if (WasInBounds)
1273     cast<GetElementPtrInst>(FalseInst)->setIsInBounds();
1274 
1275   return nullptr;
1276 }
1277 
1278 // See if this is a pattern like:
1279 //   %old_cmp1 = icmp slt i32 %x, C2
1280 //   %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1281 //   %old_x_offseted = add i32 %x, C1
1282 //   %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1283 //   %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1284 // This can be rewritten as more canonical pattern:
1285 //   %new_cmp1 = icmp slt i32 %x, -C1
1286 //   %new_cmp2 = icmp sge i32 %x, C0-C1
1287 //   %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1288 //   %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1289 // Iff -C1 s<= C2 s<= C0-C1
1290 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1291 //      SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1292 static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1293                                     InstCombiner::BuilderTy &Builder) {
1294   Value *X = Sel0.getTrueValue();
1295   Value *Sel1 = Sel0.getFalseValue();
1296 
1297   // First match the condition of the outermost select.
1298   // Said condition must be one-use.
1299   if (!Cmp0.hasOneUse())
1300     return nullptr;
1301   ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
1302   Value *Cmp00 = Cmp0.getOperand(0);
1303   Constant *C0;
1304   if (!match(Cmp0.getOperand(1),
1305              m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1306     return nullptr;
1307 
1308   if (!isa<SelectInst>(Sel1)) {
1309     Pred0 = ICmpInst::getInversePredicate(Pred0);
1310     std::swap(X, Sel1);
1311   }
1312 
1313   // Canonicalize Cmp0 into ult or uge.
1314   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1315   switch (Pred0) {
1316   case ICmpInst::Predicate::ICMP_ULT:
1317   case ICmpInst::Predicate::ICMP_UGE:
1318     // Although icmp ult %x, 0 is an unusual thing to try and should generally
1319     // have been simplified, it does not verify with undef inputs so ensure we
1320     // are not in a strange state.
1321     if (!match(C0, m_SpecificInt_ICMP(
1322                        ICmpInst::Predicate::ICMP_NE,
1323                        APInt::getZero(C0->getType()->getScalarSizeInBits()))))
1324       return nullptr;
1325     break; // Great!
1326   case ICmpInst::Predicate::ICMP_ULE:
1327   case ICmpInst::Predicate::ICMP_UGT:
1328     // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
1329     // C0, which again means it must not have any all-ones elements.
1330     if (!match(C0,
1331                m_SpecificInt_ICMP(
1332                    ICmpInst::Predicate::ICMP_NE,
1333                    APInt::getAllOnes(C0->getType()->getScalarSizeInBits()))))
1334       return nullptr; // Can't do, have all-ones element[s].
1335     C0 = InstCombiner::AddOne(C0);
1336     break;
1337   default:
1338     return nullptr; // Unknown predicate.
1339   }
1340 
1341   // Now that we've canonicalized the ICmp, we know the X we expect;
1342   // the select in other hand should be one-use.
1343   if (!Sel1->hasOneUse())
1344     return nullptr;
1345 
1346   // If the types do not match, look through any truncs to the underlying
1347   // instruction.
1348   if (Cmp00->getType() != X->getType() && X->hasOneUse())
1349     match(X, m_TruncOrSelf(m_Value(X)));
1350 
1351   // We now can finish matching the condition of the outermost select:
1352   // it should either be the X itself, or an addition of some constant to X.
1353   Constant *C1;
1354   if (Cmp00 == X)
1355     C1 = ConstantInt::getNullValue(X->getType());
1356   else if (!match(Cmp00,
1357                   m_Add(m_Specific(X),
1358                         m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1359     return nullptr;
1360 
1361   Value *Cmp1;
1362   ICmpInst::Predicate Pred1;
1363   Constant *C2;
1364   Value *ReplacementLow, *ReplacementHigh;
1365   if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1366                             m_Value(ReplacementHigh))) ||
1367       !match(Cmp1,
1368              m_ICmp(Pred1, m_Specific(X),
1369                     m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1370     return nullptr;
1371 
1372   if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1373     return nullptr; // Not enough one-use instructions for the fold.
1374   // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1375   //        two comparisons we'll need to build.
1376 
1377   // Canonicalize Cmp1 into the form we expect.
1378   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1379   switch (Pred1) {
1380   case ICmpInst::Predicate::ICMP_SLT:
1381     break;
1382   case ICmpInst::Predicate::ICMP_SLE:
1383     // We'd have to increment C2 by one, and for that it must not have signed
1384     // max element, but then it would have been canonicalized to 'slt' before
1385     // we get here. So we can't do anything useful with 'sle'.
1386     return nullptr;
1387   case ICmpInst::Predicate::ICMP_SGT:
1388     // We want to canonicalize it to 'slt', so we'll need to increment C2,
1389     // which again means it must not have any signed max elements.
1390     if (!match(C2,
1391                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1392                                   APInt::getSignedMaxValue(
1393                                       C2->getType()->getScalarSizeInBits()))))
1394       return nullptr; // Can't do, have signed max element[s].
1395     C2 = InstCombiner::AddOne(C2);
1396     LLVM_FALLTHROUGH;
1397   case ICmpInst::Predicate::ICMP_SGE:
1398     // Also non-canonical, but here we don't need to change C2,
1399     // so we don't have any restrictions on C2, so we can just handle it.
1400     std::swap(ReplacementLow, ReplacementHigh);
1401     break;
1402   default:
1403     return nullptr; // Unknown predicate.
1404   }
1405 
1406   // The thresholds of this clamp-like pattern.
1407   auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1408   auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1409   if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
1410     std::swap(ThresholdLowIncl, ThresholdHighExcl);
1411 
1412   // The fold has a precondition 1: C2 s>= ThresholdLow
1413   auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1414                                          ThresholdLowIncl);
1415   if (!match(Precond1, m_One()))
1416     return nullptr;
1417   // The fold has a precondition 2: C2 s<= ThresholdHigh
1418   auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1419                                          ThresholdHighExcl);
1420   if (!match(Precond2, m_One()))
1421     return nullptr;
1422 
1423   // If we are matching from a truncated input, we need to sext the
1424   // ReplacementLow and ReplacementHigh values. Only do the transform if they
1425   // are free to extend due to being constants.
1426   if (X->getType() != Sel0.getType()) {
1427     Constant *LowC, *HighC;
1428     if (!match(ReplacementLow, m_ImmConstant(LowC)) ||
1429         !match(ReplacementHigh, m_ImmConstant(HighC)))
1430       return nullptr;
1431     ReplacementLow = ConstantExpr::getSExt(LowC, X->getType());
1432     ReplacementHigh = ConstantExpr::getSExt(HighC, X->getType());
1433   }
1434 
1435   // All good, finally emit the new pattern.
1436   Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1437   Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1438   Value *MaybeReplacedLow =
1439       Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1440 
1441   // Create the final select. If we looked through a truncate above, we will
1442   // need to retruncate the result.
1443   Value *MaybeReplacedHigh = Builder.CreateSelect(
1444       ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1445   return Builder.CreateTrunc(MaybeReplacedHigh, Sel0.getType());
1446 }
1447 
1448 // If we have
1449 //  %cmp = icmp [canonical predicate] i32 %x, C0
1450 //  %r = select i1 %cmp, i32 %y, i32 C1
1451 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1452 // will have if we flip the strictness of the predicate (i.e. without changing
1453 // the result) is identical to the C1 in select. If it matches we can change
1454 // original comparison to one with swapped predicate, reuse the constant,
1455 // and swap the hands of select.
1456 static Instruction *
1457 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1458                                          InstCombinerImpl &IC) {
1459   ICmpInst::Predicate Pred;
1460   Value *X;
1461   Constant *C0;
1462   if (!match(&Cmp, m_OneUse(m_ICmp(
1463                        Pred, m_Value(X),
1464                        m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1465     return nullptr;
1466 
1467   // If comparison predicate is non-relational, we won't be able to do anything.
1468   if (ICmpInst::isEquality(Pred))
1469     return nullptr;
1470 
1471   // If comparison predicate is non-canonical, then we certainly won't be able
1472   // to make it canonical; canonicalizeCmpWithConstant() already tried.
1473   if (!InstCombiner::isCanonicalPredicate(Pred))
1474     return nullptr;
1475 
1476   // If the [input] type of comparison and select type are different, lets abort
1477   // for now. We could try to compare constants with trunc/[zs]ext though.
1478   if (C0->getType() != Sel.getType())
1479     return nullptr;
1480 
1481   // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1482 
1483   Value *SelVal0, *SelVal1; // We do not care which one is from where.
1484   match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1485   // At least one of these values we are selecting between must be a constant
1486   // else we'll never succeed.
1487   if (!match(SelVal0, m_AnyIntegralConstant()) &&
1488       !match(SelVal1, m_AnyIntegralConstant()))
1489     return nullptr;
1490 
1491   // Does this constant C match any of the `select` values?
1492   auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1493     return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1494   };
1495 
1496   // If C0 *already* matches true/false value of select, we are done.
1497   if (MatchesSelectValue(C0))
1498     return nullptr;
1499 
1500   // Check the constant we'd have with flipped-strictness predicate.
1501   auto FlippedStrictness =
1502       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0);
1503   if (!FlippedStrictness)
1504     return nullptr;
1505 
1506   // If said constant doesn't match either, then there is no hope,
1507   if (!MatchesSelectValue(FlippedStrictness->second))
1508     return nullptr;
1509 
1510   // It matched! Lets insert the new comparison just before select.
1511   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1512   IC.Builder.SetInsertPoint(&Sel);
1513 
1514   Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1515   Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1516                                         Cmp.getName() + ".inv");
1517   IC.replaceOperand(Sel, 0, NewCmp);
1518   Sel.swapValues();
1519   Sel.swapProfMetadata();
1520 
1521   return &Sel;
1522 }
1523 
1524 /// Visit a SelectInst that has an ICmpInst as its first operand.
1525 Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
1526                                                       ICmpInst *ICI) {
1527   if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI))
1528     return NewSel;
1529 
1530   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1531     return NewSel;
1532 
1533   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1534     return NewAbs;
1535 
1536   if (Value *V = canonicalizeClampLike(SI, *ICI, Builder))
1537     return replaceInstUsesWith(SI, V);
1538 
1539   if (Instruction *NewSel =
1540           tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1541     return NewSel;
1542 
1543   bool Changed = adjustMinMax(SI, *ICI);
1544 
1545   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1546     return replaceInstUsesWith(SI, V);
1547 
1548   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1549   Value *TrueVal = SI.getTrueValue();
1550   Value *FalseVal = SI.getFalseValue();
1551   ICmpInst::Predicate Pred = ICI->getPredicate();
1552   Value *CmpLHS = ICI->getOperand(0);
1553   Value *CmpRHS = ICI->getOperand(1);
1554   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1555     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1556       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1557       SI.setOperand(1, CmpRHS);
1558       Changed = true;
1559     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1560       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1561       SI.setOperand(2, CmpRHS);
1562       Changed = true;
1563     }
1564   }
1565 
1566   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1567   // decomposeBitTestICmp() might help.
1568   {
1569     unsigned BitWidth =
1570         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1571     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1572     Value *X;
1573     const APInt *Y, *C;
1574     bool TrueWhenUnset;
1575     bool IsBitTest = false;
1576     if (ICmpInst::isEquality(Pred) &&
1577         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1578         match(CmpRHS, m_Zero())) {
1579       IsBitTest = true;
1580       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1581     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1582       X = CmpLHS;
1583       Y = &MinSignedValue;
1584       IsBitTest = true;
1585       TrueWhenUnset = false;
1586     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1587       X = CmpLHS;
1588       Y = &MinSignedValue;
1589       IsBitTest = true;
1590       TrueWhenUnset = true;
1591     }
1592     if (IsBitTest) {
1593       Value *V = nullptr;
1594       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1595       if (TrueWhenUnset && TrueVal == X &&
1596           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1597         V = Builder.CreateAnd(X, ~(*Y));
1598       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1599       else if (!TrueWhenUnset && FalseVal == X &&
1600                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1601         V = Builder.CreateAnd(X, ~(*Y));
1602       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1603       else if (TrueWhenUnset && FalseVal == X &&
1604                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1605         V = Builder.CreateOr(X, *Y);
1606       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1607       else if (!TrueWhenUnset && TrueVal == X &&
1608                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1609         V = Builder.CreateOr(X, *Y);
1610 
1611       if (V)
1612         return replaceInstUsesWith(SI, V);
1613     }
1614   }
1615 
1616   if (Instruction *V =
1617           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1618     return V;
1619 
1620   if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1621     return V;
1622 
1623   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1624     return replaceInstUsesWith(SI, V);
1625 
1626   if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1627     return replaceInstUsesWith(SI, V);
1628 
1629   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1630     return replaceInstUsesWith(SI, V);
1631 
1632   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1633     return replaceInstUsesWith(SI, V);
1634 
1635   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1636     return replaceInstUsesWith(SI, V);
1637 
1638   return Changed ? &SI : nullptr;
1639 }
1640 
1641 /// SI is a select whose condition is a PHI node (but the two may be in
1642 /// different blocks). See if the true/false values (V) are live in all of the
1643 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1644 ///
1645 ///   X = phi [ C1, BB1], [C2, BB2]
1646 ///   Y = add
1647 ///   Z = select X, Y, 0
1648 ///
1649 /// because Y is not live in BB1/BB2.
1650 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1651                                                    const SelectInst &SI) {
1652   // If the value is a non-instruction value like a constant or argument, it
1653   // can always be mapped.
1654   const Instruction *I = dyn_cast<Instruction>(V);
1655   if (!I) return true;
1656 
1657   // If V is a PHI node defined in the same block as the condition PHI, we can
1658   // map the arguments.
1659   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1660 
1661   if (const PHINode *VP = dyn_cast<PHINode>(I))
1662     if (VP->getParent() == CondPHI->getParent())
1663       return true;
1664 
1665   // Otherwise, if the PHI and select are defined in the same block and if V is
1666   // defined in a different block, then we can transform it.
1667   if (SI.getParent() == CondPHI->getParent() &&
1668       I->getParent() != CondPHI->getParent())
1669     return true;
1670 
1671   // Otherwise we have a 'hard' case and we can't tell without doing more
1672   // detailed dominator based analysis, punt.
1673   return false;
1674 }
1675 
1676 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1677 ///   SPF2(SPF1(A, B), C)
1678 Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
1679                                             SelectPatternFlavor SPF1, Value *A,
1680                                             Value *B, Instruction &Outer,
1681                                             SelectPatternFlavor SPF2,
1682                                             Value *C) {
1683   if (Outer.getType() != Inner->getType())
1684     return nullptr;
1685 
1686   if (C == A || C == B) {
1687     // MAX(MAX(A, B), B) -> MAX(A, B)
1688     // MIN(MIN(a, b), a) -> MIN(a, b)
1689     // TODO: This could be done in instsimplify.
1690     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1691       return replaceInstUsesWith(Outer, Inner);
1692 
1693     // MAX(MIN(a, b), a) -> a
1694     // MIN(MAX(a, b), a) -> a
1695     // TODO: This could be done in instsimplify.
1696     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1697         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1698         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1699         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1700       return replaceInstUsesWith(Outer, C);
1701   }
1702 
1703   if (SPF1 == SPF2) {
1704     const APInt *CB, *CC;
1705     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1706       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1707       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1708       // TODO: This could be done in instsimplify.
1709       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1710           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1711           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1712           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1713         return replaceInstUsesWith(Outer, Inner);
1714 
1715       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1716       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1717       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1718           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1719           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1720           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1721         Outer.replaceUsesOfWith(Inner, A);
1722         return &Outer;
1723       }
1724     }
1725   }
1726 
1727   // max(max(A, B), min(A, B)) --> max(A, B)
1728   // min(min(A, B), max(A, B)) --> min(A, B)
1729   // TODO: This could be done in instsimplify.
1730   if (SPF1 == SPF2 &&
1731       ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1732        (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1733        (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1734        (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1735     return replaceInstUsesWith(Outer, Inner);
1736 
1737   // ABS(ABS(X)) -> ABS(X)
1738   // NABS(NABS(X)) -> NABS(X)
1739   // TODO: This could be done in instsimplify.
1740   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1741     return replaceInstUsesWith(Outer, Inner);
1742   }
1743 
1744   // ABS(NABS(X)) -> ABS(X)
1745   // NABS(ABS(X)) -> NABS(X)
1746   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1747       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1748     SelectInst *SI = cast<SelectInst>(Inner);
1749     Value *NewSI =
1750         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1751                              SI->getTrueValue(), SI->getName(), SI);
1752     return replaceInstUsesWith(Outer, NewSI);
1753   }
1754 
1755   auto IsFreeOrProfitableToInvert =
1756       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1757     if (match(V, m_Not(m_Value(NotV)))) {
1758       // If V has at most 2 uses then we can get rid of the xor operation
1759       // entirely.
1760       ElidesXor |= !V->hasNUsesOrMore(3);
1761       return true;
1762     }
1763 
1764     if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1765       NotV = nullptr;
1766       return true;
1767     }
1768 
1769     return false;
1770   };
1771 
1772   Value *NotA, *NotB, *NotC;
1773   bool ElidesXor = false;
1774 
1775   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1776   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1777   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1778   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1779   //
1780   // This transform is performance neutral if we can elide at least one xor from
1781   // the set of three operands, since we'll be tacking on an xor at the very
1782   // end.
1783   if (SelectPatternResult::isMinOrMax(SPF1) &&
1784       SelectPatternResult::isMinOrMax(SPF2) &&
1785       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1786       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1787       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1788     if (!NotA)
1789       NotA = Builder.CreateNot(A);
1790     if (!NotB)
1791       NotB = Builder.CreateNot(B);
1792     if (!NotC)
1793       NotC = Builder.CreateNot(C);
1794 
1795     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1796                                    NotB);
1797     Value *NewOuter = Builder.CreateNot(
1798         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1799     return replaceInstUsesWith(Outer, NewOuter);
1800   }
1801 
1802   return nullptr;
1803 }
1804 
1805 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1806 /// This is even legal for FP.
1807 static Instruction *foldAddSubSelect(SelectInst &SI,
1808                                      InstCombiner::BuilderTy &Builder) {
1809   Value *CondVal = SI.getCondition();
1810   Value *TrueVal = SI.getTrueValue();
1811   Value *FalseVal = SI.getFalseValue();
1812   auto *TI = dyn_cast<Instruction>(TrueVal);
1813   auto *FI = dyn_cast<Instruction>(FalseVal);
1814   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1815     return nullptr;
1816 
1817   Instruction *AddOp = nullptr, *SubOp = nullptr;
1818   if ((TI->getOpcode() == Instruction::Sub &&
1819        FI->getOpcode() == Instruction::Add) ||
1820       (TI->getOpcode() == Instruction::FSub &&
1821        FI->getOpcode() == Instruction::FAdd)) {
1822     AddOp = FI;
1823     SubOp = TI;
1824   } else if ((FI->getOpcode() == Instruction::Sub &&
1825               TI->getOpcode() == Instruction::Add) ||
1826              (FI->getOpcode() == Instruction::FSub &&
1827               TI->getOpcode() == Instruction::FAdd)) {
1828     AddOp = TI;
1829     SubOp = FI;
1830   }
1831 
1832   if (AddOp) {
1833     Value *OtherAddOp = nullptr;
1834     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1835       OtherAddOp = AddOp->getOperand(1);
1836     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1837       OtherAddOp = AddOp->getOperand(0);
1838     }
1839 
1840     if (OtherAddOp) {
1841       // So at this point we know we have (Y -> OtherAddOp):
1842       //        select C, (add X, Y), (sub X, Z)
1843       Value *NegVal; // Compute -Z
1844       if (SI.getType()->isFPOrFPVectorTy()) {
1845         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1846         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1847           FastMathFlags Flags = AddOp->getFastMathFlags();
1848           Flags &= SubOp->getFastMathFlags();
1849           NegInst->setFastMathFlags(Flags);
1850         }
1851       } else {
1852         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1853       }
1854 
1855       Value *NewTrueOp = OtherAddOp;
1856       Value *NewFalseOp = NegVal;
1857       if (AddOp != TI)
1858         std::swap(NewTrueOp, NewFalseOp);
1859       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1860                                            SI.getName() + ".p", &SI);
1861 
1862       if (SI.getType()->isFPOrFPVectorTy()) {
1863         Instruction *RI =
1864             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1865 
1866         FastMathFlags Flags = AddOp->getFastMathFlags();
1867         Flags &= SubOp->getFastMathFlags();
1868         RI->setFastMathFlags(Flags);
1869         return RI;
1870       } else
1871         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1872     }
1873   }
1874   return nullptr;
1875 }
1876 
1877 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1878 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1879 /// Along with a number of patterns similar to:
1880 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1881 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1882 static Instruction *
1883 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1884   Value *CondVal = SI.getCondition();
1885   Value *TrueVal = SI.getTrueValue();
1886   Value *FalseVal = SI.getFalseValue();
1887 
1888   WithOverflowInst *II;
1889   if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1890       !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1891     return nullptr;
1892 
1893   Value *X = II->getLHS();
1894   Value *Y = II->getRHS();
1895 
1896   auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1897     Type *Ty = Limit->getType();
1898 
1899     ICmpInst::Predicate Pred;
1900     Value *TrueVal, *FalseVal, *Op;
1901     const APInt *C;
1902     if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1903                                m_Value(TrueVal), m_Value(FalseVal))))
1904       return false;
1905 
1906     auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
1907     auto IsMinMax = [&](Value *Min, Value *Max) {
1908       APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1909       APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1910       return match(Min, m_SpecificInt(MinVal)) &&
1911              match(Max, m_SpecificInt(MaxVal));
1912     };
1913 
1914     if (Op != X && Op != Y)
1915       return false;
1916 
1917     if (IsAdd) {
1918       // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1919       // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1920       // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1921       // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1922       if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1923           IsMinMax(TrueVal, FalseVal))
1924         return true;
1925       // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1926       // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1927       // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1928       // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1929       if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1930           IsMinMax(FalseVal, TrueVal))
1931         return true;
1932     } else {
1933       // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1934       // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1935       if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1936           IsMinMax(TrueVal, FalseVal))
1937         return true;
1938       // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1939       // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1940       if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1941           IsMinMax(FalseVal, TrueVal))
1942         return true;
1943       // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1944       // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1945       if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1946           IsMinMax(FalseVal, TrueVal))
1947         return true;
1948       // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1949       // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1950       if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1951           IsMinMax(TrueVal, FalseVal))
1952         return true;
1953     }
1954 
1955     return false;
1956   };
1957 
1958   Intrinsic::ID NewIntrinsicID;
1959   if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1960       match(TrueVal, m_AllOnes()))
1961     // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1962     NewIntrinsicID = Intrinsic::uadd_sat;
1963   else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1964            match(TrueVal, m_Zero()))
1965     // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1966     NewIntrinsicID = Intrinsic::usub_sat;
1967   else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1968            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1969     // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1970     // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1971     // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1972     // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1973     // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1974     // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1975     // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1976     // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1977     NewIntrinsicID = Intrinsic::sadd_sat;
1978   else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1979            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1980     // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1981     // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1982     // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1983     // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1984     // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1985     // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1986     // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1987     // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1988     NewIntrinsicID = Intrinsic::ssub_sat;
1989   else
1990     return nullptr;
1991 
1992   Function *F =
1993       Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1994   return CallInst::Create(F, {X, Y});
1995 }
1996 
1997 Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
1998   Constant *C;
1999   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
2000       !match(Sel.getFalseValue(), m_Constant(C)))
2001     return nullptr;
2002 
2003   Instruction *ExtInst;
2004   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
2005       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
2006     return nullptr;
2007 
2008   auto ExtOpcode = ExtInst->getOpcode();
2009   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
2010     return nullptr;
2011 
2012   // If we are extending from a boolean type or if we can create a select that
2013   // has the same size operands as its condition, try to narrow the select.
2014   Value *X = ExtInst->getOperand(0);
2015   Type *SmallType = X->getType();
2016   Value *Cond = Sel.getCondition();
2017   auto *Cmp = dyn_cast<CmpInst>(Cond);
2018   if (!SmallType->isIntOrIntVectorTy(1) &&
2019       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
2020     return nullptr;
2021 
2022   // If the constant is the same after truncation to the smaller type and
2023   // extension to the original type, we can narrow the select.
2024   Type *SelType = Sel.getType();
2025   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
2026   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
2027   if (ExtC == C && ExtInst->hasOneUse()) {
2028     Value *TruncCVal = cast<Value>(TruncC);
2029     if (ExtInst == Sel.getFalseValue())
2030       std::swap(X, TruncCVal);
2031 
2032     // select Cond, (ext X), C --> ext(select Cond, X, C')
2033     // select Cond, C, (ext X) --> ext(select Cond, C', X)
2034     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
2035     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
2036   }
2037 
2038   // If one arm of the select is the extend of the condition, replace that arm
2039   // with the extension of the appropriate known bool value.
2040   if (Cond == X) {
2041     if (ExtInst == Sel.getTrueValue()) {
2042       // select X, (sext X), C --> select X, -1, C
2043       // select X, (zext X), C --> select X,  1, C
2044       Constant *One = ConstantInt::getTrue(SmallType);
2045       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
2046       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
2047     } else {
2048       // select X, C, (sext X) --> select X, C, 0
2049       // select X, C, (zext X) --> select X, C, 0
2050       Constant *Zero = ConstantInt::getNullValue(SelType);
2051       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
2052     }
2053   }
2054 
2055   return nullptr;
2056 }
2057 
2058 /// Try to transform a vector select with a constant condition vector into a
2059 /// shuffle for easier combining with other shuffles and insert/extract.
2060 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2061   Value *CondVal = SI.getCondition();
2062   Constant *CondC;
2063   auto *CondValTy = dyn_cast<FixedVectorType>(CondVal->getType());
2064   if (!CondValTy || !match(CondVal, m_Constant(CondC)))
2065     return nullptr;
2066 
2067   unsigned NumElts = CondValTy->getNumElements();
2068   SmallVector<int, 16> Mask;
2069   Mask.reserve(NumElts);
2070   for (unsigned i = 0; i != NumElts; ++i) {
2071     Constant *Elt = CondC->getAggregateElement(i);
2072     if (!Elt)
2073       return nullptr;
2074 
2075     if (Elt->isOneValue()) {
2076       // If the select condition element is true, choose from the 1st vector.
2077       Mask.push_back(i);
2078     } else if (Elt->isNullValue()) {
2079       // If the select condition element is false, choose from the 2nd vector.
2080       Mask.push_back(i + NumElts);
2081     } else if (isa<UndefValue>(Elt)) {
2082       // Undef in a select condition (choose one of the operands) does not mean
2083       // the same thing as undef in a shuffle mask (any value is acceptable), so
2084       // give up.
2085       return nullptr;
2086     } else {
2087       // Bail out on a constant expression.
2088       return nullptr;
2089     }
2090   }
2091 
2092   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2093 }
2094 
2095 /// If we have a select of vectors with a scalar condition, try to convert that
2096 /// to a vector select by splatting the condition. A splat may get folded with
2097 /// other operations in IR and having all operands of a select be vector types
2098 /// is likely better for vector codegen.
2099 static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2100                                                    InstCombinerImpl &IC) {
2101   auto *Ty = dyn_cast<VectorType>(Sel.getType());
2102   if (!Ty)
2103     return nullptr;
2104 
2105   // We can replace a single-use extract with constant index.
2106   Value *Cond = Sel.getCondition();
2107   if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2108     return nullptr;
2109 
2110   // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2111   // Splatting the extracted condition reduces code (we could directly create a
2112   // splat shuffle of the source vector to eliminate the intermediate step).
2113   return IC.replaceOperand(
2114       Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
2115 }
2116 
2117 /// Reuse bitcasted operands between a compare and select:
2118 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2119 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2120 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2121                                           InstCombiner::BuilderTy &Builder) {
2122   Value *Cond = Sel.getCondition();
2123   Value *TVal = Sel.getTrueValue();
2124   Value *FVal = Sel.getFalseValue();
2125 
2126   CmpInst::Predicate Pred;
2127   Value *A, *B;
2128   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2129     return nullptr;
2130 
2131   // The select condition is a compare instruction. If the select's true/false
2132   // values are already the same as the compare operands, there's nothing to do.
2133   if (TVal == A || TVal == B || FVal == A || FVal == B)
2134     return nullptr;
2135 
2136   Value *C, *D;
2137   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2138     return nullptr;
2139 
2140   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2141   Value *TSrc, *FSrc;
2142   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2143       !match(FVal, m_BitCast(m_Value(FSrc))))
2144     return nullptr;
2145 
2146   // If the select true/false values are *different bitcasts* of the same source
2147   // operands, make the select operands the same as the compare operands and
2148   // cast the result. This is the canonical select form for min/max.
2149   Value *NewSel;
2150   if (TSrc == C && FSrc == D) {
2151     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2152     // bitcast (select (cmp A, B), A, B)
2153     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2154   } else if (TSrc == D && FSrc == C) {
2155     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2156     // bitcast (select (cmp A, B), B, A)
2157     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2158   } else {
2159     return nullptr;
2160   }
2161   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2162 }
2163 
2164 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2165 /// instructions.
2166 ///
2167 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2168 /// selects between the returned value of the cmpxchg instruction its compare
2169 /// operand, the result of the select will always be equal to its false value.
2170 /// For example:
2171 ///
2172 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2173 ///   %1 = extractvalue { i64, i1 } %0, 1
2174 ///   %2 = extractvalue { i64, i1 } %0, 0
2175 ///   %3 = select i1 %1, i64 %compare, i64 %2
2176 ///   ret i64 %3
2177 ///
2178 /// The returned value of the cmpxchg instruction (%2) is the original value
2179 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2180 /// must have been equal to %compare. Thus, the result of the select is always
2181 /// equal to %2, and the code can be simplified to:
2182 ///
2183 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2184 ///   %1 = extractvalue { i64, i1 } %0, 0
2185 ///   ret i64 %1
2186 ///
2187 static Value *foldSelectCmpXchg(SelectInst &SI) {
2188   // A helper that determines if V is an extractvalue instruction whose
2189   // aggregate operand is a cmpxchg instruction and whose single index is equal
2190   // to I. If such conditions are true, the helper returns the cmpxchg
2191   // instruction; otherwise, a nullptr is returned.
2192   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2193     auto *Extract = dyn_cast<ExtractValueInst>(V);
2194     if (!Extract)
2195       return nullptr;
2196     if (Extract->getIndices()[0] != I)
2197       return nullptr;
2198     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2199   };
2200 
2201   // If the select has a single user, and this user is a select instruction that
2202   // we can simplify, skip the cmpxchg simplification for now.
2203   if (SI.hasOneUse())
2204     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2205       if (Select->getCondition() == SI.getCondition())
2206         if (Select->getFalseValue() == SI.getTrueValue() ||
2207             Select->getTrueValue() == SI.getFalseValue())
2208           return nullptr;
2209 
2210   // Ensure the select condition is the returned flag of a cmpxchg instruction.
2211   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2212   if (!CmpXchg)
2213     return nullptr;
2214 
2215   // Check the true value case: The true value of the select is the returned
2216   // value of the same cmpxchg used by the condition, and the false value is the
2217   // cmpxchg instruction's compare operand.
2218   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2219     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2220       return SI.getFalseValue();
2221 
2222   // Check the false value case: The false value of the select is the returned
2223   // value of the same cmpxchg used by the condition, and the true value is the
2224   // cmpxchg instruction's compare operand.
2225   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2226     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2227       return SI.getFalseValue();
2228 
2229   return nullptr;
2230 }
2231 
2232 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2233                                        Value *Y,
2234                                        InstCombiner::BuilderTy &Builder) {
2235   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2236   bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2237                     SPF == SelectPatternFlavor::SPF_UMAX;
2238   // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2239   // the constant value check to an assert.
2240   Value *A;
2241   const APInt *C1, *C2;
2242   if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2243       match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2244     // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2245     // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2246     Value *NewMinMax = createMinMax(Builder, SPF, A,
2247                                     ConstantInt::get(X->getType(), *C2 - *C1));
2248     return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2249                                      ConstantInt::get(X->getType(), *C1));
2250   }
2251 
2252   if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2253       match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2254     bool Overflow;
2255     APInt Diff = C2->ssub_ov(*C1, Overflow);
2256     if (!Overflow) {
2257       // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2258       // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2259       Value *NewMinMax = createMinMax(Builder, SPF, A,
2260                                       ConstantInt::get(X->getType(), Diff));
2261       return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2262                                        ConstantInt::get(X->getType(), *C1));
2263     }
2264   }
2265 
2266   return nullptr;
2267 }
2268 
2269 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2270 Instruction *InstCombinerImpl::matchSAddSubSat(Instruction &MinMax1) {
2271   Type *Ty = MinMax1.getType();
2272 
2273   // We are looking for a tree of:
2274   // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2275   // Where the min and max could be reversed
2276   Instruction *MinMax2;
2277   BinaryOperator *AddSub;
2278   const APInt *MinValue, *MaxValue;
2279   if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2280     if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2281       return nullptr;
2282   } else if (match(&MinMax1,
2283                    m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2284     if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2285       return nullptr;
2286   } else
2287     return nullptr;
2288 
2289   // Check that the constants clamp a saturate, and that the new type would be
2290   // sensible to convert to.
2291   if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2292     return nullptr;
2293   // In what bitwidth can this be treated as saturating arithmetics?
2294   unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2295   // FIXME: This isn't quite right for vectors, but using the scalar type is a
2296   // good first approximation for what should be done there.
2297   if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2298     return nullptr;
2299 
2300   // Also make sure that the number of uses is as expected. The 3 is for the
2301   // the two items of the compare and the select, or 2 from a min/max.
2302   unsigned ExpUses = isa<IntrinsicInst>(MinMax1) ? 2 : 3;
2303   if (MinMax2->hasNUsesOrMore(ExpUses) || AddSub->hasNUsesOrMore(ExpUses))
2304     return nullptr;
2305 
2306   // Create the new type (which can be a vector type)
2307   Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2308 
2309   Intrinsic::ID IntrinsicID;
2310   if (AddSub->getOpcode() == Instruction::Add)
2311     IntrinsicID = Intrinsic::sadd_sat;
2312   else if (AddSub->getOpcode() == Instruction::Sub)
2313     IntrinsicID = Intrinsic::ssub_sat;
2314   else
2315     return nullptr;
2316 
2317   // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
2318   // is usually achieved via a sext from a smaller type.
2319   if (ComputeMinSignedBits(AddSub->getOperand(0), 0, AddSub) > NewBitWidth ||
2320       ComputeMinSignedBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
2321     return nullptr;
2322 
2323   // Finally create and return the sat intrinsic, truncated to the new type
2324   Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2325   Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
2326   Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
2327   Value *Sat = Builder.CreateCall(F, {AT, BT});
2328   return CastInst::Create(Instruction::SExt, Sat, Ty);
2329 }
2330 
2331 /// Reduce a sequence of min/max with a common operand.
2332 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2333                                         Value *RHS,
2334                                         InstCombiner::BuilderTy &Builder) {
2335   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2336   // TODO: Allow FP min/max with nnan/nsz.
2337   if (!LHS->getType()->isIntOrIntVectorTy())
2338     return nullptr;
2339 
2340   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2341   Value *A, *B, *C, *D;
2342   SelectPatternResult L = matchSelectPattern(LHS, A, B);
2343   SelectPatternResult R = matchSelectPattern(RHS, C, D);
2344   if (SPF != L.Flavor || L.Flavor != R.Flavor)
2345     return nullptr;
2346 
2347   // Look for a common operand. The use checks are different than usual because
2348   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2349   // the select.
2350   Value *MinMaxOp = nullptr;
2351   Value *ThirdOp = nullptr;
2352   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2353     // If the LHS is only used in this chain and the RHS is used outside of it,
2354     // reuse the RHS min/max because that will eliminate the LHS.
2355     if (D == A || C == A) {
2356       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2357       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2358       MinMaxOp = RHS;
2359       ThirdOp = B;
2360     } else if (D == B || C == B) {
2361       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2362       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2363       MinMaxOp = RHS;
2364       ThirdOp = A;
2365     }
2366   } else if (!RHS->hasNUsesOrMore(3)) {
2367     // Reuse the LHS. This will eliminate the RHS.
2368     if (D == A || D == B) {
2369       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2370       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2371       MinMaxOp = LHS;
2372       ThirdOp = C;
2373     } else if (C == A || C == B) {
2374       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2375       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2376       MinMaxOp = LHS;
2377       ThirdOp = D;
2378     }
2379   }
2380   if (!MinMaxOp || !ThirdOp)
2381     return nullptr;
2382 
2383   CmpInst::Predicate P = getMinMaxPred(SPF);
2384   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2385   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2386 }
2387 
2388 /// Try to reduce a funnel/rotate pattern that includes a compare and select
2389 /// into a funnel shift intrinsic. Example:
2390 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2391 ///              --> call llvm.fshl.i32(a, a, b)
2392 /// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
2393 ///                 --> call llvm.fshl.i32(a, b, c)
2394 /// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
2395 ///                 --> call llvm.fshr.i32(a, b, c)
2396 static Instruction *foldSelectFunnelShift(SelectInst &Sel,
2397                                           InstCombiner::BuilderTy &Builder) {
2398   // This must be a power-of-2 type for a bitmasking transform to be valid.
2399   unsigned Width = Sel.getType()->getScalarSizeInBits();
2400   if (!isPowerOf2_32(Width))
2401     return nullptr;
2402 
2403   BinaryOperator *Or0, *Or1;
2404   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
2405     return nullptr;
2406 
2407   Value *SV0, *SV1, *SA0, *SA1;
2408   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0),
2409                                           m_ZExtOrSelf(m_Value(SA0))))) ||
2410       !match(Or1, m_OneUse(m_LogicalShift(m_Value(SV1),
2411                                           m_ZExtOrSelf(m_Value(SA1))))) ||
2412       Or0->getOpcode() == Or1->getOpcode())
2413     return nullptr;
2414 
2415   // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
2416   if (Or0->getOpcode() == BinaryOperator::LShr) {
2417     std::swap(Or0, Or1);
2418     std::swap(SV0, SV1);
2419     std::swap(SA0, SA1);
2420   }
2421   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2422          Or1->getOpcode() == BinaryOperator::LShr &&
2423          "Illegal or(shift,shift) pair");
2424 
2425   // Check the shift amounts to see if they are an opposite pair.
2426   Value *ShAmt;
2427   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2428     ShAmt = SA0;
2429   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2430     ShAmt = SA1;
2431   else
2432     return nullptr;
2433 
2434   // We should now have this pattern:
2435   // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
2436   // The false value of the select must be a funnel-shift of the true value:
2437   // IsFShl -> TVal must be SV0 else TVal must be SV1.
2438   bool IsFshl = (ShAmt == SA0);
2439   Value *TVal = Sel.getTrueValue();
2440   if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
2441     return nullptr;
2442 
2443   // Finally, see if the select is filtering out a shift-by-zero.
2444   Value *Cond = Sel.getCondition();
2445   ICmpInst::Predicate Pred;
2446   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2447       Pred != ICmpInst::ICMP_EQ)
2448     return nullptr;
2449 
2450   // If this is not a rotate then the select was blocking poison from the
2451   // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
2452   if (SV0 != SV1) {
2453     if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1))
2454       SV1 = Builder.CreateFreeze(SV1);
2455     else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0))
2456       SV0 = Builder.CreateFreeze(SV0);
2457   }
2458 
2459   // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2460   // Convert to funnel shift intrinsic.
2461   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2462   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2463   ShAmt = Builder.CreateZExt(ShAmt, Sel.getType());
2464   return CallInst::Create(F, { SV0, SV1, ShAmt });
2465 }
2466 
2467 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2468                                          InstCombiner::BuilderTy &Builder) {
2469   Value *Cond = Sel.getCondition();
2470   Value *TVal = Sel.getTrueValue();
2471   Value *FVal = Sel.getFalseValue();
2472   Type *SelType = Sel.getType();
2473 
2474   // Match select ?, TC, FC where the constants are equal but negated.
2475   // TODO: Generalize to handle a negated variable operand?
2476   const APFloat *TC, *FC;
2477   if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2478       !abs(*TC).bitwiseIsEqual(abs(*FC)))
2479     return nullptr;
2480 
2481   assert(TC != FC && "Expected equal select arms to simplify");
2482 
2483   Value *X;
2484   const APInt *C;
2485   bool IsTrueIfSignSet;
2486   ICmpInst::Predicate Pred;
2487   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2488       !InstCombiner::isSignBitCheck(Pred, *C, IsTrueIfSignSet) ||
2489       X->getType() != SelType)
2490     return nullptr;
2491 
2492   // If needed, negate the value that will be the sign argument of the copysign:
2493   // (bitcast X) <  0 ? -TC :  TC --> copysign(TC,  X)
2494   // (bitcast X) <  0 ?  TC : -TC --> copysign(TC, -X)
2495   // (bitcast X) >= 0 ? -TC :  TC --> copysign(TC, -X)
2496   // (bitcast X) >= 0 ?  TC : -TC --> copysign(TC,  X)
2497   if (IsTrueIfSignSet ^ TC->isNegative())
2498     X = Builder.CreateFNegFMF(X, &Sel);
2499 
2500   // Canonicalize the magnitude argument as the positive constant since we do
2501   // not care about its sign.
2502   Value *MagArg = TC->isNegative() ? FVal : TVal;
2503   Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2504                                           Sel.getType());
2505   Instruction *CopySign = CallInst::Create(F, { MagArg, X });
2506   CopySign->setFastMathFlags(Sel.getFastMathFlags());
2507   return CopySign;
2508 }
2509 
2510 Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
2511   auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2512   if (!VecTy)
2513     return nullptr;
2514 
2515   unsigned NumElts = VecTy->getNumElements();
2516   APInt UndefElts(NumElts, 0);
2517   APInt AllOnesEltMask(APInt::getAllOnes(NumElts));
2518   if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2519     if (V != &Sel)
2520       return replaceInstUsesWith(Sel, V);
2521     return &Sel;
2522   }
2523 
2524   // A select of a "select shuffle" with a common operand can be rearranged
2525   // to select followed by "select shuffle". Because of poison, this only works
2526   // in the case of a shuffle with no undefined mask elements.
2527   Value *Cond = Sel.getCondition();
2528   Value *TVal = Sel.getTrueValue();
2529   Value *FVal = Sel.getFalseValue();
2530   Value *X, *Y;
2531   ArrayRef<int> Mask;
2532   if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2533       !is_contained(Mask, UndefMaskElem) &&
2534       cast<ShuffleVectorInst>(TVal)->isSelect()) {
2535     if (X == FVal) {
2536       // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2537       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2538       return new ShuffleVectorInst(X, NewSel, Mask);
2539     }
2540     if (Y == FVal) {
2541       // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2542       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2543       return new ShuffleVectorInst(NewSel, Y, Mask);
2544     }
2545   }
2546   if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2547       !is_contained(Mask, UndefMaskElem) &&
2548       cast<ShuffleVectorInst>(FVal)->isSelect()) {
2549     if (X == TVal) {
2550       // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2551       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2552       return new ShuffleVectorInst(X, NewSel, Mask);
2553     }
2554     if (Y == TVal) {
2555       // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2556       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2557       return new ShuffleVectorInst(NewSel, Y, Mask);
2558     }
2559   }
2560 
2561   return nullptr;
2562 }
2563 
2564 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2565                                         const DominatorTree &DT,
2566                                         InstCombiner::BuilderTy &Builder) {
2567   // Find the block's immediate dominator that ends with a conditional branch
2568   // that matches select's condition (maybe inverted).
2569   auto *IDomNode = DT[BB]->getIDom();
2570   if (!IDomNode)
2571     return nullptr;
2572   BasicBlock *IDom = IDomNode->getBlock();
2573 
2574   Value *Cond = Sel.getCondition();
2575   Value *IfTrue, *IfFalse;
2576   BasicBlock *TrueSucc, *FalseSucc;
2577   if (match(IDom->getTerminator(),
2578             m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2579                  m_BasicBlock(FalseSucc)))) {
2580     IfTrue = Sel.getTrueValue();
2581     IfFalse = Sel.getFalseValue();
2582   } else if (match(IDom->getTerminator(),
2583                    m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2584                         m_BasicBlock(FalseSucc)))) {
2585     IfTrue = Sel.getFalseValue();
2586     IfFalse = Sel.getTrueValue();
2587   } else
2588     return nullptr;
2589 
2590   // Make sure the branches are actually different.
2591   if (TrueSucc == FalseSucc)
2592     return nullptr;
2593 
2594   // We want to replace select %cond, %a, %b with a phi that takes value %a
2595   // for all incoming edges that are dominated by condition `%cond == true`,
2596   // and value %b for edges dominated by condition `%cond == false`. If %a
2597   // or %b are also phis from the same basic block, we can go further and take
2598   // their incoming values from the corresponding blocks.
2599   BasicBlockEdge TrueEdge(IDom, TrueSucc);
2600   BasicBlockEdge FalseEdge(IDom, FalseSucc);
2601   DenseMap<BasicBlock *, Value *> Inputs;
2602   for (auto *Pred : predecessors(BB)) {
2603     // Check implication.
2604     BasicBlockEdge Incoming(Pred, BB);
2605     if (DT.dominates(TrueEdge, Incoming))
2606       Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2607     else if (DT.dominates(FalseEdge, Incoming))
2608       Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2609     else
2610       return nullptr;
2611     // Check availability.
2612     if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2613       if (!DT.dominates(Insn, Pred->getTerminator()))
2614         return nullptr;
2615   }
2616 
2617   Builder.SetInsertPoint(&*BB->begin());
2618   auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2619   for (auto *Pred : predecessors(BB))
2620     PN->addIncoming(Inputs[Pred], Pred);
2621   PN->takeName(&Sel);
2622   return PN;
2623 }
2624 
2625 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2626                                     InstCombiner::BuilderTy &Builder) {
2627   // Try to replace this select with Phi in one of these blocks.
2628   SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2629   CandidateBlocks.insert(Sel.getParent());
2630   for (Value *V : Sel.operands())
2631     if (auto *I = dyn_cast<Instruction>(V))
2632       CandidateBlocks.insert(I->getParent());
2633 
2634   for (BasicBlock *BB : CandidateBlocks)
2635     if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2636       return PN;
2637   return nullptr;
2638 }
2639 
2640 static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
2641   FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition());
2642   if (!FI)
2643     return nullptr;
2644 
2645   Value *Cond = FI->getOperand(0);
2646   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
2647 
2648   //   select (freeze(x == y)), x, y --> y
2649   //   select (freeze(x != y)), x, y --> x
2650   // The freeze should be only used by this select. Otherwise, remaining uses of
2651   // the freeze can observe a contradictory value.
2652   //   c = freeze(x == y)   ; Let's assume that y = poison & x = 42; c is 0 or 1
2653   //   a = select c, x, y   ;
2654   //   f(a, c)              ; f(poison, 1) cannot happen, but if a is folded
2655   //                        ; to y, this can happen.
2656   CmpInst::Predicate Pred;
2657   if (FI->hasOneUse() &&
2658       match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) &&
2659       (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) {
2660     return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal;
2661   }
2662 
2663   return nullptr;
2664 }
2665 
2666 Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
2667                                                                  SelectInst &SI,
2668                                                                  bool IsAnd) {
2669   Value *CondVal = SI.getCondition();
2670   Value *A = SI.getTrueValue();
2671   Value *B = SI.getFalseValue();
2672 
2673   assert(Op->getType()->isIntOrIntVectorTy(1) &&
2674          "Op must be either i1 or vector of i1.");
2675 
2676   Optional<bool> Res = isImpliedCondition(Op, CondVal, DL, IsAnd);
2677   if (!Res)
2678     return nullptr;
2679 
2680   Value *Zero = Constant::getNullValue(A->getType());
2681   Value *One = Constant::getAllOnesValue(A->getType());
2682 
2683   if (*Res == true) {
2684     if (IsAnd)
2685       // select op, (select cond, A, B), false => select op, A, false
2686       // and    op, (select cond, A, B)        => select op, A, false
2687       //   if op = true implies condval = true.
2688       return SelectInst::Create(Op, A, Zero);
2689     else
2690       // select op, true, (select cond, A, B) => select op, true, A
2691       // or     op, (select cond, A, B)       => select op, true, A
2692       //   if op = false implies condval = true.
2693       return SelectInst::Create(Op, One, A);
2694   } else {
2695     if (IsAnd)
2696       // select op, (select cond, A, B), false => select op, B, false
2697       // and    op, (select cond, A, B)        => select op, B, false
2698       //   if op = true implies condval = false.
2699       return SelectInst::Create(Op, B, Zero);
2700     else
2701       // select op, true, (select cond, A, B) => select op, true, B
2702       // or     op, (select cond, A, B)       => select op, true, B
2703       //   if op = false implies condval = false.
2704       return SelectInst::Create(Op, One, B);
2705   }
2706 }
2707 
2708 Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
2709   Value *CondVal = SI.getCondition();
2710   Value *TrueVal = SI.getTrueValue();
2711   Value *FalseVal = SI.getFalseValue();
2712   Type *SelType = SI.getType();
2713 
2714   // FIXME: Remove this workaround when freeze related patches are done.
2715   // For select with undef operand which feeds into an equality comparison,
2716   // don't simplify it so loop unswitch can know the equality comparison
2717   // may have an undef operand. This is a workaround for PR31652 caused by
2718   // descrepancy about branch on undef between LoopUnswitch and GVN.
2719   if (match(TrueVal, m_Undef()) || match(FalseVal, m_Undef())) {
2720     if (llvm::any_of(SI.users(), [&](User *U) {
2721           ICmpInst *CI = dyn_cast<ICmpInst>(U);
2722           if (CI && CI->isEquality())
2723             return true;
2724           return false;
2725         })) {
2726       return nullptr;
2727     }
2728   }
2729 
2730   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
2731                                     SQ.getWithInstruction(&SI)))
2732     return replaceInstUsesWith(SI, V);
2733 
2734   if (Instruction *I = canonicalizeSelectToShuffle(SI))
2735     return I;
2736 
2737   if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
2738     return I;
2739 
2740   CmpInst::Predicate Pred;
2741 
2742   // Avoid potential infinite loops by checking for non-constant condition.
2743   // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
2744   //       Scalar select must have simplified?
2745   if (SelType->isIntOrIntVectorTy(1) && !isa<Constant>(CondVal) &&
2746       TrueVal->getType() == CondVal->getType()) {
2747     // Folding select to and/or i1 isn't poison safe in general. impliesPoison
2748     // checks whether folding it does not convert a well-defined value into
2749     // poison.
2750     if (match(TrueVal, m_One()) && impliesPoison(FalseVal, CondVal)) {
2751       // Change: A = select B, true, C --> A = or B, C
2752       return BinaryOperator::CreateOr(CondVal, FalseVal);
2753     }
2754     if (match(FalseVal, m_Zero()) && impliesPoison(TrueVal, CondVal)) {
2755       // Change: A = select B, C, false --> A = and B, C
2756       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2757     }
2758 
2759     auto *One = ConstantInt::getTrue(SelType);
2760     auto *Zero = ConstantInt::getFalse(SelType);
2761 
2762     // We match the "full" 0 or 1 constant here to avoid a potential infinite
2763     // loop with vectors that may have undefined/poison elements.
2764     // select a, false, b -> select !a, b, false
2765     if (match(TrueVal, m_Specific(Zero))) {
2766       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2767       return SelectInst::Create(NotCond, FalseVal, Zero);
2768     }
2769     // select a, b, true -> select !a, true, b
2770     if (match(FalseVal, m_Specific(One))) {
2771       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2772       return SelectInst::Create(NotCond, One, TrueVal);
2773     }
2774 
2775     // select a, a, b -> select a, true, b
2776     if (CondVal == TrueVal)
2777       return replaceOperand(SI, 1, One);
2778     // select a, b, a -> select a, b, false
2779     if (CondVal == FalseVal)
2780       return replaceOperand(SI, 2, Zero);
2781 
2782     // select a, !a, b -> select !a, b, false
2783     if (match(TrueVal, m_Not(m_Specific(CondVal))))
2784       return SelectInst::Create(TrueVal, FalseVal, Zero);
2785     // select a, b, !a -> select !a, true, b
2786     if (match(FalseVal, m_Not(m_Specific(CondVal))))
2787       return SelectInst::Create(FalseVal, One, TrueVal);
2788 
2789     Value *A, *B;
2790 
2791     // DeMorgan in select form: !a && !b --> !(a || b)
2792     // select !a, !b, false --> not (select a, true, b)
2793     if (match(&SI, m_LogicalAnd(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
2794         (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
2795         !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
2796       return BinaryOperator::CreateNot(Builder.CreateSelect(A, One, B));
2797 
2798     // DeMorgan in select form: !a || !b --> !(a && b)
2799     // select !a, true, !b --> not (select a, b, false)
2800     if (match(&SI, m_LogicalOr(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
2801         (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
2802         !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
2803       return BinaryOperator::CreateNot(Builder.CreateSelect(A, B, Zero));
2804 
2805     // select (select a, true, b), true, b -> select a, true, b
2806     if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
2807         match(TrueVal, m_One()) && match(FalseVal, m_Specific(B)))
2808       return replaceOperand(SI, 0, A);
2809     // select (select a, b, false), b, false -> select a, b, false
2810     if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) &&
2811         match(TrueVal, m_Specific(B)) && match(FalseVal, m_Zero()))
2812       return replaceOperand(SI, 0, A);
2813 
2814     if (!SelType->isVectorTy()) {
2815       if (Value *S = simplifyWithOpReplaced(TrueVal, CondVal, One, SQ,
2816                                             /* AllowRefinement */ true))
2817         return replaceOperand(SI, 1, S);
2818       if (Value *S = simplifyWithOpReplaced(FalseVal, CondVal, Zero, SQ,
2819                                             /* AllowRefinement */ true))
2820         return replaceOperand(SI, 2, S);
2821     }
2822 
2823     if (match(FalseVal, m_Zero()) || match(TrueVal, m_One())) {
2824       Use *Y = nullptr;
2825       bool IsAnd = match(FalseVal, m_Zero()) ? true : false;
2826       Value *Op1 = IsAnd ? TrueVal : FalseVal;
2827       if (isCheckForZeroAndMulWithOverflow(CondVal, Op1, IsAnd, Y)) {
2828         auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
2829         InsertNewInstBefore(FI, *cast<Instruction>(Y->getUser()));
2830         replaceUse(*Y, FI);
2831         return replaceInstUsesWith(SI, Op1);
2832       }
2833 
2834       if (auto *Op1SI = dyn_cast<SelectInst>(Op1))
2835         if (auto *I = foldAndOrOfSelectUsingImpliedCond(CondVal, *Op1SI,
2836                                                         /* IsAnd */ IsAnd))
2837           return I;
2838 
2839       if (auto *ICmp0 = dyn_cast<ICmpInst>(CondVal)) {
2840         if (auto *ICmp1 = dyn_cast<ICmpInst>(Op1)) {
2841           if (auto *V = foldAndOrOfICmpsOfAndWithPow2(ICmp0, ICmp1, &SI, IsAnd,
2842                                                       /* IsLogical */ true))
2843             return replaceInstUsesWith(SI, V);
2844 
2845           if (auto *V = foldEqOfParts(ICmp0, ICmp1, IsAnd))
2846             return replaceInstUsesWith(SI, V);
2847         }
2848       }
2849     }
2850 
2851     // select (select a, true, b), c, false -> select a, c, false
2852     // select c, (select a, true, b), false -> select c, a, false
2853     //   if c implies that b is false.
2854     if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
2855         match(FalseVal, m_Zero())) {
2856       Optional<bool> Res = isImpliedCondition(TrueVal, B, DL);
2857       if (Res && *Res == false)
2858         return replaceOperand(SI, 0, A);
2859     }
2860     if (match(TrueVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
2861         match(FalseVal, m_Zero())) {
2862       Optional<bool> Res = isImpliedCondition(CondVal, B, DL);
2863       if (Res && *Res == false)
2864         return replaceOperand(SI, 1, A);
2865     }
2866     // select c, true, (select a, b, false)  -> select c, true, a
2867     // select (select a, b, false), true, c  -> select a, true, c
2868     //   if c = false implies that b = true
2869     if (match(TrueVal, m_One()) &&
2870         match(FalseVal, m_Select(m_Value(A), m_Value(B), m_Zero()))) {
2871       Optional<bool> Res = isImpliedCondition(CondVal, B, DL, false);
2872       if (Res && *Res == true)
2873         return replaceOperand(SI, 2, A);
2874     }
2875     if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) &&
2876         match(TrueVal, m_One())) {
2877       Optional<bool> Res = isImpliedCondition(FalseVal, B, DL, false);
2878       if (Res && *Res == true)
2879         return replaceOperand(SI, 0, A);
2880     }
2881 
2882     // sel (sel c, a, false), true, (sel !c, b, false) -> sel c, a, b
2883     // sel (sel !c, a, false), true, (sel c, b, false) -> sel c, b, a
2884     Value *C1, *C2;
2885     if (match(CondVal, m_Select(m_Value(C1), m_Value(A), m_Zero())) &&
2886         match(TrueVal, m_One()) &&
2887         match(FalseVal, m_Select(m_Value(C2), m_Value(B), m_Zero()))) {
2888       if (match(C2, m_Not(m_Specific(C1)))) // first case
2889         return SelectInst::Create(C1, A, B);
2890       else if (match(C1, m_Not(m_Specific(C2)))) // second case
2891         return SelectInst::Create(C2, B, A);
2892     }
2893   }
2894 
2895   // Selecting between two integer or vector splat integer constants?
2896   //
2897   // Note that we don't handle a scalar select of vectors:
2898   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2899   // because that may need 3 instructions to splat the condition value:
2900   // extend, insertelement, shufflevector.
2901   //
2902   // Do not handle i1 TrueVal and FalseVal otherwise would result in
2903   // zext/sext i1 to i1.
2904   if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(1) &&
2905       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2906     // select C, 1, 0 -> zext C to int
2907     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2908       return new ZExtInst(CondVal, SelType);
2909 
2910     // select C, -1, 0 -> sext C to int
2911     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2912       return new SExtInst(CondVal, SelType);
2913 
2914     // select C, 0, 1 -> zext !C to int
2915     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2916       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2917       return new ZExtInst(NotCond, SelType);
2918     }
2919 
2920     // select C, 0, -1 -> sext !C to int
2921     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2922       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2923       return new SExtInst(NotCond, SelType);
2924     }
2925   }
2926 
2927   if (auto *FCmp = dyn_cast<FCmpInst>(CondVal)) {
2928     Value *Cmp0 = FCmp->getOperand(0), *Cmp1 = FCmp->getOperand(1);
2929     // Are we selecting a value based on a comparison of the two values?
2930     if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
2931         (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2932       // Canonicalize to use ordered comparisons by swapping the select
2933       // operands.
2934       //
2935       // e.g.
2936       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2937       if (FCmp->hasOneUse() && FCmpInst::isUnordered(FCmp->getPredicate())) {
2938         FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
2939         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2940         // FIXME: The FMF should propagate from the select, not the fcmp.
2941         Builder.setFastMathFlags(FCmp->getFastMathFlags());
2942         Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2943                                             FCmp->getName() + ".inv");
2944         Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
2945         return replaceInstUsesWith(SI, NewSel);
2946       }
2947 
2948       // NOTE: if we wanted to, this is where to detect MIN/MAX
2949     }
2950   }
2951 
2952   // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2953   // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
2954   // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2955   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2956       match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2957       (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2958     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, &SI);
2959     return replaceInstUsesWith(SI, Fabs);
2960   }
2961   // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
2962   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2963       match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2964       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2965     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, &SI);
2966     return replaceInstUsesWith(SI, Fabs);
2967   }
2968   // With nnan and nsz:
2969   // (X <  +/-0.0) ? -X : X --> fabs(X)
2970   // (X <= +/-0.0) ? -X : X --> fabs(X)
2971   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2972       match(TrueVal, m_FNeg(m_Specific(FalseVal))) && SI.hasNoSignedZeros() &&
2973       (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2974        Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2975     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, &SI);
2976     return replaceInstUsesWith(SI, Fabs);
2977   }
2978   // With nnan and nsz:
2979   // (X >  +/-0.0) ? X : -X --> fabs(X)
2980   // (X >= +/-0.0) ? X : -X --> fabs(X)
2981   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2982       match(FalseVal, m_FNeg(m_Specific(TrueVal))) && SI.hasNoSignedZeros() &&
2983       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2984        Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2985     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, &SI);
2986     return replaceInstUsesWith(SI, Fabs);
2987   }
2988 
2989   // See if we are selecting two values based on a comparison of the two values.
2990   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2991     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2992       return Result;
2993 
2994   if (Instruction *Add = foldAddSubSelect(SI, Builder))
2995     return Add;
2996   if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2997     return Add;
2998   if (Instruction *Or = foldSetClearBits(SI, Builder))
2999     return Or;
3000   if (Instruction *Mul = foldSelectZeroOrMul(SI, *this))
3001     return Mul;
3002 
3003   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3004   auto *TI = dyn_cast<Instruction>(TrueVal);
3005   auto *FI = dyn_cast<Instruction>(FalseVal);
3006   if (TI && FI && TI->getOpcode() == FI->getOpcode())
3007     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
3008       return IV;
3009 
3010   if (Instruction *I = foldSelectExtConst(SI))
3011     return I;
3012 
3013   // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
3014   // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
3015   auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
3016                                bool Swap) -> GetElementPtrInst * {
3017     Value *Ptr = Gep->getPointerOperand();
3018     if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
3019         !Gep->hasOneUse())
3020       return nullptr;
3021     Value *Idx = Gep->getOperand(1);
3022     if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType()))
3023       return nullptr;
3024     Type *ElementType = Gep->getResultElementType();
3025     Value *NewT = Idx;
3026     Value *NewF = Constant::getNullValue(Idx->getType());
3027     if (Swap)
3028       std::swap(NewT, NewF);
3029     Value *NewSI =
3030         Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
3031     return GetElementPtrInst::Create(ElementType, Ptr, {NewSI});
3032   };
3033   if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
3034     if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
3035       return NewGep;
3036   if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
3037     if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
3038       return NewGep;
3039 
3040   // See if we can fold the select into one of our operands.
3041   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
3042     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
3043       return FoldI;
3044 
3045     Value *LHS, *RHS;
3046     Instruction::CastOps CastOp;
3047     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
3048     auto SPF = SPR.Flavor;
3049     if (SPF) {
3050       Value *LHS2, *RHS2;
3051       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
3052         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
3053                                           RHS2, SI, SPF, RHS))
3054           return R;
3055       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
3056         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
3057                                           RHS2, SI, SPF, LHS))
3058           return R;
3059       // TODO.
3060       // ABS(-X) -> ABS(X)
3061     }
3062 
3063     if (SelectPatternResult::isMinOrMax(SPF)) {
3064       // Canonicalize so that
3065       // - type casts are outside select patterns.
3066       // - float clamp is transformed to min/max pattern
3067 
3068       bool IsCastNeeded = LHS->getType() != SelType;
3069       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
3070       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
3071       if (IsCastNeeded ||
3072           (LHS->getType()->isFPOrFPVectorTy() &&
3073            ((CmpLHS != LHS && CmpLHS != RHS) ||
3074             (CmpRHS != LHS && CmpRHS != RHS)))) {
3075         CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
3076 
3077         Value *Cmp;
3078         if (CmpInst::isIntPredicate(MinMaxPred)) {
3079           Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
3080         } else {
3081           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3082           auto FMF =
3083               cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
3084           Builder.setFastMathFlags(FMF);
3085           Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
3086         }
3087 
3088         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
3089         if (!IsCastNeeded)
3090           return replaceInstUsesWith(SI, NewSI);
3091 
3092         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
3093         return replaceInstUsesWith(SI, NewCast);
3094       }
3095 
3096       // MAX(~a, ~b) -> ~MIN(a, b)
3097       // MAX(~a, C)  -> ~MIN(a, ~C)
3098       // MIN(~a, ~b) -> ~MAX(a, b)
3099       // MIN(~a, C)  -> ~MAX(a, ~C)
3100       auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
3101         Value *A;
3102         if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
3103             !isFreeToInvert(A, A->hasOneUse()) &&
3104             // Passing false to only consider m_Not and constants.
3105             isFreeToInvert(Y, false)) {
3106           Value *B = Builder.CreateNot(Y);
3107           Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
3108                                           A, B);
3109           // Copy the profile metadata.
3110           if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
3111             cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
3112             // Swap the metadata if the operands are swapped.
3113             if (X == SI.getFalseValue() && Y == SI.getTrueValue())
3114               cast<SelectInst>(NewMinMax)->swapProfMetadata();
3115           }
3116 
3117           return BinaryOperator::CreateNot(NewMinMax);
3118         }
3119 
3120         return nullptr;
3121       };
3122 
3123       if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
3124         return I;
3125       if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
3126         return I;
3127 
3128       if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
3129         return I;
3130 
3131       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
3132         return I;
3133       if (Instruction *I = matchSAddSubSat(SI))
3134         return I;
3135     }
3136   }
3137 
3138   // Canonicalize select of FP values where NaN and -0.0 are not valid as
3139   // minnum/maxnum intrinsics.
3140   if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
3141     Value *X, *Y;
3142     if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
3143       return replaceInstUsesWith(
3144           SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
3145 
3146     if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
3147       return replaceInstUsesWith(
3148           SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
3149   }
3150 
3151   // See if we can fold the select into a phi node if the condition is a select.
3152   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
3153     // The true/false values have to be live in the PHI predecessor's blocks.
3154     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
3155         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
3156       if (Instruction *NV = foldOpIntoPhi(SI, PN))
3157         return NV;
3158 
3159   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
3160     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
3161       // select(C, select(C, a, b), c) -> select(C, a, c)
3162       if (TrueSI->getCondition() == CondVal) {
3163         if (SI.getTrueValue() == TrueSI->getTrueValue())
3164           return nullptr;
3165         return replaceOperand(SI, 1, TrueSI->getTrueValue());
3166       }
3167       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
3168       // We choose this as normal form to enable folding on the And and
3169       // shortening paths for the values (this helps getUnderlyingObjects() for
3170       // example).
3171       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
3172         Value *And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition());
3173         replaceOperand(SI, 0, And);
3174         replaceOperand(SI, 1, TrueSI->getTrueValue());
3175         return &SI;
3176       }
3177     }
3178   }
3179   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
3180     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
3181       // select(C, a, select(C, b, c)) -> select(C, a, c)
3182       if (FalseSI->getCondition() == CondVal) {
3183         if (SI.getFalseValue() == FalseSI->getFalseValue())
3184           return nullptr;
3185         return replaceOperand(SI, 2, FalseSI->getFalseValue());
3186       }
3187       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
3188       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
3189         Value *Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition());
3190         replaceOperand(SI, 0, Or);
3191         replaceOperand(SI, 2, FalseSI->getFalseValue());
3192         return &SI;
3193       }
3194     }
3195   }
3196 
3197   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
3198     // The select might be preventing a division by 0.
3199     switch (BO->getOpcode()) {
3200     default:
3201       return true;
3202     case Instruction::SRem:
3203     case Instruction::URem:
3204     case Instruction::SDiv:
3205     case Instruction::UDiv:
3206       return false;
3207     }
3208   };
3209 
3210   // Try to simplify a binop sandwiched between 2 selects with the same
3211   // condition.
3212   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
3213   BinaryOperator *TrueBO;
3214   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
3215       canMergeSelectThroughBinop(TrueBO)) {
3216     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
3217       if (TrueBOSI->getCondition() == CondVal) {
3218         replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
3219         Worklist.push(TrueBO);
3220         return &SI;
3221       }
3222     }
3223     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
3224       if (TrueBOSI->getCondition() == CondVal) {
3225         replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
3226         Worklist.push(TrueBO);
3227         return &SI;
3228       }
3229     }
3230   }
3231 
3232   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
3233   BinaryOperator *FalseBO;
3234   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
3235       canMergeSelectThroughBinop(FalseBO)) {
3236     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
3237       if (FalseBOSI->getCondition() == CondVal) {
3238         replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
3239         Worklist.push(FalseBO);
3240         return &SI;
3241       }
3242     }
3243     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
3244       if (FalseBOSI->getCondition() == CondVal) {
3245         replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
3246         Worklist.push(FalseBO);
3247         return &SI;
3248       }
3249     }
3250   }
3251 
3252   Value *NotCond;
3253   if (match(CondVal, m_Not(m_Value(NotCond))) &&
3254       !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
3255     replaceOperand(SI, 0, NotCond);
3256     SI.swapValues();
3257     SI.swapProfMetadata();
3258     return &SI;
3259   }
3260 
3261   if (Instruction *I = foldVectorSelect(SI))
3262     return I;
3263 
3264   // If we can compute the condition, there's no need for a select.
3265   // Like the above fold, we are attempting to reduce compile-time cost by
3266   // putting this fold here with limitations rather than in InstSimplify.
3267   // The motivation for this call into value tracking is to take advantage of
3268   // the assumption cache, so make sure that is populated.
3269   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
3270     KnownBits Known(1);
3271     computeKnownBits(CondVal, Known, 0, &SI);
3272     if (Known.One.isOne())
3273       return replaceInstUsesWith(SI, TrueVal);
3274     if (Known.Zero.isOne())
3275       return replaceInstUsesWith(SI, FalseVal);
3276   }
3277 
3278   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
3279     return BitCastSel;
3280 
3281   // Simplify selects that test the returned flag of cmpxchg instructions.
3282   if (Value *V = foldSelectCmpXchg(SI))
3283     return replaceInstUsesWith(SI, V);
3284 
3285   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
3286     return Select;
3287 
3288   if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
3289     return Funnel;
3290 
3291   if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
3292     return Copysign;
3293 
3294   if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
3295     return replaceInstUsesWith(SI, PN);
3296 
3297   if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder))
3298     return replaceInstUsesWith(SI, Fr);
3299 
3300   // select(mask, mload(,,mask,0), 0) -> mload(,,mask,0)
3301   // Load inst is intentionally not checked for hasOneUse()
3302   if (match(FalseVal, m_Zero()) &&
3303       match(TrueVal, m_MaskedLoad(m_Value(), m_Value(), m_Specific(CondVal),
3304                                   m_CombineOr(m_Undef(), m_Zero())))) {
3305     auto *MaskedLoad = cast<IntrinsicInst>(TrueVal);
3306     if (isa<UndefValue>(MaskedLoad->getArgOperand(3)))
3307       MaskedLoad->setArgOperand(3, FalseVal /* Zero */);
3308     return replaceInstUsesWith(SI, MaskedLoad);
3309   }
3310 
3311   Value *Mask;
3312   if (match(TrueVal, m_Zero()) &&
3313       match(FalseVal, m_MaskedLoad(m_Value(), m_Value(), m_Value(Mask),
3314                                    m_CombineOr(m_Undef(), m_Zero()))) &&
3315       (CondVal->getType() == Mask->getType())) {
3316     // We can remove the select by ensuring the load zeros all lanes the
3317     // select would have.  We determine this by proving there is no overlap
3318     // between the load and select masks.
3319     // (i.e (load_mask & select_mask) == 0 == no overlap)
3320     bool CanMergeSelectIntoLoad = false;
3321     if (Value *V = SimplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI)))
3322       CanMergeSelectIntoLoad = match(V, m_Zero());
3323 
3324     if (CanMergeSelectIntoLoad) {
3325       auto *MaskedLoad = cast<IntrinsicInst>(FalseVal);
3326       if (isa<UndefValue>(MaskedLoad->getArgOperand(3)))
3327         MaskedLoad->setArgOperand(3, TrueVal /* Zero */);
3328       return replaceInstUsesWith(SI, MaskedLoad);
3329     }
3330   }
3331 
3332   return nullptr;
3333 }
3334