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