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