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