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