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