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 into usub.sat(a, b).
626 /// There are 8 commuted/swapped variants of this pattern.
627 /// TODO: Also support a - UMIN(a,b) patterns.
628 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
629                                             const Value *TrueVal,
630                                             const Value *FalseVal,
631                                             InstCombiner::BuilderTy &Builder) {
632   ICmpInst::Predicate Pred = ICI->getPredicate();
633   if (!ICmpInst::isUnsigned(Pred))
634     return nullptr;
635 
636   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
637   if (match(TrueVal, m_Zero())) {
638     Pred = ICmpInst::getInversePredicate(Pred);
639     std::swap(TrueVal, FalseVal);
640   }
641   if (!match(FalseVal, m_Zero()))
642     return nullptr;
643 
644   Value *A = ICI->getOperand(0);
645   Value *B = ICI->getOperand(1);
646   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
647     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
648     std::swap(A, B);
649     Pred = ICmpInst::getSwappedPredicate(Pred);
650   }
651 
652   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
653          "Unexpected isUnsigned predicate!");
654 
655   // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
656   bool IsNegative = false;
657   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
658     IsNegative = true;
659   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
660     return nullptr;
661 
662   // If sub is used anywhere else, we wouldn't be able to eliminate it
663   // afterwards.
664   if (!TrueVal->hasOneUse())
665     return nullptr;
666 
667   // (a > b) ? a - b : 0 -> usub.sat(a, b)
668   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
669   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
670   if (IsNegative)
671     Result = Builder.CreateNeg(Result);
672   return Result;
673 }
674 
675 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
676                                        InstCombiner::BuilderTy &Builder) {
677   if (!Cmp->hasOneUse())
678     return nullptr;
679 
680   // Match unsigned saturated add with constant.
681   Value *Cmp0 = Cmp->getOperand(0);
682   Value *Cmp1 = Cmp->getOperand(1);
683   ICmpInst::Predicate Pred = Cmp->getPredicate();
684   Value *X;
685   const APInt *C, *CmpC;
686   if (Pred == ICmpInst::ICMP_ULT &&
687       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
688       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
689     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
690     return Builder.CreateBinaryIntrinsic(
691         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
692   }
693 
694   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
695   // There are 8 commuted variants.
696   // Canonicalize -1 (saturated result) to true value of the select. Just
697   // swapping the compare operands is legal, because the selected value is the
698   // same in case of equality, so we can interchange u< and u<=.
699   if (match(FVal, m_AllOnes())) {
700     std::swap(TVal, FVal);
701     std::swap(Cmp0, Cmp1);
702   }
703   if (!match(TVal, m_AllOnes()))
704     return nullptr;
705 
706   // Canonicalize predicate to 'ULT'.
707   if (Pred == ICmpInst::ICMP_UGT) {
708     Pred = ICmpInst::ICMP_ULT;
709     std::swap(Cmp0, Cmp1);
710   }
711   if (Pred != ICmpInst::ICMP_ULT)
712     return nullptr;
713 
714   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
715   Value *Y;
716   if (match(Cmp0, m_Not(m_Value(X))) &&
717       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
718     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
719     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
720     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
721   }
722   // The 'not' op may be included in the sum but not the compare.
723   X = Cmp0;
724   Y = Cmp1;
725   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
726     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
727     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
728     BinaryOperator *BO = cast<BinaryOperator>(FVal);
729     return Builder.CreateBinaryIntrinsic(
730         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
731   }
732 
733   return nullptr;
734 }
735 
736 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
737 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
738 ///
739 /// For example, we can fold the following code sequence:
740 /// \code
741 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
742 ///   %1 = icmp ne i32 %x, 0
743 ///   %2 = select i1 %1, i32 %0, i32 32
744 /// \code
745 ///
746 /// into:
747 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
748 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
749                                  InstCombiner::BuilderTy &Builder) {
750   ICmpInst::Predicate Pred = ICI->getPredicate();
751   Value *CmpLHS = ICI->getOperand(0);
752   Value *CmpRHS = ICI->getOperand(1);
753 
754   // Check if the condition value compares a value for equality against zero.
755   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
756     return nullptr;
757 
758   Value *Count = FalseVal;
759   Value *ValueOnZero = TrueVal;
760   if (Pred == ICmpInst::ICMP_NE)
761     std::swap(Count, ValueOnZero);
762 
763   // Skip zero extend/truncate.
764   Value *V = nullptr;
765   if (match(Count, m_ZExt(m_Value(V))) ||
766       match(Count, m_Trunc(m_Value(V))))
767     Count = V;
768 
769   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
770   // input to the cttz/ctlz is used as LHS for the compare instruction.
771   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
772       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
773     return nullptr;
774 
775   IntrinsicInst *II = cast<IntrinsicInst>(Count);
776 
777   // Check if the value propagated on zero is a constant number equal to the
778   // sizeof in bits of 'Count'.
779   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
780   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
781     // Explicitly clear the 'undef_on_zero' flag.
782     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
783     NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
784     Builder.Insert(NewI);
785     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
786   }
787 
788   // If the ValueOnZero is not the bitwidth, we can at least make use of the
789   // fact that the cttz/ctlz result will not be used if the input is zero, so
790   // it's okay to relax it to undef for that case.
791   if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
792     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
793 
794   return nullptr;
795 }
796 
797 /// Return true if we find and adjust an icmp+select pattern where the compare
798 /// is with a constant that can be incremented or decremented to match the
799 /// minimum or maximum idiom.
800 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
801   ICmpInst::Predicate Pred = Cmp.getPredicate();
802   Value *CmpLHS = Cmp.getOperand(0);
803   Value *CmpRHS = Cmp.getOperand(1);
804   Value *TrueVal = Sel.getTrueValue();
805   Value *FalseVal = Sel.getFalseValue();
806 
807   // We may move or edit the compare, so make sure the select is the only user.
808   const APInt *CmpC;
809   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
810     return false;
811 
812   // These transforms only work for selects of integers or vector selects of
813   // integer vectors.
814   Type *SelTy = Sel.getType();
815   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
816   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
817     return false;
818 
819   Constant *AdjustedRHS;
820   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
821     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
822   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
823     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
824   else
825     return false;
826 
827   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
828   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
829   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
830       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
831     ; // Nothing to do here. Values match without any sign/zero extension.
832   }
833   // Types do not match. Instead of calculating this with mixed types, promote
834   // all to the larger type. This enables scalar evolution to analyze this
835   // expression.
836   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
837     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
838 
839     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
840     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
841     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
842     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
843     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
844       CmpLHS = TrueVal;
845       AdjustedRHS = SextRHS;
846     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
847                SextRHS == TrueVal) {
848       CmpLHS = FalseVal;
849       AdjustedRHS = SextRHS;
850     } else if (Cmp.isUnsigned()) {
851       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
852       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
853       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
854       // zext + signed compare cannot be changed:
855       //    0xff <s 0x00, but 0x00ff >s 0x0000
856       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
857         CmpLHS = TrueVal;
858         AdjustedRHS = ZextRHS;
859       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
860                  ZextRHS == TrueVal) {
861         CmpLHS = FalseVal;
862         AdjustedRHS = ZextRHS;
863       } else {
864         return false;
865       }
866     } else {
867       return false;
868     }
869   } else {
870     return false;
871   }
872 
873   Pred = ICmpInst::getSwappedPredicate(Pred);
874   CmpRHS = AdjustedRHS;
875   std::swap(FalseVal, TrueVal);
876   Cmp.setPredicate(Pred);
877   Cmp.setOperand(0, CmpLHS);
878   Cmp.setOperand(1, CmpRHS);
879   Sel.setOperand(1, TrueVal);
880   Sel.setOperand(2, FalseVal);
881   Sel.swapProfMetadata();
882 
883   // Move the compare instruction right before the select instruction. Otherwise
884   // the sext/zext value may be defined after the compare instruction uses it.
885   Cmp.moveBefore(&Sel);
886 
887   return true;
888 }
889 
890 /// If this is an integer min/max (icmp + select) with a constant operand,
891 /// create the canonical icmp for the min/max operation and canonicalize the
892 /// constant to the 'false' operand of the select:
893 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
894 /// Note: if C1 != C2, this will change the icmp constant to the existing
895 /// constant operand of the select.
896 static Instruction *
897 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
898                                InstCombiner::BuilderTy &Builder) {
899   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
900     return nullptr;
901 
902   // Canonicalize the compare predicate based on whether we have min or max.
903   Value *LHS, *RHS;
904   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
905   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
906     return nullptr;
907 
908   // Is this already canonical?
909   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
910   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
911       Cmp.getPredicate() == CanonicalPred)
912     return nullptr;
913 
914   // Create the canonical compare and plug it into the select.
915   Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
916 
917   // If the select operands did not change, we're done.
918   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
919     return &Sel;
920 
921   // If we are swapping the select operands, swap the metadata too.
922   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
923          "Unexpected results from matchSelectPattern");
924   Sel.setTrueValue(LHS);
925   Sel.setFalseValue(RHS);
926   Sel.swapProfMetadata();
927   return &Sel;
928 }
929 
930 /// There are many select variants for each of ABS/NABS.
931 /// In matchSelectPattern(), there are different compare constants, compare
932 /// predicates/operands and select operands.
933 /// In isKnownNegation(), there are different formats of negated operands.
934 /// Canonicalize all these variants to 1 pattern.
935 /// This makes CSE more likely.
936 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
937                                         InstCombiner::BuilderTy &Builder) {
938   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
939     return nullptr;
940 
941   // Choose a sign-bit check for the compare (likely simpler for codegen).
942   // ABS:  (X <s 0) ? -X : X
943   // NABS: (X <s 0) ? X : -X
944   Value *LHS, *RHS;
945   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
946   if (SPF != SelectPatternFlavor::SPF_ABS &&
947       SPF != SelectPatternFlavor::SPF_NABS)
948     return nullptr;
949 
950   Value *TVal = Sel.getTrueValue();
951   Value *FVal = Sel.getFalseValue();
952   assert(isKnownNegation(TVal, FVal) &&
953          "Unexpected result from matchSelectPattern");
954 
955   // The compare may use the negated abs()/nabs() operand, or it may use
956   // negation in non-canonical form such as: sub A, B.
957   bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
958                           match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
959 
960   bool CmpCanonicalized = !CmpUsesNegatedOp &&
961                           match(Cmp.getOperand(1), m_ZeroInt()) &&
962                           Cmp.getPredicate() == ICmpInst::ICMP_SLT;
963   bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
964 
965   // Is this already canonical?
966   if (CmpCanonicalized && RHSCanonicalized)
967     return nullptr;
968 
969   // If RHS is used by other instructions except compare and select, don't
970   // canonicalize it to not increase the instruction count.
971   if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
972     return nullptr;
973 
974   // Create the canonical compare: icmp slt LHS 0.
975   if (!CmpCanonicalized) {
976     Cmp.setPredicate(ICmpInst::ICMP_SLT);
977     Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
978     if (CmpUsesNegatedOp)
979       Cmp.setOperand(0, LHS);
980   }
981 
982   // Create the canonical RHS: RHS = sub (0, LHS).
983   if (!RHSCanonicalized) {
984     assert(RHS->hasOneUse() && "RHS use number is not right");
985     RHS = Builder.CreateNeg(LHS);
986     if (TVal == LHS) {
987       Sel.setFalseValue(RHS);
988       FVal = RHS;
989     } else {
990       Sel.setTrueValue(RHS);
991       TVal = RHS;
992     }
993   }
994 
995   // If the select operands do not change, we're done.
996   if (SPF == SelectPatternFlavor::SPF_NABS) {
997     if (TVal == LHS)
998       return &Sel;
999     assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1000   } else {
1001     if (FVal == LHS)
1002       return &Sel;
1003     assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1004   }
1005 
1006   // We are swapping the select operands, so swap the metadata too.
1007   Sel.setTrueValue(FVal);
1008   Sel.setFalseValue(TVal);
1009   Sel.swapProfMetadata();
1010   return &Sel;
1011 }
1012 
1013 /// Visit a SelectInst that has an ICmpInst as its first operand.
1014 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1015                                                   ICmpInst *ICI) {
1016   Value *TrueVal = SI.getTrueValue();
1017   Value *FalseVal = SI.getFalseValue();
1018 
1019   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
1020     return NewSel;
1021 
1022   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
1023     return NewAbs;
1024 
1025   bool Changed = adjustMinMax(SI, *ICI);
1026 
1027   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1028     return replaceInstUsesWith(SI, V);
1029 
1030   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1031   ICmpInst::Predicate Pred = ICI->getPredicate();
1032   Value *CmpLHS = ICI->getOperand(0);
1033   Value *CmpRHS = ICI->getOperand(1);
1034   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1035     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1036       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1037       SI.setOperand(1, CmpRHS);
1038       Changed = true;
1039     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1040       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1041       SI.setOperand(2, CmpRHS);
1042       Changed = true;
1043     }
1044   }
1045 
1046   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1047   // decomposeBitTestICmp() might help.
1048   {
1049     unsigned BitWidth =
1050         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1051     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1052     Value *X;
1053     const APInt *Y, *C;
1054     bool TrueWhenUnset;
1055     bool IsBitTest = false;
1056     if (ICmpInst::isEquality(Pred) &&
1057         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1058         match(CmpRHS, m_Zero())) {
1059       IsBitTest = true;
1060       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1061     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1062       X = CmpLHS;
1063       Y = &MinSignedValue;
1064       IsBitTest = true;
1065       TrueWhenUnset = false;
1066     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1067       X = CmpLHS;
1068       Y = &MinSignedValue;
1069       IsBitTest = true;
1070       TrueWhenUnset = true;
1071     }
1072     if (IsBitTest) {
1073       Value *V = nullptr;
1074       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1075       if (TrueWhenUnset && TrueVal == X &&
1076           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1077         V = Builder.CreateAnd(X, ~(*Y));
1078       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1079       else if (!TrueWhenUnset && FalseVal == X &&
1080                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1081         V = Builder.CreateAnd(X, ~(*Y));
1082       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1083       else if (TrueWhenUnset && FalseVal == X &&
1084                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1085         V = Builder.CreateOr(X, *Y);
1086       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1087       else if (!TrueWhenUnset && TrueVal == X &&
1088                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1089         V = Builder.CreateOr(X, *Y);
1090 
1091       if (V)
1092         return replaceInstUsesWith(SI, V);
1093     }
1094   }
1095 
1096   if (Instruction *V =
1097           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1098     return V;
1099 
1100   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1101     return replaceInstUsesWith(SI, V);
1102 
1103   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1104     return replaceInstUsesWith(SI, V);
1105 
1106   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1107     return replaceInstUsesWith(SI, V);
1108 
1109   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1110     return replaceInstUsesWith(SI, V);
1111 
1112   return Changed ? &SI : nullptr;
1113 }
1114 
1115 /// SI is a select whose condition is a PHI node (but the two may be in
1116 /// different blocks). See if the true/false values (V) are live in all of the
1117 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1118 ///
1119 ///   X = phi [ C1, BB1], [C2, BB2]
1120 ///   Y = add
1121 ///   Z = select X, Y, 0
1122 ///
1123 /// because Y is not live in BB1/BB2.
1124 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1125                                                    const SelectInst &SI) {
1126   // If the value is a non-instruction value like a constant or argument, it
1127   // can always be mapped.
1128   const Instruction *I = dyn_cast<Instruction>(V);
1129   if (!I) return true;
1130 
1131   // If V is a PHI node defined in the same block as the condition PHI, we can
1132   // map the arguments.
1133   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1134 
1135   if (const PHINode *VP = dyn_cast<PHINode>(I))
1136     if (VP->getParent() == CondPHI->getParent())
1137       return true;
1138 
1139   // Otherwise, if the PHI and select are defined in the same block and if V is
1140   // defined in a different block, then we can transform it.
1141   if (SI.getParent() == CondPHI->getParent() &&
1142       I->getParent() != CondPHI->getParent())
1143     return true;
1144 
1145   // Otherwise we have a 'hard' case and we can't tell without doing more
1146   // detailed dominator based analysis, punt.
1147   return false;
1148 }
1149 
1150 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1151 ///   SPF2(SPF1(A, B), C)
1152 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1153                                         SelectPatternFlavor SPF1,
1154                                         Value *A, Value *B,
1155                                         Instruction &Outer,
1156                                         SelectPatternFlavor SPF2, Value *C) {
1157   if (Outer.getType() != Inner->getType())
1158     return nullptr;
1159 
1160   if (C == A || C == B) {
1161     // MAX(MAX(A, B), B) -> MAX(A, B)
1162     // MIN(MIN(a, b), a) -> MIN(a, b)
1163     // TODO: This could be done in instsimplify.
1164     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1165       return replaceInstUsesWith(Outer, Inner);
1166 
1167     // MAX(MIN(a, b), a) -> a
1168     // MIN(MAX(a, b), a) -> a
1169     // TODO: This could be done in instsimplify.
1170     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1171         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1172         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1173         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1174       return replaceInstUsesWith(Outer, C);
1175   }
1176 
1177   if (SPF1 == SPF2) {
1178     const APInt *CB, *CC;
1179     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1180       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1181       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1182       // TODO: This could be done in instsimplify.
1183       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1184           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1185           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1186           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1187         return replaceInstUsesWith(Outer, Inner);
1188 
1189       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1190       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1191       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1192           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1193           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1194           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1195         Outer.replaceUsesOfWith(Inner, A);
1196         return &Outer;
1197       }
1198     }
1199   }
1200 
1201   // ABS(ABS(X)) -> ABS(X)
1202   // NABS(NABS(X)) -> NABS(X)
1203   // TODO: This could be done in instsimplify.
1204   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1205     return replaceInstUsesWith(Outer, Inner);
1206   }
1207 
1208   // ABS(NABS(X)) -> ABS(X)
1209   // NABS(ABS(X)) -> NABS(X)
1210   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1211       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1212     SelectInst *SI = cast<SelectInst>(Inner);
1213     Value *NewSI =
1214         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1215                              SI->getTrueValue(), SI->getName(), SI);
1216     return replaceInstUsesWith(Outer, NewSI);
1217   }
1218 
1219   auto IsFreeOrProfitableToInvert =
1220       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1221     if (match(V, m_Not(m_Value(NotV)))) {
1222       // If V has at most 2 uses then we can get rid of the xor operation
1223       // entirely.
1224       ElidesXor |= !V->hasNUsesOrMore(3);
1225       return true;
1226     }
1227 
1228     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1229       NotV = nullptr;
1230       return true;
1231     }
1232 
1233     return false;
1234   };
1235 
1236   Value *NotA, *NotB, *NotC;
1237   bool ElidesXor = false;
1238 
1239   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1240   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1241   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1242   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1243   //
1244   // This transform is performance neutral if we can elide at least one xor from
1245   // the set of three operands, since we'll be tacking on an xor at the very
1246   // end.
1247   if (SelectPatternResult::isMinOrMax(SPF1) &&
1248       SelectPatternResult::isMinOrMax(SPF2) &&
1249       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1250       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1251       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1252     if (!NotA)
1253       NotA = Builder.CreateNot(A);
1254     if (!NotB)
1255       NotB = Builder.CreateNot(B);
1256     if (!NotC)
1257       NotC = Builder.CreateNot(C);
1258 
1259     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1260                                    NotB);
1261     Value *NewOuter = Builder.CreateNot(
1262         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1263     return replaceInstUsesWith(Outer, NewOuter);
1264   }
1265 
1266   return nullptr;
1267 }
1268 
1269 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1270 /// This is even legal for FP.
1271 static Instruction *foldAddSubSelect(SelectInst &SI,
1272                                      InstCombiner::BuilderTy &Builder) {
1273   Value *CondVal = SI.getCondition();
1274   Value *TrueVal = SI.getTrueValue();
1275   Value *FalseVal = SI.getFalseValue();
1276   auto *TI = dyn_cast<Instruction>(TrueVal);
1277   auto *FI = dyn_cast<Instruction>(FalseVal);
1278   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1279     return nullptr;
1280 
1281   Instruction *AddOp = nullptr, *SubOp = nullptr;
1282   if ((TI->getOpcode() == Instruction::Sub &&
1283        FI->getOpcode() == Instruction::Add) ||
1284       (TI->getOpcode() == Instruction::FSub &&
1285        FI->getOpcode() == Instruction::FAdd)) {
1286     AddOp = FI;
1287     SubOp = TI;
1288   } else if ((FI->getOpcode() == Instruction::Sub &&
1289               TI->getOpcode() == Instruction::Add) ||
1290              (FI->getOpcode() == Instruction::FSub &&
1291               TI->getOpcode() == Instruction::FAdd)) {
1292     AddOp = TI;
1293     SubOp = FI;
1294   }
1295 
1296   if (AddOp) {
1297     Value *OtherAddOp = nullptr;
1298     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1299       OtherAddOp = AddOp->getOperand(1);
1300     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1301       OtherAddOp = AddOp->getOperand(0);
1302     }
1303 
1304     if (OtherAddOp) {
1305       // So at this point we know we have (Y -> OtherAddOp):
1306       //        select C, (add X, Y), (sub X, Z)
1307       Value *NegVal; // Compute -Z
1308       if (SI.getType()->isFPOrFPVectorTy()) {
1309         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1310         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1311           FastMathFlags Flags = AddOp->getFastMathFlags();
1312           Flags &= SubOp->getFastMathFlags();
1313           NegInst->setFastMathFlags(Flags);
1314         }
1315       } else {
1316         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1317       }
1318 
1319       Value *NewTrueOp = OtherAddOp;
1320       Value *NewFalseOp = NegVal;
1321       if (AddOp != TI)
1322         std::swap(NewTrueOp, NewFalseOp);
1323       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1324                                            SI.getName() + ".p", &SI);
1325 
1326       if (SI.getType()->isFPOrFPVectorTy()) {
1327         Instruction *RI =
1328             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1329 
1330         FastMathFlags Flags = AddOp->getFastMathFlags();
1331         Flags &= SubOp->getFastMathFlags();
1332         RI->setFastMathFlags(Flags);
1333         return RI;
1334       } else
1335         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1336     }
1337   }
1338   return nullptr;
1339 }
1340 
1341 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1342   Constant *C;
1343   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1344       !match(Sel.getFalseValue(), m_Constant(C)))
1345     return nullptr;
1346 
1347   Instruction *ExtInst;
1348   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1349       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1350     return nullptr;
1351 
1352   auto ExtOpcode = ExtInst->getOpcode();
1353   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1354     return nullptr;
1355 
1356   // If we are extending from a boolean type or if we can create a select that
1357   // has the same size operands as its condition, try to narrow the select.
1358   Value *X = ExtInst->getOperand(0);
1359   Type *SmallType = X->getType();
1360   Value *Cond = Sel.getCondition();
1361   auto *Cmp = dyn_cast<CmpInst>(Cond);
1362   if (!SmallType->isIntOrIntVectorTy(1) &&
1363       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1364     return nullptr;
1365 
1366   // If the constant is the same after truncation to the smaller type and
1367   // extension to the original type, we can narrow the select.
1368   Type *SelType = Sel.getType();
1369   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1370   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1371   if (ExtC == C) {
1372     Value *TruncCVal = cast<Value>(TruncC);
1373     if (ExtInst == Sel.getFalseValue())
1374       std::swap(X, TruncCVal);
1375 
1376     // select Cond, (ext X), C --> ext(select Cond, X, C')
1377     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1378     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1379     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1380   }
1381 
1382   // If one arm of the select is the extend of the condition, replace that arm
1383   // with the extension of the appropriate known bool value.
1384   if (Cond == X) {
1385     if (ExtInst == Sel.getTrueValue()) {
1386       // select X, (sext X), C --> select X, -1, C
1387       // select X, (zext X), C --> select X,  1, C
1388       Constant *One = ConstantInt::getTrue(SmallType);
1389       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1390       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1391     } else {
1392       // select X, C, (sext X) --> select X, C, 0
1393       // select X, C, (zext X) --> select X, C, 0
1394       Constant *Zero = ConstantInt::getNullValue(SelType);
1395       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1396     }
1397   }
1398 
1399   return nullptr;
1400 }
1401 
1402 /// Try to transform a vector select with a constant condition vector into a
1403 /// shuffle for easier combining with other shuffles and insert/extract.
1404 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1405   Value *CondVal = SI.getCondition();
1406   Constant *CondC;
1407   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1408     return nullptr;
1409 
1410   unsigned NumElts = CondVal->getType()->getVectorNumElements();
1411   SmallVector<Constant *, 16> Mask;
1412   Mask.reserve(NumElts);
1413   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1414   for (unsigned i = 0; i != NumElts; ++i) {
1415     Constant *Elt = CondC->getAggregateElement(i);
1416     if (!Elt)
1417       return nullptr;
1418 
1419     if (Elt->isOneValue()) {
1420       // If the select condition element is true, choose from the 1st vector.
1421       Mask.push_back(ConstantInt::get(Int32Ty, i));
1422     } else if (Elt->isNullValue()) {
1423       // If the select condition element is false, choose from the 2nd vector.
1424       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1425     } else if (isa<UndefValue>(Elt)) {
1426       // Undef in a select condition (choose one of the operands) does not mean
1427       // the same thing as undef in a shuffle mask (any value is acceptable), so
1428       // give up.
1429       return nullptr;
1430     } else {
1431       // Bail out on a constant expression.
1432       return nullptr;
1433     }
1434   }
1435 
1436   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1437                                ConstantVector::get(Mask));
1438 }
1439 
1440 /// Reuse bitcasted operands between a compare and select:
1441 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1442 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1443 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1444                                           InstCombiner::BuilderTy &Builder) {
1445   Value *Cond = Sel.getCondition();
1446   Value *TVal = Sel.getTrueValue();
1447   Value *FVal = Sel.getFalseValue();
1448 
1449   CmpInst::Predicate Pred;
1450   Value *A, *B;
1451   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1452     return nullptr;
1453 
1454   // The select condition is a compare instruction. If the select's true/false
1455   // values are already the same as the compare operands, there's nothing to do.
1456   if (TVal == A || TVal == B || FVal == A || FVal == B)
1457     return nullptr;
1458 
1459   Value *C, *D;
1460   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1461     return nullptr;
1462 
1463   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1464   Value *TSrc, *FSrc;
1465   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1466       !match(FVal, m_BitCast(m_Value(FSrc))))
1467     return nullptr;
1468 
1469   // If the select true/false values are *different bitcasts* of the same source
1470   // operands, make the select operands the same as the compare operands and
1471   // cast the result. This is the canonical select form for min/max.
1472   Value *NewSel;
1473   if (TSrc == C && FSrc == D) {
1474     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1475     // bitcast (select (cmp A, B), A, B)
1476     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1477   } else if (TSrc == D && FSrc == C) {
1478     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1479     // bitcast (select (cmp A, B), B, A)
1480     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1481   } else {
1482     return nullptr;
1483   }
1484   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1485 }
1486 
1487 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1488 /// instructions.
1489 ///
1490 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1491 /// selects between the returned value of the cmpxchg instruction its compare
1492 /// operand, the result of the select will always be equal to its false value.
1493 /// For example:
1494 ///
1495 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1496 ///   %1 = extractvalue { i64, i1 } %0, 1
1497 ///   %2 = extractvalue { i64, i1 } %0, 0
1498 ///   %3 = select i1 %1, i64 %compare, i64 %2
1499 ///   ret i64 %3
1500 ///
1501 /// The returned value of the cmpxchg instruction (%2) is the original value
1502 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1503 /// must have been equal to %compare. Thus, the result of the select is always
1504 /// equal to %2, and the code can be simplified to:
1505 ///
1506 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1507 ///   %1 = extractvalue { i64, i1 } %0, 0
1508 ///   ret i64 %1
1509 ///
1510 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1511   // A helper that determines if V is an extractvalue instruction whose
1512   // aggregate operand is a cmpxchg instruction and whose single index is equal
1513   // to I. If such conditions are true, the helper returns the cmpxchg
1514   // instruction; otherwise, a nullptr is returned.
1515   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1516     auto *Extract = dyn_cast<ExtractValueInst>(V);
1517     if (!Extract)
1518       return nullptr;
1519     if (Extract->getIndices()[0] != I)
1520       return nullptr;
1521     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1522   };
1523 
1524   // If the select has a single user, and this user is a select instruction that
1525   // we can simplify, skip the cmpxchg simplification for now.
1526   if (SI.hasOneUse())
1527     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1528       if (Select->getCondition() == SI.getCondition())
1529         if (Select->getFalseValue() == SI.getTrueValue() ||
1530             Select->getTrueValue() == SI.getFalseValue())
1531           return nullptr;
1532 
1533   // Ensure the select condition is the returned flag of a cmpxchg instruction.
1534   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1535   if (!CmpXchg)
1536     return nullptr;
1537 
1538   // Check the true value case: The true value of the select is the returned
1539   // value of the same cmpxchg used by the condition, and the false value is the
1540   // cmpxchg instruction's compare operand.
1541   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1542     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1543       SI.setTrueValue(SI.getFalseValue());
1544       return &SI;
1545     }
1546 
1547   // Check the false value case: The false value of the select is the returned
1548   // value of the same cmpxchg used by the condition, and the true value is the
1549   // cmpxchg instruction's compare operand.
1550   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1551     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1552       SI.setTrueValue(SI.getFalseValue());
1553       return &SI;
1554     }
1555 
1556   return nullptr;
1557 }
1558 
1559 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
1560                                        Value *Y,
1561                                        InstCombiner::BuilderTy &Builder) {
1562   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
1563   bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
1564                     SPF == SelectPatternFlavor::SPF_UMAX;
1565   // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
1566   // the constant value check to an assert.
1567   Value *A;
1568   const APInt *C1, *C2;
1569   if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
1570       match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
1571     // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
1572     // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
1573     Value *NewMinMax = createMinMax(Builder, SPF, A,
1574                                     ConstantInt::get(X->getType(), *C2 - *C1));
1575     return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
1576                                      ConstantInt::get(X->getType(), *C1));
1577   }
1578 
1579   if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
1580       match(Y, m_APInt(C2)) && X->hasNUses(2)) {
1581     bool Overflow;
1582     APInt Diff = C2->ssub_ov(*C1, Overflow);
1583     if (!Overflow) {
1584       // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
1585       // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
1586       Value *NewMinMax = createMinMax(Builder, SPF, A,
1587                                       ConstantInt::get(X->getType(), Diff));
1588       return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
1589                                        ConstantInt::get(X->getType(), *C1));
1590     }
1591   }
1592 
1593   return nullptr;
1594 }
1595 
1596 /// Reduce a sequence of min/max with a common operand.
1597 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1598                                         Value *RHS,
1599                                         InstCombiner::BuilderTy &Builder) {
1600   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1601   // TODO: Allow FP min/max with nnan/nsz.
1602   if (!LHS->getType()->isIntOrIntVectorTy())
1603     return nullptr;
1604 
1605   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1606   Value *A, *B, *C, *D;
1607   SelectPatternResult L = matchSelectPattern(LHS, A, B);
1608   SelectPatternResult R = matchSelectPattern(RHS, C, D);
1609   if (SPF != L.Flavor || L.Flavor != R.Flavor)
1610     return nullptr;
1611 
1612   // Look for a common operand. The use checks are different than usual because
1613   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1614   // the select.
1615   Value *MinMaxOp = nullptr;
1616   Value *ThirdOp = nullptr;
1617   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
1618     // If the LHS is only used in this chain and the RHS is used outside of it,
1619     // reuse the RHS min/max because that will eliminate the LHS.
1620     if (D == A || C == A) {
1621       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1622       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1623       MinMaxOp = RHS;
1624       ThirdOp = B;
1625     } else if (D == B || C == B) {
1626       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1627       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1628       MinMaxOp = RHS;
1629       ThirdOp = A;
1630     }
1631   } else if (!RHS->hasNUsesOrMore(3)) {
1632     // Reuse the LHS. This will eliminate the RHS.
1633     if (D == A || D == B) {
1634       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1635       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1636       MinMaxOp = LHS;
1637       ThirdOp = C;
1638     } else if (C == A || C == B) {
1639       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1640       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1641       MinMaxOp = LHS;
1642       ThirdOp = D;
1643     }
1644   }
1645   if (!MinMaxOp || !ThirdOp)
1646     return nullptr;
1647 
1648   CmpInst::Predicate P = getMinMaxPred(SPF);
1649   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1650   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1651 }
1652 
1653 /// Try to reduce a rotate pattern that includes a compare and select into a
1654 /// funnel shift intrinsic. Example:
1655 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
1656 ///              --> call llvm.fshl.i32(a, a, b)
1657 static Instruction *foldSelectRotate(SelectInst &Sel) {
1658   // The false value of the select must be a rotate of the true value.
1659   Value *Or0, *Or1;
1660   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
1661     return nullptr;
1662 
1663   Value *TVal = Sel.getTrueValue();
1664   Value *SA0, *SA1;
1665   if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
1666       !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
1667     return nullptr;
1668 
1669   auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
1670   auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
1671   if (ShiftOpcode0 == ShiftOpcode1)
1672     return nullptr;
1673 
1674   // We have one of these patterns so far:
1675   // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
1676   // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
1677   // This must be a power-of-2 rotate for a bitmasking transform to be valid.
1678   unsigned Width = Sel.getType()->getScalarSizeInBits();
1679   if (!isPowerOf2_32(Width))
1680     return nullptr;
1681 
1682   // Check the shift amounts to see if they are an opposite pair.
1683   Value *ShAmt;
1684   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
1685     ShAmt = SA0;
1686   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
1687     ShAmt = SA1;
1688   else
1689     return nullptr;
1690 
1691   // Finally, see if the select is filtering out a shift-by-zero.
1692   Value *Cond = Sel.getCondition();
1693   ICmpInst::Predicate Pred;
1694   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
1695       Pred != ICmpInst::ICMP_EQ)
1696     return nullptr;
1697 
1698   // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
1699   // Convert to funnel shift intrinsic.
1700   bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
1701                 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
1702   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
1703   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
1704   return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
1705 }
1706 
1707 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1708   Value *CondVal = SI.getCondition();
1709   Value *TrueVal = SI.getTrueValue();
1710   Value *FalseVal = SI.getFalseValue();
1711   Type *SelType = SI.getType();
1712 
1713   // FIXME: Remove this workaround when freeze related patches are done.
1714   // For select with undef operand which feeds into an equality comparison,
1715   // don't simplify it so loop unswitch can know the equality comparison
1716   // may have an undef operand. This is a workaround for PR31652 caused by
1717   // descrepancy about branch on undef between LoopUnswitch and GVN.
1718   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1719     if (llvm::any_of(SI.users(), [&](User *U) {
1720           ICmpInst *CI = dyn_cast<ICmpInst>(U);
1721           if (CI && CI->isEquality())
1722             return true;
1723           return false;
1724         })) {
1725       return nullptr;
1726     }
1727   }
1728 
1729   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1730                                     SQ.getWithInstruction(&SI)))
1731     return replaceInstUsesWith(SI, V);
1732 
1733   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1734     return I;
1735 
1736   // Canonicalize a one-use integer compare with a non-canonical predicate by
1737   // inverting the predicate and swapping the select operands. This matches a
1738   // compare canonicalization for conditional branches.
1739   // TODO: Should we do the same for FP compares?
1740   CmpInst::Predicate Pred;
1741   if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1742       !isCanonicalPredicate(Pred)) {
1743     // Swap true/false values and condition.
1744     CmpInst *Cond = cast<CmpInst>(CondVal);
1745     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1746     SI.setOperand(1, FalseVal);
1747     SI.setOperand(2, TrueVal);
1748     SI.swapProfMetadata();
1749     Worklist.Add(Cond);
1750     return &SI;
1751   }
1752 
1753   if (SelType->isIntOrIntVectorTy(1) &&
1754       TrueVal->getType() == CondVal->getType()) {
1755     if (match(TrueVal, m_One())) {
1756       // Change: A = select B, true, C --> A = or B, C
1757       return BinaryOperator::CreateOr(CondVal, FalseVal);
1758     }
1759     if (match(TrueVal, m_Zero())) {
1760       // Change: A = select B, false, C --> A = and !B, C
1761       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1762       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1763     }
1764     if (match(FalseVal, m_Zero())) {
1765       // Change: A = select B, C, false --> A = and B, C
1766       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1767     }
1768     if (match(FalseVal, m_One())) {
1769       // Change: A = select B, C, true --> A = or !B, C
1770       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1771       return BinaryOperator::CreateOr(NotCond, TrueVal);
1772     }
1773 
1774     // select a, a, b  -> a | b
1775     // select a, b, a  -> a & b
1776     if (CondVal == TrueVal)
1777       return BinaryOperator::CreateOr(CondVal, FalseVal);
1778     if (CondVal == FalseVal)
1779       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1780 
1781     // select a, ~a, b -> (~a) & b
1782     // select a, b, ~a -> (~a) | b
1783     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1784       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1785     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1786       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1787   }
1788 
1789   // Selecting between two integer or vector splat integer constants?
1790   //
1791   // Note that we don't handle a scalar select of vectors:
1792   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1793   // because that may need 3 instructions to splat the condition value:
1794   // extend, insertelement, shufflevector.
1795   if (SelType->isIntOrIntVectorTy() &&
1796       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1797     // select C, 1, 0 -> zext C to int
1798     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1799       return new ZExtInst(CondVal, SelType);
1800 
1801     // select C, -1, 0 -> sext C to int
1802     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1803       return new SExtInst(CondVal, SelType);
1804 
1805     // select C, 0, 1 -> zext !C to int
1806     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1807       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1808       return new ZExtInst(NotCond, SelType);
1809     }
1810 
1811     // select C, 0, -1 -> sext !C to int
1812     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1813       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1814       return new SExtInst(NotCond, SelType);
1815     }
1816   }
1817 
1818   // See if we are selecting two values based on a comparison of the two values.
1819   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1820     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1821       // Canonicalize to use ordered comparisons by swapping the select
1822       // operands.
1823       //
1824       // e.g.
1825       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1826       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1827         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1828         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1829         Builder.setFastMathFlags(FCI->getFastMathFlags());
1830         Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1831                                             FCI->getName() + ".inv");
1832 
1833         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1834                                   SI.getName() + ".p");
1835       }
1836 
1837       // NOTE: if we wanted to, this is where to detect MIN/MAX
1838     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1839       // Canonicalize to use ordered comparisons by swapping the select
1840       // operands.
1841       //
1842       // e.g.
1843       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1844       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1845         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1846         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1847         Builder.setFastMathFlags(FCI->getFastMathFlags());
1848         Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1849                                             FCI->getName() + ".inv");
1850 
1851         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1852                                   SI.getName() + ".p");
1853       }
1854 
1855       // NOTE: if we wanted to, this is where to detect MIN/MAX
1856     }
1857 
1858     // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1859     // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1860     // also require nnan because we do not want to unintentionally change the
1861     // sign of a NaN value.
1862     Value *X = FCI->getOperand(0);
1863     FCmpInst::Predicate Pred = FCI->getPredicate();
1864     if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1865       // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1866       // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
1867       if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1868            match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1869           (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1870            match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
1871         Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1872         return replaceInstUsesWith(SI, Fabs);
1873       }
1874       // With nsz:
1875       // (X <  +/-0.0) ? -X : X --> fabs(X)
1876       // (X <= +/-0.0) ? -X : X --> fabs(X)
1877       // (X >  +/-0.0) ? X : -X --> fabs(X)
1878       // (X >= +/-0.0) ? X : -X --> fabs(X)
1879       if (FCI->hasNoSignedZeros() &&
1880           ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1881             (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1882            (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1883             (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1884         Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1885         return replaceInstUsesWith(SI, Fabs);
1886       }
1887     }
1888   }
1889 
1890   // See if we are selecting two values based on a comparison of the two values.
1891   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1892     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1893       return Result;
1894 
1895   if (Instruction *Add = foldAddSubSelect(SI, Builder))
1896     return Add;
1897 
1898   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1899   auto *TI = dyn_cast<Instruction>(TrueVal);
1900   auto *FI = dyn_cast<Instruction>(FalseVal);
1901   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1902     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1903       return IV;
1904 
1905   if (Instruction *I = foldSelectExtConst(SI))
1906     return I;
1907 
1908   // See if we can fold the select into one of our operands.
1909   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1910     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1911       return FoldI;
1912 
1913     Value *LHS, *RHS;
1914     Instruction::CastOps CastOp;
1915     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1916     auto SPF = SPR.Flavor;
1917     if (SPF) {
1918       Value *LHS2, *RHS2;
1919       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1920         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
1921                                           RHS2, SI, SPF, RHS))
1922           return R;
1923       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1924         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
1925                                           RHS2, SI, SPF, LHS))
1926           return R;
1927       // TODO.
1928       // ABS(-X) -> ABS(X)
1929     }
1930 
1931     if (SelectPatternResult::isMinOrMax(SPF)) {
1932       // Canonicalize so that
1933       // - type casts are outside select patterns.
1934       // - float clamp is transformed to min/max pattern
1935 
1936       bool IsCastNeeded = LHS->getType() != SelType;
1937       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1938       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1939       if (IsCastNeeded ||
1940           (LHS->getType()->isFPOrFPVectorTy() &&
1941            ((CmpLHS != LHS && CmpLHS != RHS) ||
1942             (CmpRHS != LHS && CmpRHS != RHS)))) {
1943         CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1944 
1945         Value *Cmp;
1946         if (CmpInst::isIntPredicate(Pred)) {
1947           Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1948         } else {
1949           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1950           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1951           Builder.setFastMathFlags(FMF);
1952           Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1953         }
1954 
1955         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1956         if (!IsCastNeeded)
1957           return replaceInstUsesWith(SI, NewSI);
1958 
1959         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1960         return replaceInstUsesWith(SI, NewCast);
1961       }
1962 
1963       // MAX(~a, ~b) -> ~MIN(a, b)
1964       // MAX(~a, C)  -> ~MIN(a, ~C)
1965       // MIN(~a, ~b) -> ~MAX(a, b)
1966       // MIN(~a, C)  -> ~MAX(a, ~C)
1967       auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1968         Value *A;
1969         if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
1970             !IsFreeToInvert(A, A->hasOneUse()) &&
1971             // Passing false to only consider m_Not and constants.
1972             IsFreeToInvert(Y, false)) {
1973           Value *B = Builder.CreateNot(Y);
1974           Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
1975                                           A, B);
1976           // Copy the profile metadata.
1977           if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
1978             cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
1979             // Swap the metadata if the operands are swapped.
1980             if (X == SI.getFalseValue() && Y == SI.getTrueValue())
1981               cast<SelectInst>(NewMinMax)->swapProfMetadata();
1982           }
1983 
1984           return BinaryOperator::CreateNot(NewMinMax);
1985         }
1986 
1987         return nullptr;
1988       };
1989 
1990       if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
1991         return I;
1992       if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
1993         return I;
1994 
1995       if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
1996         return I;
1997 
1998       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1999         return I;
2000     }
2001   }
2002 
2003   // See if we can fold the select into a phi node if the condition is a select.
2004   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2005     // The true/false values have to be live in the PHI predecessor's blocks.
2006     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2007         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2008       if (Instruction *NV = foldOpIntoPhi(SI, PN))
2009         return NV;
2010 
2011   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2012     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2013       // select(C, select(C, a, b), c) -> select(C, a, c)
2014       if (TrueSI->getCondition() == CondVal) {
2015         if (SI.getTrueValue() == TrueSI->getTrueValue())
2016           return nullptr;
2017         SI.setOperand(1, TrueSI->getTrueValue());
2018         return &SI;
2019       }
2020       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2021       // We choose this as normal form to enable folding on the And and shortening
2022       // paths for the values (this helps GetUnderlyingObjects() for example).
2023       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2024         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2025         SI.setOperand(0, And);
2026         SI.setOperand(1, TrueSI->getTrueValue());
2027         return &SI;
2028       }
2029     }
2030   }
2031   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2032     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2033       // select(C, a, select(C, b, c)) -> select(C, a, c)
2034       if (FalseSI->getCondition() == CondVal) {
2035         if (SI.getFalseValue() == FalseSI->getFalseValue())
2036           return nullptr;
2037         SI.setOperand(2, FalseSI->getFalseValue());
2038         return &SI;
2039       }
2040       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2041       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2042         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2043         SI.setOperand(0, Or);
2044         SI.setOperand(2, FalseSI->getFalseValue());
2045         return &SI;
2046       }
2047     }
2048   }
2049 
2050   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2051     // The select might be preventing a division by 0.
2052     switch (BO->getOpcode()) {
2053     default:
2054       return true;
2055     case Instruction::SRem:
2056     case Instruction::URem:
2057     case Instruction::SDiv:
2058     case Instruction::UDiv:
2059       return false;
2060     }
2061   };
2062 
2063   // Try to simplify a binop sandwiched between 2 selects with the same
2064   // condition.
2065   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2066   BinaryOperator *TrueBO;
2067   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2068       canMergeSelectThroughBinop(TrueBO)) {
2069     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2070       if (TrueBOSI->getCondition() == CondVal) {
2071         TrueBO->setOperand(0, TrueBOSI->getTrueValue());
2072         Worklist.Add(TrueBO);
2073         return &SI;
2074       }
2075     }
2076     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2077       if (TrueBOSI->getCondition() == CondVal) {
2078         TrueBO->setOperand(1, TrueBOSI->getTrueValue());
2079         Worklist.Add(TrueBO);
2080         return &SI;
2081       }
2082     }
2083   }
2084 
2085   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2086   BinaryOperator *FalseBO;
2087   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2088       canMergeSelectThroughBinop(FalseBO)) {
2089     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2090       if (FalseBOSI->getCondition() == CondVal) {
2091         FalseBO->setOperand(0, FalseBOSI->getFalseValue());
2092         Worklist.Add(FalseBO);
2093         return &SI;
2094       }
2095     }
2096     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2097       if (FalseBOSI->getCondition() == CondVal) {
2098         FalseBO->setOperand(1, FalseBOSI->getFalseValue());
2099         Worklist.Add(FalseBO);
2100         return &SI;
2101       }
2102     }
2103   }
2104 
2105   Value *NotCond;
2106   if (match(CondVal, m_Not(m_Value(NotCond)))) {
2107     SI.setOperand(0, NotCond);
2108     SI.setOperand(1, FalseVal);
2109     SI.setOperand(2, TrueVal);
2110     SI.swapProfMetadata();
2111     return &SI;
2112   }
2113 
2114   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2115     unsigned VWidth = VecTy->getNumElements();
2116     APInt UndefElts(VWidth, 0);
2117     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2118     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2119       if (V != &SI)
2120         return replaceInstUsesWith(SI, V);
2121       return &SI;
2122     }
2123   }
2124 
2125   // If we can compute the condition, there's no need for a select.
2126   // Like the above fold, we are attempting to reduce compile-time cost by
2127   // putting this fold here with limitations rather than in InstSimplify.
2128   // The motivation for this call into value tracking is to take advantage of
2129   // the assumption cache, so make sure that is populated.
2130   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2131     KnownBits Known(1);
2132     computeKnownBits(CondVal, Known, 0, &SI);
2133     if (Known.One.isOneValue())
2134       return replaceInstUsesWith(SI, TrueVal);
2135     if (Known.Zero.isOneValue())
2136       return replaceInstUsesWith(SI, FalseVal);
2137   }
2138 
2139   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2140     return BitCastSel;
2141 
2142   // Simplify selects that test the returned flag of cmpxchg instructions.
2143   if (Instruction *Select = foldSelectCmpXchg(SI))
2144     return Select;
2145 
2146   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
2147     return Select;
2148 
2149   if (Instruction *Rot = foldSelectRotate(SI))
2150     return Rot;
2151 
2152   return nullptr;
2153 }
2154