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