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