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