1 //===- InstCombineSelect.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitSelect function.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Support/KnownBits.h"
22 using namespace PatternMatch;
24 #define DEBUG_TYPE "instcombine"
26 static SelectPatternFlavor
27 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
30 llvm_unreachable("unhandled!");
43 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
47 llvm_unreachable("unhandled!");
50 return ICmpInst::ICMP_SLT;
52 return ICmpInst::ICMP_ULT;
54 return ICmpInst::ICMP_SGT;
56 return ICmpInst::ICMP_UGT;
58 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
60 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
64 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
65 SelectPatternFlavor SPF, Value *A,
67 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
68 assert(CmpInst::isIntPredicate(Pred));
69 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
72 /// We want to turn code that looks like this:
74 /// %D = select %cond, %C, %A
76 /// %C = select %cond, %B, 0
79 /// Assuming that the specified instruction is an operand to the select, return
80 /// a bitmask indicating which operands of this instruction are foldable if they
81 /// equal the other incoming value of the select.
83 static unsigned getSelectFoldableOperands(Instruction *I) {
84 switch (I->getOpcode()) {
85 case Instruction::Add:
86 case Instruction::Mul:
87 case Instruction::And:
89 case Instruction::Xor:
90 return 3; // Can fold through either operand.
91 case Instruction::Sub: // Can only fold on the amount subtracted.
92 case Instruction::Shl: // Can only fold on the shift amount.
93 case Instruction::LShr:
94 case Instruction::AShr:
97 return 0; // Cannot fold
101 /// For the same transformation as the previous function, return the identity
102 /// constant that goes into the select.
103 static Constant *getSelectFoldableConstant(Instruction *I) {
104 switch (I->getOpcode()) {
105 default: llvm_unreachable("This cannot happen!");
106 case Instruction::Add:
107 case Instruction::Sub:
108 case Instruction::Or:
109 case Instruction::Xor:
110 case Instruction::Shl:
111 case Instruction::LShr:
112 case Instruction::AShr:
113 return Constant::getNullValue(I->getType());
114 case Instruction::And:
115 return Constant::getAllOnesValue(I->getType());
116 case Instruction::Mul:
117 return ConstantInt::get(I->getType(), 1);
121 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
122 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
124 // Don't break up min/max patterns. The hasOneUse checks below prevent that
125 // for most cases, but vector min/max with bitcasts can be transformed. If the
126 // one-use restrictions are eased for other patterns, we still don't want to
127 // obfuscate min/max.
128 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
129 match(&SI, m_SMax(m_Value(), m_Value())) ||
130 match(&SI, m_UMin(m_Value(), m_Value())) ||
131 match(&SI, m_UMax(m_Value(), m_Value()))))
134 // If this is a cast from the same type, merge.
135 if (TI->getNumOperands() == 1 && TI->isCast()) {
136 Type *FIOpndTy = FI->getOperand(0)->getType();
137 if (TI->getOperand(0)->getType() != FIOpndTy)
140 // The select condition may be a vector. We may only change the operand
141 // type if the vector width remains the same (and matches the condition).
142 Type *CondTy = SI.getCondition()->getType();
143 if (CondTy->isVectorTy()) {
144 if (!FIOpndTy->isVectorTy())
146 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
149 // TODO: If the backend knew how to deal with casts better, we could
150 // remove this limitation. For now, there's too much potential to create
151 // worse codegen by promoting the select ahead of size-altering casts
154 // Note that ValueTracking's matchSelectPattern() looks through casts
155 // without checking 'hasOneUse' when it matches min/max patterns, so this
156 // transform may end up happening anyway.
157 if (TI->getOpcode() != Instruction::BitCast &&
158 (!TI->hasOneUse() || !FI->hasOneUse()))
161 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
162 // TODO: The one-use restrictions for a scalar select could be eased if
163 // the fold of a select in visitLoadInst() was enhanced to match a pattern
164 // that includes a cast.
168 // Fold this by inserting a select from the input values.
170 Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
171 FI->getOperand(0), SI.getName() + ".v", &SI);
172 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
176 // Only handle binary operators with one-use here. As with the cast case
177 // above, it may be possible to relax the one-use constraint, but that needs
178 // be examined carefully since it may not reduce the total number of
180 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
181 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
184 // Figure out if the operations have any operands in common.
185 Value *MatchOp, *OtherOpT, *OtherOpF;
187 if (TI->getOperand(0) == FI->getOperand(0)) {
188 MatchOp = TI->getOperand(0);
189 OtherOpT = TI->getOperand(1);
190 OtherOpF = FI->getOperand(1);
191 MatchIsOpZero = true;
192 } else if (TI->getOperand(1) == FI->getOperand(1)) {
193 MatchOp = TI->getOperand(1);
194 OtherOpT = TI->getOperand(0);
195 OtherOpF = FI->getOperand(0);
196 MatchIsOpZero = false;
197 } else if (!TI->isCommutative()) {
199 } else if (TI->getOperand(0) == FI->getOperand(1)) {
200 MatchOp = TI->getOperand(0);
201 OtherOpT = TI->getOperand(1);
202 OtherOpF = FI->getOperand(0);
203 MatchIsOpZero = true;
204 } else if (TI->getOperand(1) == FI->getOperand(0)) {
205 MatchOp = TI->getOperand(1);
206 OtherOpT = TI->getOperand(0);
207 OtherOpF = FI->getOperand(1);
208 MatchIsOpZero = true;
213 // If we reach here, they do have operations in common.
214 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
215 SI.getName() + ".v", &SI);
216 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
217 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
218 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
221 static bool isSelect01(Constant *C1, Constant *C2) {
222 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
225 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
228 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
230 return C1I->isOne() || C1I->isAllOnesValue() ||
231 C2I->isOne() || C2I->isAllOnesValue();
234 /// Try to fold the select into one of the operands to allow further
236 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
238 // See the comment above GetSelectFoldableOperands for a description of the
239 // transformation we are doing here.
240 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
241 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
242 !isa<Constant>(FalseVal)) {
243 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
244 unsigned OpToFold = 0;
245 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
247 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
252 Constant *C = getSelectFoldableConstant(TVI);
253 Value *OOp = TVI->getOperand(2-OpToFold);
254 // Avoid creating select between 2 constants unless it's selecting
255 // between 0, 1 and -1.
256 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
257 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
258 NewSel->takeName(TVI);
259 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
260 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
262 BO->copyIRFlags(TVI_BO);
270 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
271 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
272 !isa<Constant>(TrueVal)) {
273 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
274 unsigned OpToFold = 0;
275 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
277 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
282 Constant *C = getSelectFoldableConstant(FVI);
283 Value *OOp = FVI->getOperand(2-OpToFold);
284 // Avoid creating select between 2 constants unless it's selecting
285 // between 0, 1 and -1.
286 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
287 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
288 NewSel->takeName(FVI);
289 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
290 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
292 BO->copyIRFlags(FVI_BO);
304 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
306 /// (or (shl (and X, C1), C3), Y)
308 /// C1 and C2 are both powers of 2
310 /// C3 = Log(C2) - Log(C1)
312 /// This transform handles cases where:
313 /// 1. The icmp predicate is inverted
314 /// 2. The select operands are reversed
315 /// 3. The magnitude of C2 and C1 are flipped
316 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
318 InstCombiner::BuilderTy *Builder) {
319 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
320 if (!IC || !SI.getType()->isIntegerTy())
323 Value *CmpLHS = IC->getOperand(0);
324 Value *CmpRHS = IC->getOperand(1);
329 bool NeedAnd = false;
330 if (IC->isEquality()) {
331 if (!match(CmpRHS, m_Zero()))
335 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
339 C1Log = C1->logBase2();
340 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
341 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
342 IC->getPredicate() == ICmpInst::ICMP_SGT) {
343 // We also need to recognize (icmp slt (trunc (X)), 0) and
344 // (icmp sgt (trunc (X)), -1).
345 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
346 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
347 (!IsEqualZero && !match(CmpRHS, m_Zero())))
350 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
353 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
360 bool OrOnTrueVal = false;
361 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
363 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
365 if (!OrOnFalseVal && !OrOnTrueVal)
368 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
370 unsigned C2Log = C2->logBase2();
372 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
373 bool NeedShift = C1Log != C2Log;
374 bool NeedZExtTrunc = Y->getType()->getIntegerBitWidth() !=
375 V->getType()->getIntegerBitWidth();
377 // Make sure we don't create more instructions than we save.
378 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
379 if ((NeedShift + NeedXor + NeedZExtTrunc) >
380 (IC->hasOneUse() + Or->hasOneUse()))
384 // Insert the AND instruction on the input to the truncate.
385 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
386 V = Builder->CreateAnd(V, ConstantInt::get(V->getType(), C1));
390 V = Builder->CreateZExtOrTrunc(V, Y->getType());
391 V = Builder->CreateShl(V, C2Log - C1Log);
392 } else if (C1Log > C2Log) {
393 V = Builder->CreateLShr(V, C1Log - C2Log);
394 V = Builder->CreateZExtOrTrunc(V, Y->getType());
396 V = Builder->CreateZExtOrTrunc(V, Y->getType());
399 V = Builder->CreateXor(V, *C2);
401 return Builder->CreateOr(V, Y);
404 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
405 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
407 /// For example, we can fold the following code sequence:
409 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
410 /// %1 = icmp ne i32 %x, 0
411 /// %2 = select i1 %1, i32 %0, i32 32
415 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
416 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
417 InstCombiner::BuilderTy *Builder) {
418 ICmpInst::Predicate Pred = ICI->getPredicate();
419 Value *CmpLHS = ICI->getOperand(0);
420 Value *CmpRHS = ICI->getOperand(1);
422 // Check if the condition value compares a value for equality against zero.
423 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
426 Value *Count = FalseVal;
427 Value *ValueOnZero = TrueVal;
428 if (Pred == ICmpInst::ICMP_NE)
429 std::swap(Count, ValueOnZero);
431 // Skip zero extend/truncate.
433 if (match(Count, m_ZExt(m_Value(V))) ||
434 match(Count, m_Trunc(m_Value(V))))
437 // Check if the value propagated on zero is a constant number equal to the
438 // sizeof in bits of 'Count'.
439 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
440 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
443 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
444 // input to the cttz/ctlz is used as LHS for the compare instruction.
445 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
446 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
447 IntrinsicInst *II = cast<IntrinsicInst>(Count);
448 // Explicitly clear the 'undef_on_zero' flag.
449 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
450 Type *Ty = NewI->getArgOperand(1)->getType();
451 NewI->setArgOperand(1, Constant::getNullValue(Ty));
452 Builder->Insert(NewI);
453 return Builder->CreateZExtOrTrunc(NewI, ValueOnZero->getType());
459 /// Return true if we find and adjust an icmp+select pattern where the compare
460 /// is with a constant that can be incremented or decremented to match the
461 /// minimum or maximum idiom.
462 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
463 ICmpInst::Predicate Pred = Cmp.getPredicate();
464 Value *CmpLHS = Cmp.getOperand(0);
465 Value *CmpRHS = Cmp.getOperand(1);
466 Value *TrueVal = Sel.getTrueValue();
467 Value *FalseVal = Sel.getFalseValue();
469 // We may move or edit the compare, so make sure the select is the only user.
471 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
474 // These transforms only work for selects of integers or vector selects of
476 Type *SelTy = Sel.getType();
477 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
478 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
481 Constant *AdjustedRHS;
482 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
483 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
484 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
485 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
489 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
490 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
491 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
492 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
493 ; // Nothing to do here. Values match without any sign/zero extension.
495 // Types do not match. Instead of calculating this with mixed types, promote
496 // all to the larger type. This enables scalar evolution to analyze this
498 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
499 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
501 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
502 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
503 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
504 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
505 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
507 AdjustedRHS = SextRHS;
508 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
509 SextRHS == TrueVal) {
511 AdjustedRHS = SextRHS;
512 } else if (Cmp.isUnsigned()) {
513 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
514 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
515 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
516 // zext + signed compare cannot be changed:
517 // 0xff <s 0x00, but 0x00ff >s 0x0000
518 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
520 AdjustedRHS = ZextRHS;
521 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
522 ZextRHS == TrueVal) {
524 AdjustedRHS = ZextRHS;
535 Pred = ICmpInst::getSwappedPredicate(Pred);
536 CmpRHS = AdjustedRHS;
537 std::swap(FalseVal, TrueVal);
538 Cmp.setPredicate(Pred);
539 Cmp.setOperand(0, CmpLHS);
540 Cmp.setOperand(1, CmpRHS);
541 Sel.setOperand(1, TrueVal);
542 Sel.setOperand(2, FalseVal);
543 Sel.swapProfMetadata();
545 // Move the compare instruction right before the select instruction. Otherwise
546 // the sext/zext value may be defined after the compare instruction uses it.
547 Cmp.moveBefore(&Sel);
552 /// If this is an integer min/max (icmp + select) with a constant operand,
553 /// create the canonical icmp for the min/max operation and canonicalize the
554 /// constant to the 'false' operand of the select:
555 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
556 /// Note: if C1 != C2, this will change the icmp constant to the existing
557 /// constant operand of the select.
559 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
560 InstCombiner::BuilderTy &Builder) {
561 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
564 // Canonicalize the compare predicate based on whether we have min or max.
566 ICmpInst::Predicate NewPred;
567 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
568 switch (SPR.Flavor) {
569 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
570 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
571 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
572 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
573 default: return nullptr;
576 // Is this already canonical?
577 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
578 Cmp.getPredicate() == NewPred)
581 // Create the canonical compare and plug it into the select.
582 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
584 // If the select operands did not change, we're done.
585 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
588 // If we are swapping the select operands, swap the metadata too.
589 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
590 "Unexpected results from matchSelectPattern");
591 Sel.setTrueValue(LHS);
592 Sel.setFalseValue(RHS);
593 Sel.swapProfMetadata();
597 /// Visit a SelectInst that has an ICmpInst as its first operand.
598 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
600 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *Builder))
603 bool Changed = adjustMinMax(SI, *ICI);
605 ICmpInst::Predicate Pred = ICI->getPredicate();
606 Value *CmpLHS = ICI->getOperand(0);
607 Value *CmpRHS = ICI->getOperand(1);
608 Value *TrueVal = SI.getTrueValue();
609 Value *FalseVal = SI.getFalseValue();
611 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
612 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
613 // FIXME: Type and constness constraints could be lifted, but we have to
614 // watch code size carefully. We should consider xor instead of
615 // sub/add when we decide to do that.
616 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
617 if (TrueVal->getType() == Ty) {
618 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
619 ConstantInt *C1 = nullptr, *C2 = nullptr;
620 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
621 C1 = dyn_cast<ConstantInt>(TrueVal);
622 C2 = dyn_cast<ConstantInt>(FalseVal);
623 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
624 C1 = dyn_cast<ConstantInt>(FalseVal);
625 C2 = dyn_cast<ConstantInt>(TrueVal);
628 // This shift results in either -1 or 0.
629 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
631 // Check if we can express the operation with a single or.
632 if (C2->isAllOnesValue())
633 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
635 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
636 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
642 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
644 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
645 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
646 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
647 SI.setOperand(1, CmpRHS);
649 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
650 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
651 SI.setOperand(2, CmpRHS);
656 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
657 // decomposeBitTestICmp() might help.
660 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
661 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
665 bool IsBitTest = false;
666 if (ICmpInst::isEquality(Pred) &&
667 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
668 match(CmpRHS, m_Zero())) {
670 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
671 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
675 TrueWhenUnset = false;
676 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
680 TrueWhenUnset = true;
684 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
685 if (TrueWhenUnset && TrueVal == X &&
686 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
687 V = Builder->CreateAnd(X, ~(*Y));
688 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
689 else if (!TrueWhenUnset && FalseVal == X &&
690 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
691 V = Builder->CreateAnd(X, ~(*Y));
692 // (X & Y) == 0 ? X ^ Y : X --> X | Y
693 else if (TrueWhenUnset && FalseVal == X &&
694 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
695 V = Builder->CreateOr(X, *Y);
696 // (X & Y) != 0 ? X : X ^ Y --> X | Y
697 else if (!TrueWhenUnset && TrueVal == X &&
698 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
699 V = Builder->CreateOr(X, *Y);
702 return replaceInstUsesWith(SI, V);
706 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
707 return replaceInstUsesWith(SI, V);
709 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
710 return replaceInstUsesWith(SI, V);
712 return Changed ? &SI : nullptr;
716 /// SI is a select whose condition is a PHI node (but the two may be in
717 /// different blocks). See if the true/false values (V) are live in all of the
718 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
720 /// X = phi [ C1, BB1], [C2, BB2]
722 /// Z = select X, Y, 0
724 /// because Y is not live in BB1/BB2.
726 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
727 const SelectInst &SI) {
728 // If the value is a non-instruction value like a constant or argument, it
729 // can always be mapped.
730 const Instruction *I = dyn_cast<Instruction>(V);
733 // If V is a PHI node defined in the same block as the condition PHI, we can
734 // map the arguments.
735 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
737 if (const PHINode *VP = dyn_cast<PHINode>(I))
738 if (VP->getParent() == CondPHI->getParent())
741 // Otherwise, if the PHI and select are defined in the same block and if V is
742 // defined in a different block, then we can transform it.
743 if (SI.getParent() == CondPHI->getParent() &&
744 I->getParent() != CondPHI->getParent())
747 // Otherwise we have a 'hard' case and we can't tell without doing more
748 // detailed dominator based analysis, punt.
752 /// We have an SPF (e.g. a min or max) of an SPF of the form:
753 /// SPF2(SPF1(A, B), C)
754 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
755 SelectPatternFlavor SPF1,
758 SelectPatternFlavor SPF2, Value *C) {
759 if (Outer.getType() != Inner->getType())
762 if (C == A || C == B) {
763 // MAX(MAX(A, B), B) -> MAX(A, B)
764 // MIN(MIN(a, b), a) -> MIN(a, b)
766 return replaceInstUsesWith(Outer, Inner);
768 // MAX(MIN(a, b), a) -> a
769 // MIN(MAX(a, b), a) -> a
770 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
771 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
772 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
773 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
774 return replaceInstUsesWith(Outer, C);
778 const APInt *CB, *CC;
779 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
780 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
781 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
782 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
783 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
784 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
785 (SPF1 == SPF_SMAX && CB->sge(*CC)))
786 return replaceInstUsesWith(Outer, Inner);
788 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
789 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
790 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
791 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
792 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
793 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
794 Outer.replaceUsesOfWith(Inner, A);
800 // ABS(ABS(X)) -> ABS(X)
801 // NABS(NABS(X)) -> NABS(X)
802 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
803 return replaceInstUsesWith(Outer, Inner);
806 // ABS(NABS(X)) -> ABS(X)
807 // NABS(ABS(X)) -> NABS(X)
808 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
809 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
810 SelectInst *SI = cast<SelectInst>(Inner);
812 Builder->CreateSelect(SI->getCondition(), SI->getFalseValue(),
813 SI->getTrueValue(), SI->getName(), SI);
814 return replaceInstUsesWith(Outer, NewSI);
817 auto IsFreeOrProfitableToInvert =
818 [&](Value *V, Value *&NotV, bool &ElidesXor) {
819 if (match(V, m_Not(m_Value(NotV)))) {
820 // If V has at most 2 uses then we can get rid of the xor operation
822 ElidesXor |= !V->hasNUsesOrMore(3);
826 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
834 Value *NotA, *NotB, *NotC;
835 bool ElidesXor = false;
837 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
838 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
839 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
840 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
842 // This transform is performance neutral if we can elide at least one xor from
843 // the set of three operands, since we'll be tacking on an xor at the very
845 if (SelectPatternResult::isMinOrMax(SPF1) &&
846 SelectPatternResult::isMinOrMax(SPF2) &&
847 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
848 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
849 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
851 NotA = Builder->CreateNot(A);
853 NotB = Builder->CreateNot(B);
855 NotC = Builder->CreateNot(C);
857 Value *NewInner = generateMinMaxSelectPattern(
858 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
859 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
860 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
861 return replaceInstUsesWith(Outer, NewOuter);
867 /// If one of the constants is zero (we know they can't both be) and we have an
868 /// icmp instruction with zero, and we have an 'and' with the non-constant value
869 /// and a power of two we can turn the select into a shift on the result of the
871 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
872 ConstantInt *FalseVal,
873 InstCombiner::BuilderTy *Builder) {
874 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
875 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
878 if (!match(IC->getOperand(1), m_Zero()))
882 Value *LHS = IC->getOperand(0);
883 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
886 // If both select arms are non-zero see if we have a select of the form
887 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
888 // for 'x ? 2^n : 0' and fix the thing up at the end.
889 ConstantInt *Offset = nullptr;
890 if (!TrueVal->isZero() && !FalseVal->isZero()) {
891 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
893 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
898 // Adjust TrueVal and FalseVal to the offset.
899 TrueVal = ConstantInt::get(Builder->getContext(),
900 TrueVal->getValue() - Offset->getValue());
901 FalseVal = ConstantInt::get(Builder->getContext(),
902 FalseVal->getValue() - Offset->getValue());
905 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
906 if (!AndRHS->getValue().isPowerOf2() ||
907 (!TrueVal->getValue().isPowerOf2() &&
908 !FalseVal->getValue().isPowerOf2()))
911 // Determine which shift is needed to transform result of the 'and' into the
913 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
914 unsigned ValZeros = ValC->getValue().logBase2();
915 unsigned AndZeros = AndRHS->getValue().logBase2();
917 // If types don't match we can still convert the select by introducing a zext
918 // or a trunc of the 'and'. The trunc case requires that all of the truncated
919 // bits are zero, we can figure that out by looking at the 'and' mask.
920 if (AndZeros >= ValC->getBitWidth())
923 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
924 if (ValZeros > AndZeros)
925 V = Builder->CreateShl(V, ValZeros - AndZeros);
926 else if (ValZeros < AndZeros)
927 V = Builder->CreateLShr(V, AndZeros - ValZeros);
929 // Okay, now we know that everything is set up, we just don't know whether we
930 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
931 bool ShouldNotVal = !TrueVal->isZero();
932 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
934 V = Builder->CreateXor(V, ValC);
936 // Apply an offset if needed.
938 V = Builder->CreateAdd(V, Offset);
942 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
943 /// This is even legal for FP.
944 static Instruction *foldAddSubSelect(SelectInst &SI,
945 InstCombiner::BuilderTy &Builder) {
946 Value *CondVal = SI.getCondition();
947 Value *TrueVal = SI.getTrueValue();
948 Value *FalseVal = SI.getFalseValue();
949 auto *TI = dyn_cast<Instruction>(TrueVal);
950 auto *FI = dyn_cast<Instruction>(FalseVal);
951 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
954 Instruction *AddOp = nullptr, *SubOp = nullptr;
955 if ((TI->getOpcode() == Instruction::Sub &&
956 FI->getOpcode() == Instruction::Add) ||
957 (TI->getOpcode() == Instruction::FSub &&
958 FI->getOpcode() == Instruction::FAdd)) {
961 } else if ((FI->getOpcode() == Instruction::Sub &&
962 TI->getOpcode() == Instruction::Add) ||
963 (FI->getOpcode() == Instruction::FSub &&
964 TI->getOpcode() == Instruction::FAdd)) {
970 Value *OtherAddOp = nullptr;
971 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
972 OtherAddOp = AddOp->getOperand(1);
973 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
974 OtherAddOp = AddOp->getOperand(0);
978 // So at this point we know we have (Y -> OtherAddOp):
979 // select C, (add X, Y), (sub X, Z)
980 Value *NegVal; // Compute -Z
981 if (SI.getType()->isFPOrFPVectorTy()) {
982 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
983 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
984 FastMathFlags Flags = AddOp->getFastMathFlags();
985 Flags &= SubOp->getFastMathFlags();
986 NegInst->setFastMathFlags(Flags);
989 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
992 Value *NewTrueOp = OtherAddOp;
993 Value *NewFalseOp = NegVal;
995 std::swap(NewTrueOp, NewFalseOp);
996 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
997 SI.getName() + ".p", &SI);
999 if (SI.getType()->isFPOrFPVectorTy()) {
1001 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1003 FastMathFlags Flags = AddOp->getFastMathFlags();
1004 Flags &= SubOp->getFastMathFlags();
1005 RI->setFastMathFlags(Flags);
1008 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1014 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1015 Instruction *ExtInst;
1016 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1017 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1020 auto ExtOpcode = ExtInst->getOpcode();
1021 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1024 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1025 Value *X = ExtInst->getOperand(0);
1026 Type *SmallType = X->getType();
1027 if (!SmallType->getScalarType()->isIntegerTy(1))
1031 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1032 !match(Sel.getFalseValue(), m_Constant(C)))
1035 // If the constant is the same after truncation to the smaller type and
1036 // extension to the original type, we can narrow the select.
1037 Value *Cond = Sel.getCondition();
1038 Type *SelType = Sel.getType();
1039 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1040 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1042 Value *TruncCVal = cast<Value>(TruncC);
1043 if (ExtInst == Sel.getFalseValue())
1044 std::swap(X, TruncCVal);
1046 // select Cond, (ext X), C --> ext(select Cond, X, C')
1047 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1048 Value *NewSel = Builder->CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1049 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1052 // If one arm of the select is the extend of the condition, replace that arm
1053 // with the extension of the appropriate known bool value.
1055 if (ExtInst == Sel.getTrueValue()) {
1056 // select X, (sext X), C --> select X, -1, C
1057 // select X, (zext X), C --> select X, 1, C
1058 Constant *One = ConstantInt::getTrue(SmallType);
1059 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1060 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1062 // select X, C, (sext X) --> select X, C, 0
1063 // select X, C, (zext X) --> select X, C, 0
1064 Constant *Zero = ConstantInt::getNullValue(SelType);
1065 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1072 /// Try to transform a vector select with a constant condition vector into a
1073 /// shuffle for easier combining with other shuffles and insert/extract.
1074 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1075 Value *CondVal = SI.getCondition();
1077 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1080 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1081 SmallVector<Constant *, 16> Mask;
1082 Mask.reserve(NumElts);
1083 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1084 for (unsigned i = 0; i != NumElts; ++i) {
1085 Constant *Elt = CondC->getAggregateElement(i);
1089 if (Elt->isOneValue()) {
1090 // If the select condition element is true, choose from the 1st vector.
1091 Mask.push_back(ConstantInt::get(Int32Ty, i));
1092 } else if (Elt->isNullValue()) {
1093 // If the select condition element is false, choose from the 2nd vector.
1094 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1095 } else if (isa<UndefValue>(Elt)) {
1096 // Undef in a select condition (choose one of the operands) does not mean
1097 // the same thing as undef in a shuffle mask (any value is acceptable), so
1101 // Bail out on a constant expression.
1106 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1107 ConstantVector::get(Mask));
1110 /// Reuse bitcasted operands between a compare and select:
1111 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1112 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1113 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1114 InstCombiner::BuilderTy &Builder) {
1115 Value *Cond = Sel.getCondition();
1116 Value *TVal = Sel.getTrueValue();
1117 Value *FVal = Sel.getFalseValue();
1119 CmpInst::Predicate Pred;
1121 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1124 // The select condition is a compare instruction. If the select's true/false
1125 // values are already the same as the compare operands, there's nothing to do.
1126 if (TVal == A || TVal == B || FVal == A || FVal == B)
1130 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1133 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1135 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1136 !match(FVal, m_BitCast(m_Value(FSrc))))
1139 // If the select true/false values are *different bitcasts* of the same source
1140 // operands, make the select operands the same as the compare operands and
1141 // cast the result. This is the canonical select form for min/max.
1143 if (TSrc == C && FSrc == D) {
1144 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1145 // bitcast (select (cmp A, B), A, B)
1146 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1147 } else if (TSrc == D && FSrc == C) {
1148 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1149 // bitcast (select (cmp A, B), B, A)
1150 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1154 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1157 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1158 Value *CondVal = SI.getCondition();
1159 Value *TrueVal = SI.getTrueValue();
1160 Value *FalseVal = SI.getFalseValue();
1161 Type *SelType = SI.getType();
1163 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1164 SQ.getWithInstruction(&SI)))
1165 return replaceInstUsesWith(SI, V);
1167 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1170 if (SelType->getScalarType()->isIntegerTy(1) &&
1171 TrueVal->getType() == CondVal->getType()) {
1172 if (match(TrueVal, m_One())) {
1173 // Change: A = select B, true, C --> A = or B, C
1174 return BinaryOperator::CreateOr(CondVal, FalseVal);
1176 if (match(TrueVal, m_Zero())) {
1177 // Change: A = select B, false, C --> A = and !B, C
1178 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1179 return BinaryOperator::CreateAnd(NotCond, FalseVal);
1181 if (match(FalseVal, m_Zero())) {
1182 // Change: A = select B, C, false --> A = and B, C
1183 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1185 if (match(FalseVal, m_One())) {
1186 // Change: A = select B, C, true --> A = or !B, C
1187 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1188 return BinaryOperator::CreateOr(NotCond, TrueVal);
1191 // select a, a, b -> a | b
1192 // select a, b, a -> a & b
1193 if (CondVal == TrueVal)
1194 return BinaryOperator::CreateOr(CondVal, FalseVal);
1195 if (CondVal == FalseVal)
1196 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1198 // select a, ~a, b -> (~a) & b
1199 // select a, b, ~a -> (~a) | b
1200 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1201 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1202 if (match(FalseVal, m_Not(m_Specific(CondVal))))
1203 return BinaryOperator::CreateOr(TrueVal, FalseVal);
1206 // Selecting between two integer or vector splat integer constants?
1208 // Note that we don't handle a scalar select of vectors:
1209 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1210 // because that may need 3 instructions to splat the condition value:
1211 // extend, insertelement, shufflevector.
1212 if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1213 // select C, 1, 0 -> zext C to int
1214 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1215 return new ZExtInst(CondVal, SelType);
1217 // select C, -1, 0 -> sext C to int
1218 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1219 return new SExtInst(CondVal, SelType);
1221 // select C, 0, 1 -> zext !C to int
1222 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1223 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1224 return new ZExtInst(NotCond, SelType);
1227 // select C, 0, -1 -> sext !C to int
1228 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1229 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1230 return new SExtInst(NotCond, SelType);
1234 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
1235 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
1236 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
1237 return replaceInstUsesWith(SI, V);
1239 // See if we are selecting two values based on a comparison of the two values.
1240 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1241 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1242 // Transform (X == Y) ? X : Y -> Y
1243 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1244 // This is not safe in general for floating point:
1245 // consider X== -0, Y== +0.
1246 // It becomes safe if either operand is a nonzero constant.
1247 ConstantFP *CFPt, *CFPf;
1248 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1249 !CFPt->getValueAPF().isZero()) ||
1250 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1251 !CFPf->getValueAPF().isZero()))
1252 return replaceInstUsesWith(SI, FalseVal);
1254 // Transform (X une Y) ? X : Y -> X
1255 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1256 // This is not safe in general for floating point:
1257 // consider X== -0, Y== +0.
1258 // It becomes safe if either operand is a nonzero constant.
1259 ConstantFP *CFPt, *CFPf;
1260 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1261 !CFPt->getValueAPF().isZero()) ||
1262 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1263 !CFPf->getValueAPF().isZero()))
1264 return replaceInstUsesWith(SI, TrueVal);
1267 // Canonicalize to use ordered comparisons by swapping the select
1271 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1272 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1273 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1274 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1275 Builder->setFastMathFlags(FCI->getFastMathFlags());
1276 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1277 FCI->getName() + ".inv");
1279 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1280 SI.getName() + ".p");
1283 // NOTE: if we wanted to, this is where to detect MIN/MAX
1284 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1285 // Transform (X == Y) ? Y : X -> X
1286 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1287 // This is not safe in general for floating point:
1288 // consider X== -0, Y== +0.
1289 // It becomes safe if either operand is a nonzero constant.
1290 ConstantFP *CFPt, *CFPf;
1291 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1292 !CFPt->getValueAPF().isZero()) ||
1293 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1294 !CFPf->getValueAPF().isZero()))
1295 return replaceInstUsesWith(SI, FalseVal);
1297 // Transform (X une Y) ? Y : X -> Y
1298 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1299 // This is not safe in general for floating point:
1300 // consider X== -0, Y== +0.
1301 // It becomes safe if either operand is a nonzero constant.
1302 ConstantFP *CFPt, *CFPf;
1303 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1304 !CFPt->getValueAPF().isZero()) ||
1305 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1306 !CFPf->getValueAPF().isZero()))
1307 return replaceInstUsesWith(SI, TrueVal);
1310 // Canonicalize to use ordered comparisons by swapping the select
1314 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1315 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1316 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1317 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1318 Builder->setFastMathFlags(FCI->getFastMathFlags());
1319 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1320 FCI->getName() + ".inv");
1322 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1323 SI.getName() + ".p");
1326 // NOTE: if we wanted to, this is where to detect MIN/MAX
1328 // NOTE: if we wanted to, this is where to detect ABS
1331 // See if we are selecting two values based on a comparison of the two values.
1332 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1333 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1336 if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1339 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1340 auto *TI = dyn_cast<Instruction>(TrueVal);
1341 auto *FI = dyn_cast<Instruction>(FalseVal);
1342 if (TI && FI && TI->getOpcode() == FI->getOpcode())
1343 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1346 if (Instruction *I = foldSelectExtConst(SI))
1349 // See if we can fold the select into one of our operands.
1350 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1351 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1354 Value *LHS, *RHS, *LHS2, *RHS2;
1355 Instruction::CastOps CastOp;
1356 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1357 auto SPF = SPR.Flavor;
1359 if (SelectPatternResult::isMinOrMax(SPF)) {
1360 // Canonicalize so that type casts are outside select patterns.
1361 if (LHS->getType()->getPrimitiveSizeInBits() !=
1362 SelType->getPrimitiveSizeInBits()) {
1363 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1366 if (CmpInst::isIntPredicate(Pred)) {
1367 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1369 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1370 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1371 Builder->setFastMathFlags(FMF);
1372 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1375 Value *NewSI = Builder->CreateCast(
1376 CastOp, Builder->CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI),
1378 return replaceInstUsesWith(SI, NewSI);
1383 // MAX(MAX(a, b), a) -> MAX(a, b)
1384 // MIN(MIN(a, b), a) -> MIN(a, b)
1385 // MAX(MIN(a, b), a) -> a
1386 // MIN(MAX(a, b), a) -> a
1387 // ABS(ABS(a)) -> ABS(a)
1388 // NABS(NABS(a)) -> NABS(a)
1389 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1390 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1393 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1394 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1399 // MAX(~a, ~b) -> ~MIN(a, b)
1400 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1401 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1402 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1403 // For this transform to be profitable, we need to eliminate at least two
1404 // 'not' instructions if we're going to add one 'not' instruction.
1406 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1407 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
1408 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1410 if (NumberOfNots >= 2) {
1411 Value *NewLHS = Builder->CreateNot(LHS);
1412 Value *NewRHS = Builder->CreateNot(RHS);
1413 Value *NewCmp = SPF == SPF_SMAX
1414 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1415 : Builder->CreateICmpULT(NewLHS, NewRHS);
1417 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1418 return replaceInstUsesWith(SI, NewSI);
1423 // ABS(-X) -> ABS(X)
1426 // See if we can fold the select into a phi node if the condition is a select.
1427 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1428 // The true/false values have to be live in the PHI predecessor's blocks.
1429 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1430 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1431 if (Instruction *NV = foldOpIntoPhi(SI, PN))
1434 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1435 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1436 // select(C, select(C, a, b), c) -> select(C, a, c)
1437 if (TrueSI->getCondition() == CondVal) {
1438 if (SI.getTrueValue() == TrueSI->getTrueValue())
1440 SI.setOperand(1, TrueSI->getTrueValue());
1443 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1444 // We choose this as normal form to enable folding on the And and shortening
1445 // paths for the values (this helps GetUnderlyingObjects() for example).
1446 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1447 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1448 SI.setOperand(0, And);
1449 SI.setOperand(1, TrueSI->getTrueValue());
1454 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1455 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1456 // select(C, a, select(C, b, c)) -> select(C, a, c)
1457 if (FalseSI->getCondition() == CondVal) {
1458 if (SI.getFalseValue() == FalseSI->getFalseValue())
1460 SI.setOperand(2, FalseSI->getFalseValue());
1463 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1464 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1465 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1466 SI.setOperand(0, Or);
1467 SI.setOperand(2, FalseSI->getFalseValue());
1473 if (BinaryOperator::isNot(CondVal)) {
1474 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1475 SI.setOperand(1, FalseVal);
1476 SI.setOperand(2, TrueVal);
1480 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1481 unsigned VWidth = VecTy->getNumElements();
1482 APInt UndefElts(VWidth, 0);
1483 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1484 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1486 return replaceInstUsesWith(SI, V);
1490 if (isa<ConstantAggregateZero>(CondVal)) {
1491 return replaceInstUsesWith(SI, FalseVal);
1495 // See if we can determine the result of this select based on a dominating
1497 BasicBlock *Parent = SI.getParent();
1498 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1499 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1500 if (PBI && PBI->isConditional() &&
1501 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1502 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1503 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1504 Optional<bool> Implication = isImpliedCondition(
1505 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1507 Value *V = *Implication ? TrueVal : FalseVal;
1508 return replaceInstUsesWith(SI, V);
1513 // If we can compute the condition, there's no need for a select.
1514 // Like the above fold, we are attempting to reduce compile-time cost by
1515 // putting this fold here with limitations rather than in InstSimplify.
1516 // The motivation for this call into value tracking is to take advantage of
1517 // the assumption cache, so make sure that is populated.
1518 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1520 computeKnownBits(CondVal, Known, 0, &SI);
1521 if (Known.One.isOneValue())
1522 return replaceInstUsesWith(SI, TrueVal);
1523 if (Known.Zero.isOneValue())
1524 return replaceInstUsesWith(SI, FalseVal);
1527 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, *Builder))