1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitSelect function.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CmpInstAnalysis.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
41 #include <cassert>
42 #include <utility>
43 
44 using namespace llvm;
45 using namespace PatternMatch;
46 
47 #define DEBUG_TYPE "instcombine"
48 
49 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
50                            SelectPatternFlavor SPF, Value *A, Value *B) {
51   CmpInst::Predicate Pred = getMinMaxPred(SPF);
52   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
53   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
54 }
55 
56 /// Replace a select operand based on an equality comparison with the identity
57 /// constant of a binop.
58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
59                                             const TargetLibraryInfo &TLI) {
60   // The select condition must be an equality compare with a constant operand.
61   Value *X;
62   Constant *C;
63   CmpInst::Predicate Pred;
64   if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
65     return nullptr;
66 
67   bool IsEq;
68   if (ICmpInst::isEquality(Pred))
69     IsEq = Pred == ICmpInst::ICMP_EQ;
70   else if (Pred == FCmpInst::FCMP_OEQ)
71     IsEq = true;
72   else if (Pred == FCmpInst::FCMP_UNE)
73     IsEq = false;
74   else
75     return nullptr;
76 
77   // A select operand must be a binop.
78   BinaryOperator *BO;
79   if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
80     return nullptr;
81 
82   // The compare constant must be the identity constant for that binop.
83   // If this a floating-point compare with 0.0, any zero constant will do.
84   Type *Ty = BO->getType();
85   Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
86   if (IdC != C) {
87     if (!IdC || !CmpInst::isFPPredicate(Pred))
88       return nullptr;
89     if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
90       return nullptr;
91   }
92 
93   // Last, match the compare variable operand with a binop operand.
94   Value *Y;
95   if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
96     return nullptr;
97   if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
98     return nullptr;
99 
100   // +0.0 compares equal to -0.0, and so it does not behave as required for this
101   // transform. Bail out if we can not exclude that possibility.
102   if (isa<FPMathOperator>(BO))
103     if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
104       return nullptr;
105 
106   // BO = binop Y, X
107   // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
108   // =>
109   // S = { select (cmp eq X, C),  Y, ? } or { select (cmp ne X, C), ?,  Y }
110   Sel.setOperand(IsEq ? 1 : 2, Y);
111   return &Sel;
112 }
113 
114 /// This folds:
115 ///  select (icmp eq (and X, C1)), TC, FC
116 ///    iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117 /// To something like:
118 ///  (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
119 /// Or:
120 ///  (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121 /// With some variations depending if FC is larger than TC, or the shift
122 /// isn't needed, or the bit widths don't match.
123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
124                                 InstCombiner::BuilderTy &Builder) {
125   const APInt *SelTC, *SelFC;
126   if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127       !match(Sel.getFalseValue(), m_APInt(SelFC)))
128     return nullptr;
129 
130   // If this is a vector select, we need a vector compare.
131   Type *SelType = Sel.getType();
132   if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
133     return nullptr;
134 
135   Value *V;
136   APInt AndMask;
137   bool CreateAnd = false;
138   ICmpInst::Predicate Pred = Cmp->getPredicate();
139   if (ICmpInst::isEquality(Pred)) {
140     if (!match(Cmp->getOperand(1), m_Zero()))
141       return nullptr;
142 
143     V = Cmp->getOperand(0);
144     const APInt *AndRHS;
145     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
146       return nullptr;
147 
148     AndMask = *AndRHS;
149   } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
150                                   Pred, V, AndMask)) {
151     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
152     if (!AndMask.isPowerOf2())
153       return nullptr;
154 
155     CreateAnd = true;
156   } else {
157     return nullptr;
158   }
159 
160   // In general, when both constants are non-zero, we would need an offset to
161   // replace the select. This would require more instructions than we started
162   // with. But there's one special-case that we handle here because it can
163   // simplify/reduce the instructions.
164   APInt TC = *SelTC;
165   APInt FC = *SelFC;
166   if (!TC.isNullValue() && !FC.isNullValue()) {
167     // If the select constants differ by exactly one bit and that's the same
168     // bit that is masked and checked by the select condition, the select can
169     // be replaced by bitwise logic to set/clear one bit of the constant result.
170     if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
171       return nullptr;
172     if (CreateAnd) {
173       // If we have to create an 'and', then we must kill the cmp to not
174       // increase the instruction count.
175       if (!Cmp->hasOneUse())
176         return nullptr;
177       V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
178     }
179     bool ExtraBitInTC = TC.ugt(FC);
180     if (Pred == ICmpInst::ICMP_EQ) {
181       // If the masked bit in V is clear, clear or set the bit in the result:
182       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184       Constant *C = ConstantInt::get(SelType, TC);
185       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
186     }
187     if (Pred == ICmpInst::ICMP_NE) {
188       // If the masked bit in V is set, set or clear the bit in the result:
189       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191       Constant *C = ConstantInt::get(SelType, FC);
192       return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
193     }
194     llvm_unreachable("Only expecting equality predicates");
195   }
196 
197   // Make sure one of the select arms is a power-of-2.
198   if (!TC.isPowerOf2() && !FC.isPowerOf2())
199     return nullptr;
200 
201   // Determine which shift is needed to transform result of the 'and' into the
202   // desired result.
203   const APInt &ValC = !TC.isNullValue() ? TC : FC;
204   unsigned ValZeros = ValC.logBase2();
205   unsigned AndZeros = AndMask.logBase2();
206 
207   // Insert the 'and' instruction on the input to the truncate.
208   if (CreateAnd)
209     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
210 
211   // If types don't match, we can still convert the select by introducing a zext
212   // or a trunc of the 'and'.
213   if (ValZeros > AndZeros) {
214     V = Builder.CreateZExtOrTrunc(V, SelType);
215     V = Builder.CreateShl(V, ValZeros - AndZeros);
216   } else if (ValZeros < AndZeros) {
217     V = Builder.CreateLShr(V, AndZeros - ValZeros);
218     V = Builder.CreateZExtOrTrunc(V, SelType);
219   } else {
220     V = Builder.CreateZExtOrTrunc(V, SelType);
221   }
222 
223   // Okay, now we know that everything is set up, we just don't know whether we
224   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225   bool ShouldNotVal = !TC.isNullValue();
226   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
227   if (ShouldNotVal)
228     V = Builder.CreateXor(V, ValC);
229 
230   return V;
231 }
232 
233 /// We want to turn code that looks like this:
234 ///   %C = or %A, %B
235 ///   %D = select %cond, %C, %A
236 /// into:
237 ///   %C = select %cond, %B, 0
238 ///   %D = or %A, %C
239 ///
240 /// Assuming that the specified instruction is an operand to the select, return
241 /// a bitmask indicating which operands of this instruction are foldable if they
242 /// equal the other incoming value of the select.
243 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
244   switch (I->getOpcode()) {
245   case Instruction::Add:
246   case Instruction::Mul:
247   case Instruction::And:
248   case Instruction::Or:
249   case Instruction::Xor:
250     return 3;              // Can fold through either operand.
251   case Instruction::Sub:   // Can only fold on the amount subtracted.
252   case Instruction::Shl:   // Can only fold on the shift amount.
253   case Instruction::LShr:
254   case Instruction::AShr:
255     return 1;
256   default:
257     return 0;              // Cannot fold
258   }
259 }
260 
261 /// For the same transformation as the previous function, return the identity
262 /// constant that goes into the select.
263 static APInt getSelectFoldableConstant(BinaryOperator *I) {
264   switch (I->getOpcode()) {
265   default: llvm_unreachable("This cannot happen!");
266   case Instruction::Add:
267   case Instruction::Sub:
268   case Instruction::Or:
269   case Instruction::Xor:
270   case Instruction::Shl:
271   case Instruction::LShr:
272   case Instruction::AShr:
273     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
274   case Instruction::And:
275     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
276   case Instruction::Mul:
277     return APInt(I->getType()->getScalarSizeInBits(), 1);
278   }
279 }
280 
281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
283                                           Instruction *FI) {
284   // Don't break up min/max patterns. The hasOneUse checks below prevent that
285   // for most cases, but vector min/max with bitcasts can be transformed. If the
286   // one-use restrictions are eased for other patterns, we still don't want to
287   // obfuscate min/max.
288   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289        match(&SI, m_SMax(m_Value(), m_Value())) ||
290        match(&SI, m_UMin(m_Value(), m_Value())) ||
291        match(&SI, m_UMax(m_Value(), m_Value()))))
292     return nullptr;
293 
294   // If this is a cast from the same type, merge.
295   if (TI->getNumOperands() == 1 && TI->isCast()) {
296     Type *FIOpndTy = FI->getOperand(0)->getType();
297     if (TI->getOperand(0)->getType() != FIOpndTy)
298       return nullptr;
299 
300     // The select condition may be a vector. We may only change the operand
301     // type if the vector width remains the same (and matches the condition).
302     Type *CondTy = SI.getCondition()->getType();
303     if (CondTy->isVectorTy()) {
304       if (!FIOpndTy->isVectorTy())
305         return nullptr;
306       if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
307         return nullptr;
308 
309       // TODO: If the backend knew how to deal with casts better, we could
310       // remove this limitation. For now, there's too much potential to create
311       // worse codegen by promoting the select ahead of size-altering casts
312       // (PR28160).
313       //
314       // Note that ValueTracking's matchSelectPattern() looks through casts
315       // without checking 'hasOneUse' when it matches min/max patterns, so this
316       // transform may end up happening anyway.
317       if (TI->getOpcode() != Instruction::BitCast &&
318           (!TI->hasOneUse() || !FI->hasOneUse()))
319         return nullptr;
320     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
321       // TODO: The one-use restrictions for a scalar select could be eased if
322       // the fold of a select in visitLoadInst() was enhanced to match a pattern
323       // that includes a cast.
324       return nullptr;
325     }
326 
327     // Fold this by inserting a select from the input values.
328     Value *NewSI =
329         Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
330                              FI->getOperand(0), SI.getName() + ".v", &SI);
331     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
332                             TI->getType());
333   }
334 
335   // Only handle binary operators (including two-operand getelementptr) with
336   // one-use here. As with the cast case above, it may be possible to relax the
337   // one-use constraint, but that needs be examined carefully since it may not
338   // reduce the total number of instructions.
339   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
340       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
341       !TI->hasOneUse() || !FI->hasOneUse())
342     return nullptr;
343 
344   // Figure out if the operations have any operands in common.
345   Value *MatchOp, *OtherOpT, *OtherOpF;
346   bool MatchIsOpZero;
347   if (TI->getOperand(0) == FI->getOperand(0)) {
348     MatchOp  = TI->getOperand(0);
349     OtherOpT = TI->getOperand(1);
350     OtherOpF = FI->getOperand(1);
351     MatchIsOpZero = true;
352   } else if (TI->getOperand(1) == FI->getOperand(1)) {
353     MatchOp  = TI->getOperand(1);
354     OtherOpT = TI->getOperand(0);
355     OtherOpF = FI->getOperand(0);
356     MatchIsOpZero = false;
357   } else if (!TI->isCommutative()) {
358     return nullptr;
359   } else if (TI->getOperand(0) == FI->getOperand(1)) {
360     MatchOp  = TI->getOperand(0);
361     OtherOpT = TI->getOperand(1);
362     OtherOpF = FI->getOperand(0);
363     MatchIsOpZero = true;
364   } else if (TI->getOperand(1) == FI->getOperand(0)) {
365     MatchOp  = TI->getOperand(1);
366     OtherOpT = TI->getOperand(0);
367     OtherOpF = FI->getOperand(1);
368     MatchIsOpZero = true;
369   } else {
370     return nullptr;
371   }
372 
373   // If the select condition is a vector, the operands of the original select's
374   // operands also must be vectors. This may not be the case for getelementptr
375   // for example.
376   if (SI.getCondition()->getType()->isVectorTy() &&
377       (!OtherOpT->getType()->isVectorTy() ||
378        !OtherOpF->getType()->isVectorTy()))
379     return nullptr;
380 
381   // If we reach here, they do have operations in common.
382   Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
383                                       SI.getName() + ".v", &SI);
384   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
385   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
386   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
387     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
388     NewBO->copyIRFlags(TI);
389     NewBO->andIRFlags(FI);
390     return NewBO;
391   }
392   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
393     auto *FGEP = cast<GetElementPtrInst>(FI);
394     Type *ElementType = TGEP->getResultElementType();
395     return TGEP->isInBounds() && FGEP->isInBounds()
396                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
397                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
398   }
399   llvm_unreachable("Expected BinaryOperator or GEP");
400   return nullptr;
401 }
402 
403 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
404   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
405     return false;
406   return C1I.isOneValue() || C1I.isAllOnesValue() ||
407          C2I.isOneValue() || C2I.isAllOnesValue();
408 }
409 
410 /// Try to fold the select into one of the operands to allow further
411 /// optimization.
412 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
413                                             Value *FalseVal) {
414   // See the comment above GetSelectFoldableOperands for a description of the
415   // transformation we are doing here.
416   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
417     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
418       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
419         unsigned OpToFold = 0;
420         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
421           OpToFold = 1;
422         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
423           OpToFold = 2;
424         }
425 
426         if (OpToFold) {
427           APInt CI = getSelectFoldableConstant(TVI);
428           Value *OOp = TVI->getOperand(2-OpToFold);
429           // Avoid creating select between 2 constants unless it's selecting
430           // between 0, 1 and -1.
431           const APInt *OOpC;
432           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
433           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
434             Value *C = ConstantInt::get(OOp->getType(), CI);
435             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
436             NewSel->takeName(TVI);
437             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
438                                                         FalseVal, NewSel);
439             BO->copyIRFlags(TVI);
440             return BO;
441           }
442         }
443       }
444     }
445   }
446 
447   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
448     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
449       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
450         unsigned OpToFold = 0;
451         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
452           OpToFold = 1;
453         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
454           OpToFold = 2;
455         }
456 
457         if (OpToFold) {
458           APInt CI = getSelectFoldableConstant(FVI);
459           Value *OOp = FVI->getOperand(2-OpToFold);
460           // Avoid creating select between 2 constants unless it's selecting
461           // between 0, 1 and -1.
462           const APInt *OOpC;
463           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
464           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
465             Value *C = ConstantInt::get(OOp->getType(), CI);
466             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
467             NewSel->takeName(FVI);
468             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
469                                                         TrueVal, NewSel);
470             BO->copyIRFlags(FVI);
471             return BO;
472           }
473         }
474       }
475     }
476   }
477 
478   return nullptr;
479 }
480 
481 /// We want to turn:
482 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
483 /// into:
484 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
485 /// Note:
486 ///   Z may be 0 if lshr is missing.
487 /// Worst-case scenario is that we will replace 5 instructions with 5 different
488 /// instructions, but we got rid of select.
489 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
490                                          Value *TVal, Value *FVal,
491                                          InstCombiner::BuilderTy &Builder) {
492   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
493         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
494         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
495     return nullptr;
496 
497   // The TrueVal has general form of:  and %B, 1
498   Value *B;
499   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
500     return nullptr;
501 
502   // Where %B may be optionally shifted:  lshr %X, %Z.
503   Value *X, *Z;
504   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
505   if (!HasShift)
506     X = B;
507 
508   Value *Y;
509   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
510     return nullptr;
511 
512   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
513   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
514   Constant *One = ConstantInt::get(SelType, 1);
515   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
516   Value *FullMask = Builder.CreateOr(Y, MaskB);
517   Value *MaskedX = Builder.CreateAnd(X, FullMask);
518   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
519   return new ZExtInst(ICmpNeZero, SelType);
520 }
521 
522 /// We want to turn:
523 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
524 /// into:
525 ///   (or (shl (and X, C1), C3), Y)
526 /// iff:
527 ///   C1 and C2 are both powers of 2
528 /// where:
529 ///   C3 = Log(C2) - Log(C1)
530 ///
531 /// This transform handles cases where:
532 /// 1. The icmp predicate is inverted
533 /// 2. The select operands are reversed
534 /// 3. The magnitude of C2 and C1 are flipped
535 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
536                                   Value *FalseVal,
537                                   InstCombiner::BuilderTy &Builder) {
538   // Only handle integer compares. Also, if this is a vector select, we need a
539   // vector compare.
540   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
541       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
542     return nullptr;
543 
544   Value *CmpLHS = IC->getOperand(0);
545   Value *CmpRHS = IC->getOperand(1);
546 
547   Value *V;
548   unsigned C1Log;
549   bool IsEqualZero;
550   bool NeedAnd = false;
551   if (IC->isEquality()) {
552     if (!match(CmpRHS, m_Zero()))
553       return nullptr;
554 
555     const APInt *C1;
556     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
557       return nullptr;
558 
559     V = CmpLHS;
560     C1Log = C1->logBase2();
561     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
562   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
563              IC->getPredicate() == ICmpInst::ICMP_SGT) {
564     // We also need to recognize (icmp slt (trunc (X)), 0) and
565     // (icmp sgt (trunc (X)), -1).
566     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
567     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
568         (!IsEqualZero && !match(CmpRHS, m_Zero())))
569       return nullptr;
570 
571     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
572       return nullptr;
573 
574     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
575     NeedAnd = true;
576   } else {
577     return nullptr;
578   }
579 
580   const APInt *C2;
581   bool OrOnTrueVal = false;
582   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
583   if (!OrOnFalseVal)
584     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
585 
586   if (!OrOnFalseVal && !OrOnTrueVal)
587     return nullptr;
588 
589   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
590 
591   unsigned C2Log = C2->logBase2();
592 
593   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
594   bool NeedShift = C1Log != C2Log;
595   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
596                        V->getType()->getScalarSizeInBits();
597 
598   // Make sure we don't create more instructions than we save.
599   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
600   if ((NeedShift + NeedXor + NeedZExtTrunc) >
601       (IC->hasOneUse() + Or->hasOneUse()))
602     return nullptr;
603 
604   if (NeedAnd) {
605     // Insert the AND instruction on the input to the truncate.
606     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
607     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
608   }
609 
610   if (C2Log > C1Log) {
611     V = Builder.CreateZExtOrTrunc(V, Y->getType());
612     V = Builder.CreateShl(V, C2Log - C1Log);
613   } else if (C1Log > C2Log) {
614     V = Builder.CreateLShr(V, C1Log - C2Log);
615     V = Builder.CreateZExtOrTrunc(V, Y->getType());
616   } else
617     V = Builder.CreateZExtOrTrunc(V, Y->getType());
618 
619   if (NeedXor)
620     V = Builder.CreateXor(V, *C2);
621 
622   return Builder.CreateOr(V, Y);
623 }
624 
625 /// Transform patterns such as: (a > b) ? a - b : 0
626 /// into: ((a > b) ? a : b) - b)
627 /// This produces a canonical max pattern that is more easily recognized by the
628 /// backend and converted into saturated subtraction instructions if those
629 /// exist.
630 /// There are 8 commuted/swapped variants of this pattern.
631 /// TODO: Also support a - UMIN(a,b) patterns.
632 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
633                                             const Value *TrueVal,
634                                             const Value *FalseVal,
635                                             InstCombiner::BuilderTy &Builder) {
636   ICmpInst::Predicate Pred = ICI->getPredicate();
637   if (!ICmpInst::isUnsigned(Pred))
638     return nullptr;
639 
640   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
641   if (match(TrueVal, m_Zero())) {
642     Pred = ICmpInst::getInversePredicate(Pred);
643     std::swap(TrueVal, FalseVal);
644   }
645   if (!match(FalseVal, m_Zero()))
646     return nullptr;
647 
648   Value *A = ICI->getOperand(0);
649   Value *B = ICI->getOperand(1);
650   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
651     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
652     std::swap(A, B);
653     Pred = ICmpInst::getSwappedPredicate(Pred);
654   }
655 
656   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
657          "Unexpected isUnsigned predicate!");
658 
659   // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
660   bool IsNegative = false;
661   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
662     IsNegative = true;
663   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
664     return nullptr;
665 
666   // If sub is used anywhere else, we wouldn't be able to eliminate it
667   // afterwards.
668   if (!TrueVal->hasOneUse())
669     return nullptr;
670 
671   // All checks passed, convert to canonical unsigned saturated subtraction
672   // form: sub(max()).
673   // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
674   Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
675   return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
676 }
677 
678 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
679                                        InstCombiner::BuilderTy &Builder) {
680   if (!Cmp->hasOneUse())
681     return nullptr;
682 
683   // Canonicalize to 'ULT' to simplify matching below.
684   Value *Cmp0 = Cmp->getOperand(0);
685   Value *Cmp1 = Cmp->getOperand(1);
686   ICmpInst::Predicate Pred = Cmp->getPredicate();
687   if (Pred == ICmpInst::ICMP_UGT) {
688     Pred = ICmpInst::ICMP_ULT;
689     std::swap(Cmp0, Cmp1);
690   }
691 
692   if (Pred != ICmpInst::ICMP_ULT)
693     return nullptr;
694 
695   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
696   // TODO: There are more variations of this pattern.
697   Value *X, *Y;
698   if (match(TVal, m_AllOnes()) && match(Cmp0, m_Not(m_Value(X))) &&
699       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
700     // Change the comparison to use the sum (false value of the select). That is
701     // the canonical pattern match form for uadd.with.overflow and eliminates a
702     // use of the 'not' op:
703     // (~X u< Y) ? -1 : (X + Y) --> ((X + Y) u< Y) ? -1 : (X + Y)
704     // (~X u< Y) ? -1 : (Y + X) --> ((Y + X) u< Y) ? -1 : (Y + X)
705     Value *NewCmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, FVal, Y);
706     return Builder.CreateSelect(NewCmp, TVal, FVal);
707   }
708 
709   // Match unsigned saturated add with constant.
710   const APInt *C, *CmpC;
711   if (match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
712       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
713     // Commute compare predicate and select operands:
714     // (X u< ~C) ? (X + C) : -1 --> (X u> ~C) ? -1 : (X + C)
715     Value *NewCmp = Builder.CreateICmp(ICmpInst::ICMP_UGT, X, Cmp1);
716     return Builder.CreateSelect(NewCmp, FVal, TVal);
717   }
718 
719   return nullptr;
720 }
721 
722 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
723 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
724 ///
725 /// For example, we can fold the following code sequence:
726 /// \code
727 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
728 ///   %1 = icmp ne i32 %x, 0
729 ///   %2 = select i1 %1, i32 %0, i32 32
730 /// \code
731 ///
732 /// into:
733 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
734 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
735                                  InstCombiner::BuilderTy &Builder) {
736   ICmpInst::Predicate Pred = ICI->getPredicate();
737   Value *CmpLHS = ICI->getOperand(0);
738   Value *CmpRHS = ICI->getOperand(1);
739 
740   // Check if the condition value compares a value for equality against zero.
741   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
742     return nullptr;
743 
744   Value *Count = FalseVal;
745   Value *ValueOnZero = TrueVal;
746   if (Pred == ICmpInst::ICMP_NE)
747     std::swap(Count, ValueOnZero);
748 
749   // Skip zero extend/truncate.
750   Value *V = nullptr;
751   if (match(Count, m_ZExt(m_Value(V))) ||
752       match(Count, m_Trunc(m_Value(V))))
753     Count = V;
754 
755   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
756   // input to the cttz/ctlz is used as LHS for the compare instruction.
757   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
758       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
759     return nullptr;
760 
761   IntrinsicInst *II = cast<IntrinsicInst>(Count);
762 
763   // Check if the value propagated on zero is a constant number equal to the
764   // sizeof in bits of 'Count'.
765   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
766   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
767     // Explicitly clear the 'undef_on_zero' flag.
768     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
769     NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
770     Builder.Insert(NewI);
771     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
772   }
773 
774   // If the ValueOnZero is not the bitwidth, we can at least make use of the
775   // fact that the cttz/ctlz result will not be used if the input is zero, so
776   // it's okay to relax it to undef for that case.
777   if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
778     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
779 
780   return nullptr;
781 }
782 
783 /// Return true if we find and adjust an icmp+select pattern where the compare
784 /// is with a constant that can be incremented or decremented to match the
785 /// minimum or maximum idiom.
786 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
787   ICmpInst::Predicate Pred = Cmp.getPredicate();
788   Value *CmpLHS = Cmp.getOperand(0);
789   Value *CmpRHS = Cmp.getOperand(1);
790   Value *TrueVal = Sel.getTrueValue();
791   Value *FalseVal = Sel.getFalseValue();
792 
793   // We may move or edit the compare, so make sure the select is the only user.
794   const APInt *CmpC;
795   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
796     return false;
797 
798   // These transforms only work for selects of integers or vector selects of
799   // integer vectors.
800   Type *SelTy = Sel.getType();
801   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
802   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
803     return false;
804 
805   Constant *AdjustedRHS;
806   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
807     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
808   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
809     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
810   else
811     return false;
812 
813   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
814   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
815   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
816       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
817     ; // Nothing to do here. Values match without any sign/zero extension.
818   }
819   // Types do not match. Instead of calculating this with mixed types, promote
820   // all to the larger type. This enables scalar evolution to analyze this
821   // expression.
822   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
823     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
824 
825     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
826     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
827     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
828     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
829     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
830       CmpLHS = TrueVal;
831       AdjustedRHS = SextRHS;
832     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
833                SextRHS == TrueVal) {
834       CmpLHS = FalseVal;
835       AdjustedRHS = SextRHS;
836     } else if (Cmp.isUnsigned()) {
837       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
838       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
839       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
840       // zext + signed compare cannot be changed:
841       //    0xff <s 0x00, but 0x00ff >s 0x0000
842       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
843         CmpLHS = TrueVal;
844         AdjustedRHS = ZextRHS;
845       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
846                  ZextRHS == TrueVal) {
847         CmpLHS = FalseVal;
848         AdjustedRHS = ZextRHS;
849       } else {
850         return false;
851       }
852     } else {
853       return false;
854     }
855   } else {
856     return false;
857   }
858 
859   Pred = ICmpInst::getSwappedPredicate(Pred);
860   CmpRHS = AdjustedRHS;
861   std::swap(FalseVal, TrueVal);
862   Cmp.setPredicate(Pred);
863   Cmp.setOperand(0, CmpLHS);
864   Cmp.setOperand(1, CmpRHS);
865   Sel.setOperand(1, TrueVal);
866   Sel.setOperand(2, FalseVal);
867   Sel.swapProfMetadata();
868 
869   // Move the compare instruction right before the select instruction. Otherwise
870   // the sext/zext value may be defined after the compare instruction uses it.
871   Cmp.moveBefore(&Sel);
872 
873   return true;
874 }
875 
876 /// If this is an integer min/max (icmp + select) with a constant operand,
877 /// create the canonical icmp for the min/max operation and canonicalize the
878 /// constant to the 'false' operand of the select:
879 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
880 /// Note: if C1 != C2, this will change the icmp constant to the existing
881 /// constant operand of the select.
882 static Instruction *
883 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
884                                InstCombiner::BuilderTy &Builder) {
885   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
886     return nullptr;
887 
888   // Canonicalize the compare predicate based on whether we have min or max.
889   Value *LHS, *RHS;
890   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
891   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
892     return nullptr;
893 
894   // Is this already canonical?
895   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
896   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
897       Cmp.getPredicate() == CanonicalPred)
898     return nullptr;
899 
900   // Create the canonical compare and plug it into the select.
901   Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
902 
903   // If the select operands did not change, we're done.
904   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
905     return &Sel;
906 
907   // If we are swapping the select operands, swap the metadata too.
908   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
909          "Unexpected results from matchSelectPattern");
910   Sel.setTrueValue(LHS);
911   Sel.setFalseValue(RHS);
912   Sel.swapProfMetadata();
913   return &Sel;
914 }
915 
916 /// There are many select variants for each of ABS/NABS.
917 /// In matchSelectPattern(), there are different compare constants, compare
918 /// predicates/operands and select operands.
919 /// In isKnownNegation(), there are different formats of negated operands.
920 /// Canonicalize all these variants to 1 pattern.
921 /// This makes CSE more likely.
922 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
923                                         InstCombiner::BuilderTy &Builder) {
924   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
925     return nullptr;
926 
927   // Choose a sign-bit check for the compare (likely simpler for codegen).
928   // ABS:  (X <s 0) ? -X : X
929   // NABS: (X <s 0) ? X : -X
930   Value *LHS, *RHS;
931   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
932   if (SPF != SelectPatternFlavor::SPF_ABS &&
933       SPF != SelectPatternFlavor::SPF_NABS)
934     return nullptr;
935 
936   Value *TVal = Sel.getTrueValue();
937   Value *FVal = Sel.getFalseValue();
938   assert(isKnownNegation(TVal, FVal) &&
939          "Unexpected result from matchSelectPattern");
940 
941   // The compare may use the negated abs()/nabs() operand, or it may use
942   // negation in non-canonical form such as: sub A, B.
943   bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
944                           match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
945 
946   bool CmpCanonicalized = !CmpUsesNegatedOp &&
947                           match(Cmp.getOperand(1), m_ZeroInt()) &&
948                           Cmp.getPredicate() == ICmpInst::ICMP_SLT;
949   bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
950 
951   // Is this already canonical?
952   if (CmpCanonicalized && RHSCanonicalized)
953     return nullptr;
954 
955   // If RHS is used by other instructions except compare and select, don't
956   // canonicalize it to not increase the instruction count.
957   if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
958     return nullptr;
959 
960   // Create the canonical compare: icmp slt LHS 0.
961   if (!CmpCanonicalized) {
962     Cmp.setPredicate(ICmpInst::ICMP_SLT);
963     Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
964     if (CmpUsesNegatedOp)
965       Cmp.setOperand(0, LHS);
966   }
967 
968   // Create the canonical RHS: RHS = sub (0, LHS).
969   if (!RHSCanonicalized) {
970     assert(RHS->hasOneUse() && "RHS use number is not right");
971     RHS = Builder.CreateNeg(LHS);
972     if (TVal == LHS) {
973       Sel.setFalseValue(RHS);
974       FVal = RHS;
975     } else {
976       Sel.setTrueValue(RHS);
977       TVal = RHS;
978     }
979   }
980 
981   // If the select operands do not change, we're done.
982   if (SPF == SelectPatternFlavor::SPF_NABS) {
983     if (TVal == LHS)
984       return &Sel;
985     assert(FVal == LHS && "Unexpected results from matchSelectPattern");
986   } else {
987     if (FVal == LHS)
988       return &Sel;
989     assert(TVal == LHS && "Unexpected results from matchSelectPattern");
990   }
991 
992   // We are swapping the select operands, so swap the metadata too.
993   Sel.setTrueValue(FVal);
994   Sel.setFalseValue(TVal);
995   Sel.swapProfMetadata();
996   return &Sel;
997 }
998 
999 /// Visit a SelectInst that has an ICmpInst as its first operand.
1000 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1001                                                   ICmpInst *ICI) {
1002   Value *TrueVal = SI.getTrueValue();
1003   Value *FalseVal = SI.getFalseValue();
1004 
1005   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
1006     return NewSel;
1007 
1008   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
1009     return NewAbs;
1010 
1011   bool Changed = adjustMinMax(SI, *ICI);
1012 
1013   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1014     return replaceInstUsesWith(SI, V);
1015 
1016   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1017   ICmpInst::Predicate Pred = ICI->getPredicate();
1018   Value *CmpLHS = ICI->getOperand(0);
1019   Value *CmpRHS = ICI->getOperand(1);
1020   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1021     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1022       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1023       SI.setOperand(1, CmpRHS);
1024       Changed = true;
1025     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1026       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1027       SI.setOperand(2, CmpRHS);
1028       Changed = true;
1029     }
1030   }
1031 
1032   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1033   // decomposeBitTestICmp() might help.
1034   {
1035     unsigned BitWidth =
1036         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1037     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1038     Value *X;
1039     const APInt *Y, *C;
1040     bool TrueWhenUnset;
1041     bool IsBitTest = false;
1042     if (ICmpInst::isEquality(Pred) &&
1043         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1044         match(CmpRHS, m_Zero())) {
1045       IsBitTest = true;
1046       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1047     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1048       X = CmpLHS;
1049       Y = &MinSignedValue;
1050       IsBitTest = true;
1051       TrueWhenUnset = false;
1052     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1053       X = CmpLHS;
1054       Y = &MinSignedValue;
1055       IsBitTest = true;
1056       TrueWhenUnset = true;
1057     }
1058     if (IsBitTest) {
1059       Value *V = nullptr;
1060       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1061       if (TrueWhenUnset && TrueVal == X &&
1062           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1063         V = Builder.CreateAnd(X, ~(*Y));
1064       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1065       else if (!TrueWhenUnset && FalseVal == X &&
1066                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1067         V = Builder.CreateAnd(X, ~(*Y));
1068       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1069       else if (TrueWhenUnset && FalseVal == X &&
1070                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1071         V = Builder.CreateOr(X, *Y);
1072       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1073       else if (!TrueWhenUnset && TrueVal == X &&
1074                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1075         V = Builder.CreateOr(X, *Y);
1076 
1077       if (V)
1078         return replaceInstUsesWith(SI, V);
1079     }
1080   }
1081 
1082   if (Instruction *V =
1083           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1084     return V;
1085 
1086   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1087     return replaceInstUsesWith(SI, V);
1088 
1089   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1090     return replaceInstUsesWith(SI, V);
1091 
1092   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1093     return replaceInstUsesWith(SI, V);
1094 
1095   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1096     return replaceInstUsesWith(SI, V);
1097 
1098   return Changed ? &SI : nullptr;
1099 }
1100 
1101 /// SI is a select whose condition is a PHI node (but the two may be in
1102 /// different blocks). See if the true/false values (V) are live in all of the
1103 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1104 ///
1105 ///   X = phi [ C1, BB1], [C2, BB2]
1106 ///   Y = add
1107 ///   Z = select X, Y, 0
1108 ///
1109 /// because Y is not live in BB1/BB2.
1110 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1111                                                    const SelectInst &SI) {
1112   // If the value is a non-instruction value like a constant or argument, it
1113   // can always be mapped.
1114   const Instruction *I = dyn_cast<Instruction>(V);
1115   if (!I) return true;
1116 
1117   // If V is a PHI node defined in the same block as the condition PHI, we can
1118   // map the arguments.
1119   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1120 
1121   if (const PHINode *VP = dyn_cast<PHINode>(I))
1122     if (VP->getParent() == CondPHI->getParent())
1123       return true;
1124 
1125   // Otherwise, if the PHI and select are defined in the same block and if V is
1126   // defined in a different block, then we can transform it.
1127   if (SI.getParent() == CondPHI->getParent() &&
1128       I->getParent() != CondPHI->getParent())
1129     return true;
1130 
1131   // Otherwise we have a 'hard' case and we can't tell without doing more
1132   // detailed dominator based analysis, punt.
1133   return false;
1134 }
1135 
1136 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1137 ///   SPF2(SPF1(A, B), C)
1138 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1139                                         SelectPatternFlavor SPF1,
1140                                         Value *A, Value *B,
1141                                         Instruction &Outer,
1142                                         SelectPatternFlavor SPF2, Value *C) {
1143   if (Outer.getType() != Inner->getType())
1144     return nullptr;
1145 
1146   if (C == A || C == B) {
1147     // MAX(MAX(A, B), B) -> MAX(A, B)
1148     // MIN(MIN(a, b), a) -> MIN(a, b)
1149     // TODO: This could be done in instsimplify.
1150     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1151       return replaceInstUsesWith(Outer, Inner);
1152 
1153     // MAX(MIN(a, b), a) -> a
1154     // MIN(MAX(a, b), a) -> a
1155     // TODO: This could be done in instsimplify.
1156     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1157         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1158         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1159         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1160       return replaceInstUsesWith(Outer, C);
1161   }
1162 
1163   if (SPF1 == SPF2) {
1164     const APInt *CB, *CC;
1165     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1166       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1167       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1168       // TODO: This could be done in instsimplify.
1169       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1170           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1171           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1172           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1173         return replaceInstUsesWith(Outer, Inner);
1174 
1175       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1176       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1177       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1178           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1179           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1180           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1181         Outer.replaceUsesOfWith(Inner, A);
1182         return &Outer;
1183       }
1184     }
1185   }
1186 
1187   // ABS(ABS(X)) -> ABS(X)
1188   // NABS(NABS(X)) -> NABS(X)
1189   // TODO: This could be done in instsimplify.
1190   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1191     return replaceInstUsesWith(Outer, Inner);
1192   }
1193 
1194   // ABS(NABS(X)) -> ABS(X)
1195   // NABS(ABS(X)) -> NABS(X)
1196   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1197       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1198     SelectInst *SI = cast<SelectInst>(Inner);
1199     Value *NewSI =
1200         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1201                              SI->getTrueValue(), SI->getName(), SI);
1202     return replaceInstUsesWith(Outer, NewSI);
1203   }
1204 
1205   auto IsFreeOrProfitableToInvert =
1206       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1207     if (match(V, m_Not(m_Value(NotV)))) {
1208       // If V has at most 2 uses then we can get rid of the xor operation
1209       // entirely.
1210       ElidesXor |= !V->hasNUsesOrMore(3);
1211       return true;
1212     }
1213 
1214     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1215       NotV = nullptr;
1216       return true;
1217     }
1218 
1219     return false;
1220   };
1221 
1222   Value *NotA, *NotB, *NotC;
1223   bool ElidesXor = false;
1224 
1225   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1226   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1227   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1228   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1229   //
1230   // This transform is performance neutral if we can elide at least one xor from
1231   // the set of three operands, since we'll be tacking on an xor at the very
1232   // end.
1233   if (SelectPatternResult::isMinOrMax(SPF1) &&
1234       SelectPatternResult::isMinOrMax(SPF2) &&
1235       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1236       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1237       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1238     if (!NotA)
1239       NotA = Builder.CreateNot(A);
1240     if (!NotB)
1241       NotB = Builder.CreateNot(B);
1242     if (!NotC)
1243       NotC = Builder.CreateNot(C);
1244 
1245     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1246                                    NotB);
1247     Value *NewOuter = Builder.CreateNot(
1248         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1249     return replaceInstUsesWith(Outer, NewOuter);
1250   }
1251 
1252   return nullptr;
1253 }
1254 
1255 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1256 /// This is even legal for FP.
1257 static Instruction *foldAddSubSelect(SelectInst &SI,
1258                                      InstCombiner::BuilderTy &Builder) {
1259   Value *CondVal = SI.getCondition();
1260   Value *TrueVal = SI.getTrueValue();
1261   Value *FalseVal = SI.getFalseValue();
1262   auto *TI = dyn_cast<Instruction>(TrueVal);
1263   auto *FI = dyn_cast<Instruction>(FalseVal);
1264   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1265     return nullptr;
1266 
1267   Instruction *AddOp = nullptr, *SubOp = nullptr;
1268   if ((TI->getOpcode() == Instruction::Sub &&
1269        FI->getOpcode() == Instruction::Add) ||
1270       (TI->getOpcode() == Instruction::FSub &&
1271        FI->getOpcode() == Instruction::FAdd)) {
1272     AddOp = FI;
1273     SubOp = TI;
1274   } else if ((FI->getOpcode() == Instruction::Sub &&
1275               TI->getOpcode() == Instruction::Add) ||
1276              (FI->getOpcode() == Instruction::FSub &&
1277               TI->getOpcode() == Instruction::FAdd)) {
1278     AddOp = TI;
1279     SubOp = FI;
1280   }
1281 
1282   if (AddOp) {
1283     Value *OtherAddOp = nullptr;
1284     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1285       OtherAddOp = AddOp->getOperand(1);
1286     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1287       OtherAddOp = AddOp->getOperand(0);
1288     }
1289 
1290     if (OtherAddOp) {
1291       // So at this point we know we have (Y -> OtherAddOp):
1292       //        select C, (add X, Y), (sub X, Z)
1293       Value *NegVal; // Compute -Z
1294       if (SI.getType()->isFPOrFPVectorTy()) {
1295         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1296         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1297           FastMathFlags Flags = AddOp->getFastMathFlags();
1298           Flags &= SubOp->getFastMathFlags();
1299           NegInst->setFastMathFlags(Flags);
1300         }
1301       } else {
1302         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1303       }
1304 
1305       Value *NewTrueOp = OtherAddOp;
1306       Value *NewFalseOp = NegVal;
1307       if (AddOp != TI)
1308         std::swap(NewTrueOp, NewFalseOp);
1309       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1310                                            SI.getName() + ".p", &SI);
1311 
1312       if (SI.getType()->isFPOrFPVectorTy()) {
1313         Instruction *RI =
1314             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1315 
1316         FastMathFlags Flags = AddOp->getFastMathFlags();
1317         Flags &= SubOp->getFastMathFlags();
1318         RI->setFastMathFlags(Flags);
1319         return RI;
1320       } else
1321         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1322     }
1323   }
1324   return nullptr;
1325 }
1326 
1327 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1328   Constant *C;
1329   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1330       !match(Sel.getFalseValue(), m_Constant(C)))
1331     return nullptr;
1332 
1333   Instruction *ExtInst;
1334   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1335       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1336     return nullptr;
1337 
1338   auto ExtOpcode = ExtInst->getOpcode();
1339   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1340     return nullptr;
1341 
1342   // If we are extending from a boolean type or if we can create a select that
1343   // has the same size operands as its condition, try to narrow the select.
1344   Value *X = ExtInst->getOperand(0);
1345   Type *SmallType = X->getType();
1346   Value *Cond = Sel.getCondition();
1347   auto *Cmp = dyn_cast<CmpInst>(Cond);
1348   if (!SmallType->isIntOrIntVectorTy(1) &&
1349       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1350     return nullptr;
1351 
1352   // If the constant is the same after truncation to the smaller type and
1353   // extension to the original type, we can narrow the select.
1354   Type *SelType = Sel.getType();
1355   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1356   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1357   if (ExtC == C) {
1358     Value *TruncCVal = cast<Value>(TruncC);
1359     if (ExtInst == Sel.getFalseValue())
1360       std::swap(X, TruncCVal);
1361 
1362     // select Cond, (ext X), C --> ext(select Cond, X, C')
1363     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1364     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1365     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1366   }
1367 
1368   // If one arm of the select is the extend of the condition, replace that arm
1369   // with the extension of the appropriate known bool value.
1370   if (Cond == X) {
1371     if (ExtInst == Sel.getTrueValue()) {
1372       // select X, (sext X), C --> select X, -1, C
1373       // select X, (zext X), C --> select X,  1, C
1374       Constant *One = ConstantInt::getTrue(SmallType);
1375       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1376       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1377     } else {
1378       // select X, C, (sext X) --> select X, C, 0
1379       // select X, C, (zext X) --> select X, C, 0
1380       Constant *Zero = ConstantInt::getNullValue(SelType);
1381       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1382     }
1383   }
1384 
1385   return nullptr;
1386 }
1387 
1388 /// Try to transform a vector select with a constant condition vector into a
1389 /// shuffle for easier combining with other shuffles and insert/extract.
1390 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1391   Value *CondVal = SI.getCondition();
1392   Constant *CondC;
1393   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1394     return nullptr;
1395 
1396   unsigned NumElts = CondVal->getType()->getVectorNumElements();
1397   SmallVector<Constant *, 16> Mask;
1398   Mask.reserve(NumElts);
1399   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1400   for (unsigned i = 0; i != NumElts; ++i) {
1401     Constant *Elt = CondC->getAggregateElement(i);
1402     if (!Elt)
1403       return nullptr;
1404 
1405     if (Elt->isOneValue()) {
1406       // If the select condition element is true, choose from the 1st vector.
1407       Mask.push_back(ConstantInt::get(Int32Ty, i));
1408     } else if (Elt->isNullValue()) {
1409       // If the select condition element is false, choose from the 2nd vector.
1410       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1411     } else if (isa<UndefValue>(Elt)) {
1412       // Undef in a select condition (choose one of the operands) does not mean
1413       // the same thing as undef in a shuffle mask (any value is acceptable), so
1414       // give up.
1415       return nullptr;
1416     } else {
1417       // Bail out on a constant expression.
1418       return nullptr;
1419     }
1420   }
1421 
1422   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1423                                ConstantVector::get(Mask));
1424 }
1425 
1426 /// Reuse bitcasted operands between a compare and select:
1427 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1428 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1429 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1430                                           InstCombiner::BuilderTy &Builder) {
1431   Value *Cond = Sel.getCondition();
1432   Value *TVal = Sel.getTrueValue();
1433   Value *FVal = Sel.getFalseValue();
1434 
1435   CmpInst::Predicate Pred;
1436   Value *A, *B;
1437   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1438     return nullptr;
1439 
1440   // The select condition is a compare instruction. If the select's true/false
1441   // values are already the same as the compare operands, there's nothing to do.
1442   if (TVal == A || TVal == B || FVal == A || FVal == B)
1443     return nullptr;
1444 
1445   Value *C, *D;
1446   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1447     return nullptr;
1448 
1449   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1450   Value *TSrc, *FSrc;
1451   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1452       !match(FVal, m_BitCast(m_Value(FSrc))))
1453     return nullptr;
1454 
1455   // If the select true/false values are *different bitcasts* of the same source
1456   // operands, make the select operands the same as the compare operands and
1457   // cast the result. This is the canonical select form for min/max.
1458   Value *NewSel;
1459   if (TSrc == C && FSrc == D) {
1460     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1461     // bitcast (select (cmp A, B), A, B)
1462     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1463   } else if (TSrc == D && FSrc == C) {
1464     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1465     // bitcast (select (cmp A, B), B, A)
1466     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1467   } else {
1468     return nullptr;
1469   }
1470   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1471 }
1472 
1473 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1474 /// instructions.
1475 ///
1476 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1477 /// selects between the returned value of the cmpxchg instruction its compare
1478 /// operand, the result of the select will always be equal to its false value.
1479 /// For example:
1480 ///
1481 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1482 ///   %1 = extractvalue { i64, i1 } %0, 1
1483 ///   %2 = extractvalue { i64, i1 } %0, 0
1484 ///   %3 = select i1 %1, i64 %compare, i64 %2
1485 ///   ret i64 %3
1486 ///
1487 /// The returned value of the cmpxchg instruction (%2) is the original value
1488 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1489 /// must have been equal to %compare. Thus, the result of the select is always
1490 /// equal to %2, and the code can be simplified to:
1491 ///
1492 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1493 ///   %1 = extractvalue { i64, i1 } %0, 0
1494 ///   ret i64 %1
1495 ///
1496 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1497   // A helper that determines if V is an extractvalue instruction whose
1498   // aggregate operand is a cmpxchg instruction and whose single index is equal
1499   // to I. If such conditions are true, the helper returns the cmpxchg
1500   // instruction; otherwise, a nullptr is returned.
1501   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1502     auto *Extract = dyn_cast<ExtractValueInst>(V);
1503     if (!Extract)
1504       return nullptr;
1505     if (Extract->getIndices()[0] != I)
1506       return nullptr;
1507     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1508   };
1509 
1510   // If the select has a single user, and this user is a select instruction that
1511   // we can simplify, skip the cmpxchg simplification for now.
1512   if (SI.hasOneUse())
1513     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1514       if (Select->getCondition() == SI.getCondition())
1515         if (Select->getFalseValue() == SI.getTrueValue() ||
1516             Select->getTrueValue() == SI.getFalseValue())
1517           return nullptr;
1518 
1519   // Ensure the select condition is the returned flag of a cmpxchg instruction.
1520   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1521   if (!CmpXchg)
1522     return nullptr;
1523 
1524   // Check the true value case: The true value of the select is the returned
1525   // value of the same cmpxchg used by the condition, and the false value is the
1526   // cmpxchg instruction's compare operand.
1527   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1528     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1529       SI.setTrueValue(SI.getFalseValue());
1530       return &SI;
1531     }
1532 
1533   // Check the false value case: The false value of the select is the returned
1534   // value of the same cmpxchg used by the condition, and the true value is the
1535   // cmpxchg instruction's compare operand.
1536   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1537     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1538       SI.setTrueValue(SI.getFalseValue());
1539       return &SI;
1540     }
1541 
1542   return nullptr;
1543 }
1544 
1545 /// Reduce a sequence of min/max with a common operand.
1546 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1547                                         Value *RHS,
1548                                         InstCombiner::BuilderTy &Builder) {
1549   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1550   // TODO: Allow FP min/max with nnan/nsz.
1551   if (!LHS->getType()->isIntOrIntVectorTy())
1552     return nullptr;
1553 
1554   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1555   Value *A, *B, *C, *D;
1556   SelectPatternResult L = matchSelectPattern(LHS, A, B);
1557   SelectPatternResult R = matchSelectPattern(RHS, C, D);
1558   if (SPF != L.Flavor || L.Flavor != R.Flavor)
1559     return nullptr;
1560 
1561   // Look for a common operand. The use checks are different than usual because
1562   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1563   // the select.
1564   Value *MinMaxOp = nullptr;
1565   Value *ThirdOp = nullptr;
1566   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
1567     // If the LHS is only used in this chain and the RHS is used outside of it,
1568     // reuse the RHS min/max because that will eliminate the LHS.
1569     if (D == A || C == A) {
1570       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1571       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1572       MinMaxOp = RHS;
1573       ThirdOp = B;
1574     } else if (D == B || C == B) {
1575       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1576       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1577       MinMaxOp = RHS;
1578       ThirdOp = A;
1579     }
1580   } else if (!RHS->hasNUsesOrMore(3)) {
1581     // Reuse the LHS. This will eliminate the RHS.
1582     if (D == A || D == B) {
1583       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1584       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1585       MinMaxOp = LHS;
1586       ThirdOp = C;
1587     } else if (C == A || C == B) {
1588       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1589       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1590       MinMaxOp = LHS;
1591       ThirdOp = D;
1592     }
1593   }
1594   if (!MinMaxOp || !ThirdOp)
1595     return nullptr;
1596 
1597   CmpInst::Predicate P = getMinMaxPred(SPF);
1598   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1599   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1600 }
1601 
1602 /// Try to reduce a rotate pattern that includes a compare and select into a
1603 /// funnel shift intrinsic. Example:
1604 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
1605 ///              --> call llvm.fshl.i32(a, a, b)
1606 static Instruction *foldSelectRotate(SelectInst &Sel) {
1607   // The false value of the select must be a rotate of the true value.
1608   Value *Or0, *Or1;
1609   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
1610     return nullptr;
1611 
1612   Value *TVal = Sel.getTrueValue();
1613   Value *SA0, *SA1;
1614   if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
1615       !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
1616     return nullptr;
1617 
1618   auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
1619   auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
1620   if (ShiftOpcode0 == ShiftOpcode1)
1621     return nullptr;
1622 
1623   // We have one of these patterns so far:
1624   // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
1625   // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
1626   // This must be a power-of-2 rotate for a bitmasking transform to be valid.
1627   unsigned Width = Sel.getType()->getScalarSizeInBits();
1628   if (!isPowerOf2_32(Width))
1629     return nullptr;
1630 
1631   // Check the shift amounts to see if they are an opposite pair.
1632   Value *ShAmt;
1633   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
1634     ShAmt = SA0;
1635   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
1636     ShAmt = SA1;
1637   else
1638     return nullptr;
1639 
1640   // Finally, see if the select is filtering out a shift-by-zero.
1641   Value *Cond = Sel.getCondition();
1642   ICmpInst::Predicate Pred;
1643   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
1644       Pred != ICmpInst::ICMP_EQ)
1645     return nullptr;
1646 
1647   // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
1648   // Convert to funnel shift intrinsic.
1649   bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
1650                 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
1651   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
1652   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
1653   return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
1654 }
1655 
1656 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1657   Value *CondVal = SI.getCondition();
1658   Value *TrueVal = SI.getTrueValue();
1659   Value *FalseVal = SI.getFalseValue();
1660   Type *SelType = SI.getType();
1661 
1662   // FIXME: Remove this workaround when freeze related patches are done.
1663   // For select with undef operand which feeds into an equality comparison,
1664   // don't simplify it so loop unswitch can know the equality comparison
1665   // may have an undef operand. This is a workaround for PR31652 caused by
1666   // descrepancy about branch on undef between LoopUnswitch and GVN.
1667   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1668     if (llvm::any_of(SI.users(), [&](User *U) {
1669           ICmpInst *CI = dyn_cast<ICmpInst>(U);
1670           if (CI && CI->isEquality())
1671             return true;
1672           return false;
1673         })) {
1674       return nullptr;
1675     }
1676   }
1677 
1678   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1679                                     SQ.getWithInstruction(&SI)))
1680     return replaceInstUsesWith(SI, V);
1681 
1682   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1683     return I;
1684 
1685   // Canonicalize a one-use integer compare with a non-canonical predicate by
1686   // inverting the predicate and swapping the select operands. This matches a
1687   // compare canonicalization for conditional branches.
1688   // TODO: Should we do the same for FP compares?
1689   CmpInst::Predicate Pred;
1690   if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1691       !isCanonicalPredicate(Pred)) {
1692     // Swap true/false values and condition.
1693     CmpInst *Cond = cast<CmpInst>(CondVal);
1694     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1695     SI.setOperand(1, FalseVal);
1696     SI.setOperand(2, TrueVal);
1697     SI.swapProfMetadata();
1698     Worklist.Add(Cond);
1699     return &SI;
1700   }
1701 
1702   if (SelType->isIntOrIntVectorTy(1) &&
1703       TrueVal->getType() == CondVal->getType()) {
1704     if (match(TrueVal, m_One())) {
1705       // Change: A = select B, true, C --> A = or B, C
1706       return BinaryOperator::CreateOr(CondVal, FalseVal);
1707     }
1708     if (match(TrueVal, m_Zero())) {
1709       // Change: A = select B, false, C --> A = and !B, C
1710       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1711       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1712     }
1713     if (match(FalseVal, m_Zero())) {
1714       // Change: A = select B, C, false --> A = and B, C
1715       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1716     }
1717     if (match(FalseVal, m_One())) {
1718       // Change: A = select B, C, true --> A = or !B, C
1719       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1720       return BinaryOperator::CreateOr(NotCond, TrueVal);
1721     }
1722 
1723     // select a, a, b  -> a | b
1724     // select a, b, a  -> a & b
1725     if (CondVal == TrueVal)
1726       return BinaryOperator::CreateOr(CondVal, FalseVal);
1727     if (CondVal == FalseVal)
1728       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1729 
1730     // select a, ~a, b -> (~a) & b
1731     // select a, b, ~a -> (~a) | b
1732     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1733       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1734     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1735       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1736   }
1737 
1738   // Selecting between two integer or vector splat integer constants?
1739   //
1740   // Note that we don't handle a scalar select of vectors:
1741   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1742   // because that may need 3 instructions to splat the condition value:
1743   // extend, insertelement, shufflevector.
1744   if (SelType->isIntOrIntVectorTy() &&
1745       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1746     // select C, 1, 0 -> zext C to int
1747     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1748       return new ZExtInst(CondVal, SelType);
1749 
1750     // select C, -1, 0 -> sext C to int
1751     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1752       return new SExtInst(CondVal, SelType);
1753 
1754     // select C, 0, 1 -> zext !C to int
1755     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1756       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1757       return new ZExtInst(NotCond, SelType);
1758     }
1759 
1760     // select C, 0, -1 -> sext !C to int
1761     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1762       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1763       return new SExtInst(NotCond, SelType);
1764     }
1765   }
1766 
1767   // See if we are selecting two values based on a comparison of the two values.
1768   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1769     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1770       // Canonicalize to use ordered comparisons by swapping the select
1771       // operands.
1772       //
1773       // e.g.
1774       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1775       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1776         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1777         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1778         Builder.setFastMathFlags(FCI->getFastMathFlags());
1779         Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1780                                             FCI->getName() + ".inv");
1781 
1782         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1783                                   SI.getName() + ".p");
1784       }
1785 
1786       // NOTE: if we wanted to, this is where to detect MIN/MAX
1787     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1788       // Canonicalize to use ordered comparisons by swapping the select
1789       // operands.
1790       //
1791       // e.g.
1792       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1793       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1794         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1795         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1796         Builder.setFastMathFlags(FCI->getFastMathFlags());
1797         Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1798                                             FCI->getName() + ".inv");
1799 
1800         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1801                                   SI.getName() + ".p");
1802       }
1803 
1804       // NOTE: if we wanted to, this is where to detect MIN/MAX
1805     }
1806 
1807     // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1808     // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1809     // also require nnan because we do not want to unintentionally change the
1810     // sign of a NaN value.
1811     Value *X = FCI->getOperand(0);
1812     FCmpInst::Predicate Pred = FCI->getPredicate();
1813     if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1814       // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1815       // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
1816       if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1817            match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1818           (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1819            match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
1820         Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1821         return replaceInstUsesWith(SI, Fabs);
1822       }
1823       // With nsz:
1824       // (X <  +/-0.0) ? -X : X --> fabs(X)
1825       // (X <= +/-0.0) ? -X : X --> fabs(X)
1826       // (X >  +/-0.0) ? X : -X --> fabs(X)
1827       // (X >= +/-0.0) ? X : -X --> fabs(X)
1828       if (FCI->hasNoSignedZeros() &&
1829           ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1830             (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1831            (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1832             (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1833         Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1834         return replaceInstUsesWith(SI, Fabs);
1835       }
1836     }
1837   }
1838 
1839   // See if we are selecting two values based on a comparison of the two values.
1840   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1841     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1842       return Result;
1843 
1844   if (Instruction *Add = foldAddSubSelect(SI, Builder))
1845     return Add;
1846 
1847   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1848   auto *TI = dyn_cast<Instruction>(TrueVal);
1849   auto *FI = dyn_cast<Instruction>(FalseVal);
1850   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1851     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1852       return IV;
1853 
1854   if (Instruction *I = foldSelectExtConst(SI))
1855     return I;
1856 
1857   // See if we can fold the select into one of our operands.
1858   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1859     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1860       return FoldI;
1861 
1862     Value *LHS, *RHS;
1863     Instruction::CastOps CastOp;
1864     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1865     auto SPF = SPR.Flavor;
1866     if (SPF) {
1867       Value *LHS2, *RHS2;
1868       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1869         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
1870                                           RHS2, SI, SPF, RHS))
1871           return R;
1872       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1873         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
1874                                           RHS2, SI, SPF, LHS))
1875           return R;
1876       // TODO.
1877       // ABS(-X) -> ABS(X)
1878     }
1879 
1880     if (SelectPatternResult::isMinOrMax(SPF)) {
1881       // Canonicalize so that
1882       // - type casts are outside select patterns.
1883       // - float clamp is transformed to min/max pattern
1884 
1885       bool IsCastNeeded = LHS->getType() != SelType;
1886       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1887       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1888       if (IsCastNeeded ||
1889           (LHS->getType()->isFPOrFPVectorTy() &&
1890            ((CmpLHS != LHS && CmpLHS != RHS) ||
1891             (CmpRHS != LHS && CmpRHS != RHS)))) {
1892         CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1893 
1894         Value *Cmp;
1895         if (CmpInst::isIntPredicate(Pred)) {
1896           Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1897         } else {
1898           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1899           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1900           Builder.setFastMathFlags(FMF);
1901           Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1902         }
1903 
1904         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1905         if (!IsCastNeeded)
1906           return replaceInstUsesWith(SI, NewSI);
1907 
1908         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1909         return replaceInstUsesWith(SI, NewCast);
1910       }
1911 
1912       // MAX(~a, ~b) -> ~MIN(a, b)
1913       // MAX(~a, C)  -> ~MIN(a, ~C)
1914       // MIN(~a, ~b) -> ~MAX(a, b)
1915       // MIN(~a, C)  -> ~MAX(a, ~C)
1916       auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1917         Value *A;
1918         if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
1919             !IsFreeToInvert(A, A->hasOneUse()) &&
1920             // Passing false to only consider m_Not and constants.
1921             IsFreeToInvert(Y, false)) {
1922           Value *B = Builder.CreateNot(Y);
1923           Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
1924                                           A, B);
1925           // Copy the profile metadata.
1926           if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
1927             cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
1928             // Swap the metadata if the operands are swapped.
1929             if (X == SI.getFalseValue() && Y == SI.getTrueValue())
1930               cast<SelectInst>(NewMinMax)->swapProfMetadata();
1931           }
1932 
1933           return BinaryOperator::CreateNot(NewMinMax);
1934         }
1935 
1936         return nullptr;
1937       };
1938 
1939       if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
1940         return I;
1941       if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
1942         return I;
1943 
1944       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1945         return I;
1946     }
1947   }
1948 
1949   // See if we can fold the select into a phi node if the condition is a select.
1950   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1951     // The true/false values have to be live in the PHI predecessor's blocks.
1952     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1953         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1954       if (Instruction *NV = foldOpIntoPhi(SI, PN))
1955         return NV;
1956 
1957   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1958     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1959       // select(C, select(C, a, b), c) -> select(C, a, c)
1960       if (TrueSI->getCondition() == CondVal) {
1961         if (SI.getTrueValue() == TrueSI->getTrueValue())
1962           return nullptr;
1963         SI.setOperand(1, TrueSI->getTrueValue());
1964         return &SI;
1965       }
1966       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1967       // We choose this as normal form to enable folding on the And and shortening
1968       // paths for the values (this helps GetUnderlyingObjects() for example).
1969       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1970         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1971         SI.setOperand(0, And);
1972         SI.setOperand(1, TrueSI->getTrueValue());
1973         return &SI;
1974       }
1975     }
1976   }
1977   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1978     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1979       // select(C, a, select(C, b, c)) -> select(C, a, c)
1980       if (FalseSI->getCondition() == CondVal) {
1981         if (SI.getFalseValue() == FalseSI->getFalseValue())
1982           return nullptr;
1983         SI.setOperand(2, FalseSI->getFalseValue());
1984         return &SI;
1985       }
1986       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1987       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1988         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1989         SI.setOperand(0, Or);
1990         SI.setOperand(2, FalseSI->getFalseValue());
1991         return &SI;
1992       }
1993     }
1994   }
1995 
1996   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1997     // The select might be preventing a division by 0.
1998     switch (BO->getOpcode()) {
1999     default:
2000       return true;
2001     case Instruction::SRem:
2002     case Instruction::URem:
2003     case Instruction::SDiv:
2004     case Instruction::UDiv:
2005       return false;
2006     }
2007   };
2008 
2009   // Try to simplify a binop sandwiched between 2 selects with the same
2010   // condition.
2011   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2012   BinaryOperator *TrueBO;
2013   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2014       canMergeSelectThroughBinop(TrueBO)) {
2015     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2016       if (TrueBOSI->getCondition() == CondVal) {
2017         TrueBO->setOperand(0, TrueBOSI->getTrueValue());
2018         Worklist.Add(TrueBO);
2019         return &SI;
2020       }
2021     }
2022     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2023       if (TrueBOSI->getCondition() == CondVal) {
2024         TrueBO->setOperand(1, TrueBOSI->getTrueValue());
2025         Worklist.Add(TrueBO);
2026         return &SI;
2027       }
2028     }
2029   }
2030 
2031   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2032   BinaryOperator *FalseBO;
2033   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2034       canMergeSelectThroughBinop(FalseBO)) {
2035     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2036       if (FalseBOSI->getCondition() == CondVal) {
2037         FalseBO->setOperand(0, FalseBOSI->getFalseValue());
2038         Worklist.Add(FalseBO);
2039         return &SI;
2040       }
2041     }
2042     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2043       if (FalseBOSI->getCondition() == CondVal) {
2044         FalseBO->setOperand(1, FalseBOSI->getFalseValue());
2045         Worklist.Add(FalseBO);
2046         return &SI;
2047       }
2048     }
2049   }
2050 
2051   Value *NotCond;
2052   if (match(CondVal, m_Not(m_Value(NotCond)))) {
2053     SI.setOperand(0, NotCond);
2054     SI.setOperand(1, FalseVal);
2055     SI.setOperand(2, TrueVal);
2056     SI.swapProfMetadata();
2057     return &SI;
2058   }
2059 
2060   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2061     unsigned VWidth = VecTy->getNumElements();
2062     APInt UndefElts(VWidth, 0);
2063     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2064     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2065       if (V != &SI)
2066         return replaceInstUsesWith(SI, V);
2067       return &SI;
2068     }
2069   }
2070 
2071   // If we can compute the condition, there's no need for a select.
2072   // Like the above fold, we are attempting to reduce compile-time cost by
2073   // putting this fold here with limitations rather than in InstSimplify.
2074   // The motivation for this call into value tracking is to take advantage of
2075   // the assumption cache, so make sure that is populated.
2076   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2077     KnownBits Known(1);
2078     computeKnownBits(CondVal, Known, 0, &SI);
2079     if (Known.One.isOneValue())
2080       return replaceInstUsesWith(SI, TrueVal);
2081     if (Known.Zero.isOneValue())
2082       return replaceInstUsesWith(SI, FalseVal);
2083   }
2084 
2085   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2086     return BitCastSel;
2087 
2088   // Simplify selects that test the returned flag of cmpxchg instructions.
2089   if (Instruction *Select = foldSelectCmpXchg(SI))
2090     return Select;
2091 
2092   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
2093     return Select;
2094 
2095   if (Instruction *Rot = foldSelectRotate(SI))
2096     return Rot;
2097 
2098   return nullptr;
2099 }
2100