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/ADT/APInt.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/CmpInstAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/KnownBits.h"
41 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
46 using namespace PatternMatch;
48 #define DEBUG_TYPE "instcombine"
50 static SelectPatternFlavor
51 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
54 llvm_unreachable("unhandled!");
67 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
71 llvm_unreachable("unhandled!");
74 return ICmpInst::ICMP_SLT;
76 return ICmpInst::ICMP_ULT;
78 return ICmpInst::ICMP_SGT;
80 return ICmpInst::ICMP_UGT;
82 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
84 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
88 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
89 SelectPatternFlavor SPF, Value *A,
91 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
92 assert(CmpInst::isIntPredicate(Pred));
93 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
96 /// If one of the constants is zero (we know they can't both be) and we have an
97 /// icmp instruction with zero, and we have an 'and' with the non-constant value
98 /// and a power of two we can turn the select into a shift on the result of the
101 /// select (icmp eq (and X, C1)), C2, C3
102 /// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
103 /// To something like:
104 /// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
106 /// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
107 /// With some variations depending if C3 is larger than C2, or the shift
108 /// isn't needed, or the bit widths don't match.
109 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
110 APInt TrueVal, APInt FalseVal,
111 InstCombiner::BuilderTy &Builder) {
112 assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
114 // If this is a vector select, we need a vector compare.
115 if (SelType->isVectorTy() != IC->getType()->isVectorTy())
120 bool CreateAnd = false;
121 ICmpInst::Predicate Pred = IC->getPredicate();
122 if (ICmpInst::isEquality(Pred)) {
123 if (!match(IC->getOperand(1), m_Zero()))
126 V = IC->getOperand(0);
129 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
133 } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
135 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
137 if (!AndMask.isPowerOf2())
145 // If both select arms are non-zero see if we have a select of the form
146 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
147 // for 'x ? 2^n : 0' and fix the thing up at the end.
148 APInt Offset(TrueVal.getBitWidth(), 0);
149 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
150 if ((TrueVal - FalseVal).isPowerOf2())
152 else if ((FalseVal - TrueVal).isPowerOf2())
157 // Adjust TrueVal and FalseVal to the offset.
162 // Make sure one of the select arms is a power of 2.
163 if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
166 // Determine which shift is needed to transform result of the 'and' into the
168 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
169 unsigned ValZeros = ValC.logBase2();
170 unsigned AndZeros = AndMask.logBase2();
173 // Insert the AND instruction on the input to the truncate.
174 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
177 // If types don't match we can still convert the select by introducing a zext
178 // or a trunc of the 'and'.
179 if (ValZeros > AndZeros) {
180 V = Builder.CreateZExtOrTrunc(V, SelType);
181 V = Builder.CreateShl(V, ValZeros - AndZeros);
182 } else if (ValZeros < AndZeros) {
183 V = Builder.CreateLShr(V, AndZeros - ValZeros);
184 V = Builder.CreateZExtOrTrunc(V, SelType);
186 V = Builder.CreateZExtOrTrunc(V, SelType);
188 // Okay, now we know that everything is set up, we just don't know whether we
189 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
190 bool ShouldNotVal = !TrueVal.isNullValue();
191 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
193 V = Builder.CreateXor(V, ValC);
195 // Apply an offset if needed.
196 if (!Offset.isNullValue())
197 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
201 /// We want to turn code that looks like this:
203 /// %D = select %cond, %C, %A
205 /// %C = select %cond, %B, 0
208 /// Assuming that the specified instruction is an operand to the select, return
209 /// a bitmask indicating which operands of this instruction are foldable if they
210 /// equal the other incoming value of the select.
211 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
212 switch (I->getOpcode()) {
213 case Instruction::Add:
214 case Instruction::Mul:
215 case Instruction::And:
216 case Instruction::Or:
217 case Instruction::Xor:
218 return 3; // Can fold through either operand.
219 case Instruction::Sub: // Can only fold on the amount subtracted.
220 case Instruction::Shl: // Can only fold on the shift amount.
221 case Instruction::LShr:
222 case Instruction::AShr:
225 return 0; // Cannot fold
229 /// For the same transformation as the previous function, return the identity
230 /// constant that goes into the select.
231 static APInt getSelectFoldableConstant(BinaryOperator *I) {
232 switch (I->getOpcode()) {
233 default: llvm_unreachable("This cannot happen!");
234 case Instruction::Add:
235 case Instruction::Sub:
236 case Instruction::Or:
237 case Instruction::Xor:
238 case Instruction::Shl:
239 case Instruction::LShr:
240 case Instruction::AShr:
241 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
242 case Instruction::And:
243 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
244 case Instruction::Mul:
245 return APInt(I->getType()->getScalarSizeInBits(), 1);
249 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
250 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
252 // Don't break up min/max patterns. The hasOneUse checks below prevent that
253 // for most cases, but vector min/max with bitcasts can be transformed. If the
254 // one-use restrictions are eased for other patterns, we still don't want to
255 // obfuscate min/max.
256 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
257 match(&SI, m_SMax(m_Value(), m_Value())) ||
258 match(&SI, m_UMin(m_Value(), m_Value())) ||
259 match(&SI, m_UMax(m_Value(), m_Value()))))
262 // If this is a cast from the same type, merge.
263 if (TI->getNumOperands() == 1 && TI->isCast()) {
264 Type *FIOpndTy = FI->getOperand(0)->getType();
265 if (TI->getOperand(0)->getType() != FIOpndTy)
268 // The select condition may be a vector. We may only change the operand
269 // type if the vector width remains the same (and matches the condition).
270 Type *CondTy = SI.getCondition()->getType();
271 if (CondTy->isVectorTy()) {
272 if (!FIOpndTy->isVectorTy())
274 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
277 // TODO: If the backend knew how to deal with casts better, we could
278 // remove this limitation. For now, there's too much potential to create
279 // worse codegen by promoting the select ahead of size-altering casts
282 // Note that ValueTracking's matchSelectPattern() looks through casts
283 // without checking 'hasOneUse' when it matches min/max patterns, so this
284 // transform may end up happening anyway.
285 if (TI->getOpcode() != Instruction::BitCast &&
286 (!TI->hasOneUse() || !FI->hasOneUse()))
288 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
289 // TODO: The one-use restrictions for a scalar select could be eased if
290 // the fold of a select in visitLoadInst() was enhanced to match a pattern
291 // that includes a cast.
295 // Fold this by inserting a select from the input values.
297 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
298 FI->getOperand(0), SI.getName() + ".v", &SI);
299 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
303 // Only handle binary operators with one-use here. As with the cast case
304 // above, it may be possible to relax the one-use constraint, but that needs
305 // be examined carefully since it may not reduce the total number of
307 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
308 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
311 // Figure out if the operations have any operands in common.
312 Value *MatchOp, *OtherOpT, *OtherOpF;
314 if (TI->getOperand(0) == FI->getOperand(0)) {
315 MatchOp = TI->getOperand(0);
316 OtherOpT = TI->getOperand(1);
317 OtherOpF = FI->getOperand(1);
318 MatchIsOpZero = true;
319 } else if (TI->getOperand(1) == FI->getOperand(1)) {
320 MatchOp = TI->getOperand(1);
321 OtherOpT = TI->getOperand(0);
322 OtherOpF = FI->getOperand(0);
323 MatchIsOpZero = false;
324 } else if (!TI->isCommutative()) {
326 } else if (TI->getOperand(0) == FI->getOperand(1)) {
327 MatchOp = TI->getOperand(0);
328 OtherOpT = TI->getOperand(1);
329 OtherOpF = FI->getOperand(0);
330 MatchIsOpZero = true;
331 } else if (TI->getOperand(1) == FI->getOperand(0)) {
332 MatchOp = TI->getOperand(1);
333 OtherOpT = TI->getOperand(0);
334 OtherOpF = FI->getOperand(1);
335 MatchIsOpZero = true;
340 // If we reach here, they do have operations in common.
341 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
342 SI.getName() + ".v", &SI);
343 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
344 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
345 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
348 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
349 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
351 return C1I.isOneValue() || C1I.isAllOnesValue() ||
352 C2I.isOneValue() || C2I.isAllOnesValue();
355 /// Try to fold the select into one of the operands to allow further
357 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
359 // See the comment above GetSelectFoldableOperands for a description of the
360 // transformation we are doing here.
361 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
362 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
363 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
364 unsigned OpToFold = 0;
365 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
367 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
372 APInt CI = getSelectFoldableConstant(TVI);
373 Value *OOp = TVI->getOperand(2-OpToFold);
374 // Avoid creating select between 2 constants unless it's selecting
375 // between 0, 1 and -1.
377 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
378 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
379 Value *C = ConstantInt::get(OOp->getType(), CI);
380 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
381 NewSel->takeName(TVI);
382 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
384 BO->copyIRFlags(TVI);
392 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
393 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
394 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
395 unsigned OpToFold = 0;
396 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
398 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
403 APInt CI = getSelectFoldableConstant(FVI);
404 Value *OOp = FVI->getOperand(2-OpToFold);
405 // Avoid creating select between 2 constants unless it's selecting
406 // between 0, 1 and -1.
408 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
409 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
410 Value *C = ConstantInt::get(OOp->getType(), CI);
411 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
412 NewSel->takeName(FVI);
413 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
415 BO->copyIRFlags(FVI);
427 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
429 /// (or (shl (and X, C1), C3), Y)
431 /// C1 and C2 are both powers of 2
433 /// C3 = Log(C2) - Log(C1)
435 /// This transform handles cases where:
436 /// 1. The icmp predicate is inverted
437 /// 2. The select operands are reversed
438 /// 3. The magnitude of C2 and C1 are flipped
439 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
441 InstCombiner::BuilderTy &Builder) {
442 // Only handle integer compares. Also, if this is a vector select, we need a
444 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
445 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
448 Value *CmpLHS = IC->getOperand(0);
449 Value *CmpRHS = IC->getOperand(1);
454 bool NeedAnd = false;
455 if (IC->isEquality()) {
456 if (!match(CmpRHS, m_Zero()))
460 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
464 C1Log = C1->logBase2();
465 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
466 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
467 IC->getPredicate() == ICmpInst::ICMP_SGT) {
468 // We also need to recognize (icmp slt (trunc (X)), 0) and
469 // (icmp sgt (trunc (X)), -1).
470 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
471 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
472 (!IsEqualZero && !match(CmpRHS, m_Zero())))
475 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
478 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
485 bool OrOnTrueVal = false;
486 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
488 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
490 if (!OrOnFalseVal && !OrOnTrueVal)
493 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
495 unsigned C2Log = C2->logBase2();
497 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
498 bool NeedShift = C1Log != C2Log;
499 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
500 V->getType()->getScalarSizeInBits();
502 // Make sure we don't create more instructions than we save.
503 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
504 if ((NeedShift + NeedXor + NeedZExtTrunc) >
505 (IC->hasOneUse() + Or->hasOneUse()))
509 // Insert the AND instruction on the input to the truncate.
510 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
511 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
515 V = Builder.CreateZExtOrTrunc(V, Y->getType());
516 V = Builder.CreateShl(V, C2Log - C1Log);
517 } else if (C1Log > C2Log) {
518 V = Builder.CreateLShr(V, C1Log - C2Log);
519 V = Builder.CreateZExtOrTrunc(V, Y->getType());
521 V = Builder.CreateZExtOrTrunc(V, Y->getType());
524 V = Builder.CreateXor(V, *C2);
526 return Builder.CreateOr(V, Y);
529 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
530 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
532 /// For example, we can fold the following code sequence:
534 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
535 /// %1 = icmp ne i32 %x, 0
536 /// %2 = select i1 %1, i32 %0, i32 32
540 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
541 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
542 InstCombiner::BuilderTy &Builder) {
543 ICmpInst::Predicate Pred = ICI->getPredicate();
544 Value *CmpLHS = ICI->getOperand(0);
545 Value *CmpRHS = ICI->getOperand(1);
547 // Check if the condition value compares a value for equality against zero.
548 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
551 Value *Count = FalseVal;
552 Value *ValueOnZero = TrueVal;
553 if (Pred == ICmpInst::ICMP_NE)
554 std::swap(Count, ValueOnZero);
556 // Skip zero extend/truncate.
558 if (match(Count, m_ZExt(m_Value(V))) ||
559 match(Count, m_Trunc(m_Value(V))))
562 // Check if the value propagated on zero is a constant number equal to the
563 // sizeof in bits of 'Count'.
564 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
565 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
568 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
569 // input to the cttz/ctlz is used as LHS for the compare instruction.
570 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
571 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
572 IntrinsicInst *II = cast<IntrinsicInst>(Count);
573 // Explicitly clear the 'undef_on_zero' flag.
574 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
575 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
576 Builder.Insert(NewI);
577 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
583 /// Return true if we find and adjust an icmp+select pattern where the compare
584 /// is with a constant that can be incremented or decremented to match the
585 /// minimum or maximum idiom.
586 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
587 ICmpInst::Predicate Pred = Cmp.getPredicate();
588 Value *CmpLHS = Cmp.getOperand(0);
589 Value *CmpRHS = Cmp.getOperand(1);
590 Value *TrueVal = Sel.getTrueValue();
591 Value *FalseVal = Sel.getFalseValue();
593 // We may move or edit the compare, so make sure the select is the only user.
595 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
598 // These transforms only work for selects of integers or vector selects of
600 Type *SelTy = Sel.getType();
601 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
602 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
605 Constant *AdjustedRHS;
606 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
607 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
608 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
609 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
613 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
614 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
615 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
616 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
617 ; // Nothing to do here. Values match without any sign/zero extension.
619 // Types do not match. Instead of calculating this with mixed types, promote
620 // all to the larger type. This enables scalar evolution to analyze this
622 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
623 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
625 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
626 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
627 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
628 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
629 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
631 AdjustedRHS = SextRHS;
632 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
633 SextRHS == TrueVal) {
635 AdjustedRHS = SextRHS;
636 } else if (Cmp.isUnsigned()) {
637 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
638 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
639 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
640 // zext + signed compare cannot be changed:
641 // 0xff <s 0x00, but 0x00ff >s 0x0000
642 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
644 AdjustedRHS = ZextRHS;
645 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
646 ZextRHS == TrueVal) {
648 AdjustedRHS = ZextRHS;
659 Pred = ICmpInst::getSwappedPredicate(Pred);
660 CmpRHS = AdjustedRHS;
661 std::swap(FalseVal, TrueVal);
662 Cmp.setPredicate(Pred);
663 Cmp.setOperand(0, CmpLHS);
664 Cmp.setOperand(1, CmpRHS);
665 Sel.setOperand(1, TrueVal);
666 Sel.setOperand(2, FalseVal);
667 Sel.swapProfMetadata();
669 // Move the compare instruction right before the select instruction. Otherwise
670 // the sext/zext value may be defined after the compare instruction uses it.
671 Cmp.moveBefore(&Sel);
676 /// If this is an integer min/max (icmp + select) with a constant operand,
677 /// create the canonical icmp for the min/max operation and canonicalize the
678 /// constant to the 'false' operand of the select:
679 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
680 /// Note: if C1 != C2, this will change the icmp constant to the existing
681 /// constant operand of the select.
683 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
684 InstCombiner::BuilderTy &Builder) {
685 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
688 // Canonicalize the compare predicate based on whether we have min or max.
690 ICmpInst::Predicate NewPred;
691 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
692 switch (SPR.Flavor) {
693 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
694 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
695 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
696 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
697 default: return nullptr;
700 // Is this already canonical?
701 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
702 Cmp.getPredicate() == NewPred)
705 // Create the canonical compare and plug it into the select.
706 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
708 // If the select operands did not change, we're done.
709 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
712 // If we are swapping the select operands, swap the metadata too.
713 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
714 "Unexpected results from matchSelectPattern");
715 Sel.setTrueValue(LHS);
716 Sel.setFalseValue(RHS);
717 Sel.swapProfMetadata();
721 /// Visit a SelectInst that has an ICmpInst as its first operand.
722 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
724 Value *TrueVal = SI.getTrueValue();
725 Value *FalseVal = SI.getFalseValue();
727 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
730 bool Changed = adjustMinMax(SI, *ICI);
732 ICmpInst::Predicate Pred = ICI->getPredicate();
733 Value *CmpLHS = ICI->getOperand(0);
734 Value *CmpRHS = ICI->getOperand(1);
736 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
737 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
738 // FIXME: Type and constness constraints could be lifted, but we have to
739 // watch code size carefully. We should consider xor instead of
740 // sub/add when we decide to do that.
741 // TODO: Merge this with foldSelectICmpAnd somehow.
742 if (CmpLHS->getType()->isIntOrIntVectorTy() &&
743 CmpLHS->getType() == TrueVal->getType()) {
744 const APInt *C1, *C2;
745 if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
746 ICmpInst::Predicate Pred = ICI->getPredicate();
749 if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
750 if (Mask.isSignMask()) {
751 assert(X == CmpLHS && "Expected to use the compare input directly");
752 assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
754 if (Pred == ICmpInst::ICMP_NE)
757 // This shift results in either -1 or 0.
758 Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
760 // Check if we can express the operation with a single or.
761 if (C2->isAllOnesValue())
762 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
764 Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
765 return replaceInstUsesWith(SI, Builder.CreateAdd(And,
766 ConstantInt::get(And->getType(), *C1)));
773 const APInt *TrueValC, *FalseValC;
774 if (match(TrueVal, m_APInt(TrueValC)) &&
775 match(FalseVal, m_APInt(FalseValC)))
776 if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
777 *FalseValC, Builder))
778 return replaceInstUsesWith(SI, V);
781 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
783 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
784 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
785 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
786 SI.setOperand(1, CmpRHS);
788 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
789 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
790 SI.setOperand(2, CmpRHS);
795 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
796 // decomposeBitTestICmp() might help.
799 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
800 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
804 bool IsBitTest = false;
805 if (ICmpInst::isEquality(Pred) &&
806 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
807 match(CmpRHS, m_Zero())) {
809 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
810 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
814 TrueWhenUnset = false;
815 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
819 TrueWhenUnset = true;
823 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
824 if (TrueWhenUnset && TrueVal == X &&
825 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
826 V = Builder.CreateAnd(X, ~(*Y));
827 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
828 else if (!TrueWhenUnset && FalseVal == X &&
829 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
830 V = Builder.CreateAnd(X, ~(*Y));
831 // (X & Y) == 0 ? X ^ Y : X --> X | Y
832 else if (TrueWhenUnset && FalseVal == X &&
833 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
834 V = Builder.CreateOr(X, *Y);
835 // (X & Y) != 0 ? X : X ^ Y --> X | Y
836 else if (!TrueWhenUnset && TrueVal == X &&
837 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
838 V = Builder.CreateOr(X, *Y);
841 return replaceInstUsesWith(SI, V);
845 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
846 return replaceInstUsesWith(SI, V);
848 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
849 return replaceInstUsesWith(SI, V);
851 return Changed ? &SI : nullptr;
855 /// SI is a select whose condition is a PHI node (but the two may be in
856 /// different blocks). See if the true/false values (V) are live in all of the
857 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
859 /// X = phi [ C1, BB1], [C2, BB2]
861 /// Z = select X, Y, 0
863 /// because Y is not live in BB1/BB2.
864 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
865 const SelectInst &SI) {
866 // If the value is a non-instruction value like a constant or argument, it
867 // can always be mapped.
868 const Instruction *I = dyn_cast<Instruction>(V);
871 // If V is a PHI node defined in the same block as the condition PHI, we can
872 // map the arguments.
873 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
875 if (const PHINode *VP = dyn_cast<PHINode>(I))
876 if (VP->getParent() == CondPHI->getParent())
879 // Otherwise, if the PHI and select are defined in the same block and if V is
880 // defined in a different block, then we can transform it.
881 if (SI.getParent() == CondPHI->getParent() &&
882 I->getParent() != CondPHI->getParent())
885 // Otherwise we have a 'hard' case and we can't tell without doing more
886 // detailed dominator based analysis, punt.
890 /// We have an SPF (e.g. a min or max) of an SPF of the form:
891 /// SPF2(SPF1(A, B), C)
892 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
893 SelectPatternFlavor SPF1,
896 SelectPatternFlavor SPF2, Value *C) {
897 if (Outer.getType() != Inner->getType())
900 if (C == A || C == B) {
901 // MAX(MAX(A, B), B) -> MAX(A, B)
902 // MIN(MIN(a, b), a) -> MIN(a, b)
904 return replaceInstUsesWith(Outer, Inner);
906 // MAX(MIN(a, b), a) -> a
907 // MIN(MAX(a, b), a) -> a
908 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
909 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
910 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
911 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
912 return replaceInstUsesWith(Outer, C);
916 const APInt *CB, *CC;
917 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
918 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
919 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
920 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
921 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
922 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
923 (SPF1 == SPF_SMAX && CB->sge(*CC)))
924 return replaceInstUsesWith(Outer, Inner);
926 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
927 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
928 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
929 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
930 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
931 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
932 Outer.replaceUsesOfWith(Inner, A);
938 // ABS(ABS(X)) -> ABS(X)
939 // NABS(NABS(X)) -> NABS(X)
940 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
941 return replaceInstUsesWith(Outer, Inner);
944 // ABS(NABS(X)) -> ABS(X)
945 // NABS(ABS(X)) -> NABS(X)
946 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
947 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
948 SelectInst *SI = cast<SelectInst>(Inner);
950 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
951 SI->getTrueValue(), SI->getName(), SI);
952 return replaceInstUsesWith(Outer, NewSI);
955 auto IsFreeOrProfitableToInvert =
956 [&](Value *V, Value *&NotV, bool &ElidesXor) {
957 if (match(V, m_Not(m_Value(NotV)))) {
958 // If V has at most 2 uses then we can get rid of the xor operation
960 ElidesXor |= !V->hasNUsesOrMore(3);
964 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
972 Value *NotA, *NotB, *NotC;
973 bool ElidesXor = false;
975 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
976 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
977 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
978 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
980 // This transform is performance neutral if we can elide at least one xor from
981 // the set of three operands, since we'll be tacking on an xor at the very
983 if (SelectPatternResult::isMinOrMax(SPF1) &&
984 SelectPatternResult::isMinOrMax(SPF2) &&
985 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
986 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
987 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
989 NotA = Builder.CreateNot(A);
991 NotB = Builder.CreateNot(B);
993 NotC = Builder.CreateNot(C);
995 Value *NewInner = generateMinMaxSelectPattern(
996 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
997 Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
998 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
999 return replaceInstUsesWith(Outer, NewOuter);
1005 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1006 /// This is even legal for FP.
1007 static Instruction *foldAddSubSelect(SelectInst &SI,
1008 InstCombiner::BuilderTy &Builder) {
1009 Value *CondVal = SI.getCondition();
1010 Value *TrueVal = SI.getTrueValue();
1011 Value *FalseVal = SI.getFalseValue();
1012 auto *TI = dyn_cast<Instruction>(TrueVal);
1013 auto *FI = dyn_cast<Instruction>(FalseVal);
1014 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1017 Instruction *AddOp = nullptr, *SubOp = nullptr;
1018 if ((TI->getOpcode() == Instruction::Sub &&
1019 FI->getOpcode() == Instruction::Add) ||
1020 (TI->getOpcode() == Instruction::FSub &&
1021 FI->getOpcode() == Instruction::FAdd)) {
1024 } else if ((FI->getOpcode() == Instruction::Sub &&
1025 TI->getOpcode() == Instruction::Add) ||
1026 (FI->getOpcode() == Instruction::FSub &&
1027 TI->getOpcode() == Instruction::FAdd)) {
1033 Value *OtherAddOp = nullptr;
1034 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1035 OtherAddOp = AddOp->getOperand(1);
1036 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1037 OtherAddOp = AddOp->getOperand(0);
1041 // So at this point we know we have (Y -> OtherAddOp):
1042 // select C, (add X, Y), (sub X, Z)
1043 Value *NegVal; // Compute -Z
1044 if (SI.getType()->isFPOrFPVectorTy()) {
1045 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1046 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1047 FastMathFlags Flags = AddOp->getFastMathFlags();
1048 Flags &= SubOp->getFastMathFlags();
1049 NegInst->setFastMathFlags(Flags);
1052 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1055 Value *NewTrueOp = OtherAddOp;
1056 Value *NewFalseOp = NegVal;
1058 std::swap(NewTrueOp, NewFalseOp);
1059 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1060 SI.getName() + ".p", &SI);
1062 if (SI.getType()->isFPOrFPVectorTy()) {
1064 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1066 FastMathFlags Flags = AddOp->getFastMathFlags();
1067 Flags &= SubOp->getFastMathFlags();
1068 RI->setFastMathFlags(Flags);
1071 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1077 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1078 Instruction *ExtInst;
1079 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1080 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1083 auto ExtOpcode = ExtInst->getOpcode();
1084 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1087 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1088 Value *X = ExtInst->getOperand(0);
1089 Type *SmallType = X->getType();
1090 if (!SmallType->isIntOrIntVectorTy(1))
1094 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1095 !match(Sel.getFalseValue(), m_Constant(C)))
1098 // If the constant is the same after truncation to the smaller type and
1099 // extension to the original type, we can narrow the select.
1100 Value *Cond = Sel.getCondition();
1101 Type *SelType = Sel.getType();
1102 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1103 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1105 Value *TruncCVal = cast<Value>(TruncC);
1106 if (ExtInst == Sel.getFalseValue())
1107 std::swap(X, TruncCVal);
1109 // select Cond, (ext X), C --> ext(select Cond, X, C')
1110 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1111 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1112 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1115 // If one arm of the select is the extend of the condition, replace that arm
1116 // with the extension of the appropriate known bool value.
1118 if (ExtInst == Sel.getTrueValue()) {
1119 // select X, (sext X), C --> select X, -1, C
1120 // select X, (zext X), C --> select X, 1, C
1121 Constant *One = ConstantInt::getTrue(SmallType);
1122 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1123 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1125 // select X, C, (sext X) --> select X, C, 0
1126 // select X, C, (zext X) --> select X, C, 0
1127 Constant *Zero = ConstantInt::getNullValue(SelType);
1128 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1135 /// Try to transform a vector select with a constant condition vector into a
1136 /// shuffle for easier combining with other shuffles and insert/extract.
1137 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1138 Value *CondVal = SI.getCondition();
1140 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1143 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1144 SmallVector<Constant *, 16> Mask;
1145 Mask.reserve(NumElts);
1146 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1147 for (unsigned i = 0; i != NumElts; ++i) {
1148 Constant *Elt = CondC->getAggregateElement(i);
1152 if (Elt->isOneValue()) {
1153 // If the select condition element is true, choose from the 1st vector.
1154 Mask.push_back(ConstantInt::get(Int32Ty, i));
1155 } else if (Elt->isNullValue()) {
1156 // If the select condition element is false, choose from the 2nd vector.
1157 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1158 } else if (isa<UndefValue>(Elt)) {
1159 // Undef in a select condition (choose one of the operands) does not mean
1160 // the same thing as undef in a shuffle mask (any value is acceptable), so
1164 // Bail out on a constant expression.
1169 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1170 ConstantVector::get(Mask));
1173 /// Reuse bitcasted operands between a compare and select:
1174 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1175 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1176 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1177 InstCombiner::BuilderTy &Builder) {
1178 Value *Cond = Sel.getCondition();
1179 Value *TVal = Sel.getTrueValue();
1180 Value *FVal = Sel.getFalseValue();
1182 CmpInst::Predicate Pred;
1184 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1187 // The select condition is a compare instruction. If the select's true/false
1188 // values are already the same as the compare operands, there's nothing to do.
1189 if (TVal == A || TVal == B || FVal == A || FVal == B)
1193 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1196 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1198 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1199 !match(FVal, m_BitCast(m_Value(FSrc))))
1202 // If the select true/false values are *different bitcasts* of the same source
1203 // operands, make the select operands the same as the compare operands and
1204 // cast the result. This is the canonical select form for min/max.
1206 if (TSrc == C && FSrc == D) {
1207 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1208 // bitcast (select (cmp A, B), A, B)
1209 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1210 } else if (TSrc == D && FSrc == C) {
1211 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1212 // bitcast (select (cmp A, B), B, A)
1213 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1217 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1220 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1223 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1224 /// selects between the returned value of the cmpxchg instruction its compare
1225 /// operand, the result of the select will always be equal to its false value.
1228 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1229 /// %1 = extractvalue { i64, i1 } %0, 1
1230 /// %2 = extractvalue { i64, i1 } %0, 0
1231 /// %3 = select i1 %1, i64 %compare, i64 %2
1234 /// The returned value of the cmpxchg instruction (%2) is the original value
1235 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1236 /// must have been equal to %compare. Thus, the result of the select is always
1237 /// equal to %2, and the code can be simplified to:
1239 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1240 /// %1 = extractvalue { i64, i1 } %0, 0
1243 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1244 // A helper that determines if V is an extractvalue instruction whose
1245 // aggregate operand is a cmpxchg instruction and whose single index is equal
1246 // to I. If such conditions are true, the helper returns the cmpxchg
1247 // instruction; otherwise, a nullptr is returned.
1248 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1249 auto *Extract = dyn_cast<ExtractValueInst>(V);
1252 if (Extract->getIndices()[0] != I)
1254 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1257 // If the select has a single user, and this user is a select instruction that
1258 // we can simplify, skip the cmpxchg simplification for now.
1260 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1261 if (Select->getCondition() == SI.getCondition())
1262 if (Select->getFalseValue() == SI.getTrueValue() ||
1263 Select->getTrueValue() == SI.getFalseValue())
1266 // Ensure the select condition is the returned flag of a cmpxchg instruction.
1267 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1271 // Check the true value case: The true value of the select is the returned
1272 // value of the same cmpxchg used by the condition, and the false value is the
1273 // cmpxchg instruction's compare operand.
1274 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1275 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1276 SI.setTrueValue(SI.getFalseValue());
1280 // Check the false value case: The false value of the select is the returned
1281 // value of the same cmpxchg used by the condition, and the true value is the
1282 // cmpxchg instruction's compare operand.
1283 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1284 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1285 SI.setTrueValue(SI.getFalseValue());
1292 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1293 Value *CondVal = SI.getCondition();
1294 Value *TrueVal = SI.getTrueValue();
1295 Value *FalseVal = SI.getFalseValue();
1296 Type *SelType = SI.getType();
1298 // FIXME: Remove this workaround when freeze related patches are done.
1299 // For select with undef operand which feeds into an equality comparison,
1300 // don't simplify it so loop unswitch can know the equality comparison
1301 // may have an undef operand. This is a workaround for PR31652 caused by
1302 // descrepancy about branch on undef between LoopUnswitch and GVN.
1303 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1304 if (llvm::any_of(SI.users(), [&](User *U) {
1305 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1306 if (CI && CI->isEquality())
1314 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1315 SQ.getWithInstruction(&SI)))
1316 return replaceInstUsesWith(SI, V);
1318 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1321 // Canonicalize a one-use integer compare with a non-canonical predicate by
1322 // inverting the predicate and swapping the select operands. This matches a
1323 // compare canonicalization for conditional branches.
1324 // TODO: Should we do the same for FP compares?
1325 CmpInst::Predicate Pred;
1326 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1327 !isCanonicalPredicate(Pred)) {
1328 // Swap true/false values and condition.
1329 CmpInst *Cond = cast<CmpInst>(CondVal);
1330 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1331 SI.setOperand(1, FalseVal);
1332 SI.setOperand(2, TrueVal);
1333 SI.swapProfMetadata();
1338 if (SelType->isIntOrIntVectorTy(1) &&
1339 TrueVal->getType() == CondVal->getType()) {
1340 if (match(TrueVal, m_One())) {
1341 // Change: A = select B, true, C --> A = or B, C
1342 return BinaryOperator::CreateOr(CondVal, FalseVal);
1344 if (match(TrueVal, m_Zero())) {
1345 // Change: A = select B, false, C --> A = and !B, C
1346 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1347 return BinaryOperator::CreateAnd(NotCond, FalseVal);
1349 if (match(FalseVal, m_Zero())) {
1350 // Change: A = select B, C, false --> A = and B, C
1351 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1353 if (match(FalseVal, m_One())) {
1354 // Change: A = select B, C, true --> A = or !B, C
1355 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1356 return BinaryOperator::CreateOr(NotCond, TrueVal);
1359 // select a, a, b -> a | b
1360 // select a, b, a -> a & b
1361 if (CondVal == TrueVal)
1362 return BinaryOperator::CreateOr(CondVal, FalseVal);
1363 if (CondVal == FalseVal)
1364 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1366 // select a, ~a, b -> (~a) & b
1367 // select a, b, ~a -> (~a) | b
1368 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1369 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1370 if (match(FalseVal, m_Not(m_Specific(CondVal))))
1371 return BinaryOperator::CreateOr(TrueVal, FalseVal);
1374 // Selecting between two integer or vector splat integer constants?
1376 // Note that we don't handle a scalar select of vectors:
1377 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1378 // because that may need 3 instructions to splat the condition value:
1379 // extend, insertelement, shufflevector.
1380 if (SelType->isIntOrIntVectorTy() &&
1381 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1382 // select C, 1, 0 -> zext C to int
1383 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1384 return new ZExtInst(CondVal, SelType);
1386 // select C, -1, 0 -> sext C to int
1387 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1388 return new SExtInst(CondVal, SelType);
1390 // select C, 0, 1 -> zext !C to int
1391 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1392 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1393 return new ZExtInst(NotCond, SelType);
1396 // select C, 0, -1 -> sext !C to int
1397 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1398 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1399 return new SExtInst(NotCond, SelType);
1403 // See if we are selecting two values based on a comparison of the two values.
1404 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1405 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1406 // Transform (X == Y) ? X : Y -> Y
1407 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1408 // This is not safe in general for floating point:
1409 // consider X== -0, Y== +0.
1410 // It becomes safe if either operand is a nonzero constant.
1411 ConstantFP *CFPt, *CFPf;
1412 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1413 !CFPt->getValueAPF().isZero()) ||
1414 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1415 !CFPf->getValueAPF().isZero()))
1416 return replaceInstUsesWith(SI, FalseVal);
1418 // Transform (X une Y) ? X : Y -> X
1419 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1420 // This is not safe in general for floating point:
1421 // consider X== -0, Y== +0.
1422 // It becomes safe if either operand is a nonzero constant.
1423 ConstantFP *CFPt, *CFPf;
1424 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1425 !CFPt->getValueAPF().isZero()) ||
1426 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1427 !CFPf->getValueAPF().isZero()))
1428 return replaceInstUsesWith(SI, TrueVal);
1431 // Canonicalize to use ordered comparisons by swapping the select
1435 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1436 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1437 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1438 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1439 Builder.setFastMathFlags(FCI->getFastMathFlags());
1440 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1441 FCI->getName() + ".inv");
1443 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1444 SI.getName() + ".p");
1447 // NOTE: if we wanted to, this is where to detect MIN/MAX
1448 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1449 // Transform (X == Y) ? Y : X -> X
1450 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1451 // This is not safe in general for floating point:
1452 // consider X== -0, Y== +0.
1453 // It becomes safe if either operand is a nonzero constant.
1454 ConstantFP *CFPt, *CFPf;
1455 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1456 !CFPt->getValueAPF().isZero()) ||
1457 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1458 !CFPf->getValueAPF().isZero()))
1459 return replaceInstUsesWith(SI, FalseVal);
1461 // Transform (X une Y) ? Y : X -> Y
1462 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1463 // This is not safe in general for floating point:
1464 // consider X== -0, Y== +0.
1465 // It becomes safe if either operand is a nonzero constant.
1466 ConstantFP *CFPt, *CFPf;
1467 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1468 !CFPt->getValueAPF().isZero()) ||
1469 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1470 !CFPf->getValueAPF().isZero()))
1471 return replaceInstUsesWith(SI, TrueVal);
1474 // Canonicalize to use ordered comparisons by swapping the select
1478 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1479 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1480 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1481 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1482 Builder.setFastMathFlags(FCI->getFastMathFlags());
1483 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1484 FCI->getName() + ".inv");
1486 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1487 SI.getName() + ".p");
1490 // NOTE: if we wanted to, this is where to detect MIN/MAX
1492 // NOTE: if we wanted to, this is where to detect ABS
1495 // See if we are selecting two values based on a comparison of the two values.
1496 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1497 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1500 if (Instruction *Add = foldAddSubSelect(SI, Builder))
1503 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1504 auto *TI = dyn_cast<Instruction>(TrueVal);
1505 auto *FI = dyn_cast<Instruction>(FalseVal);
1506 if (TI && FI && TI->getOpcode() == FI->getOpcode())
1507 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1510 if (Instruction *I = foldSelectExtConst(SI))
1513 // See if we can fold the select into one of our operands.
1514 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1515 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1518 Value *LHS, *RHS, *LHS2, *RHS2;
1519 Instruction::CastOps CastOp;
1520 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1521 auto SPF = SPR.Flavor;
1523 if (SelectPatternResult::isMinOrMax(SPF)) {
1524 // Canonicalize so that
1525 // - type casts are outside select patterns.
1526 // - float clamp is transformed to min/max pattern
1528 bool IsCastNeeded = LHS->getType() != SelType;
1529 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1530 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1532 (LHS->getType()->isFPOrFPVectorTy() &&
1533 ((CmpLHS != LHS && CmpLHS != RHS) ||
1534 (CmpRHS != LHS && CmpRHS != RHS)))) {
1535 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1538 if (CmpInst::isIntPredicate(Pred)) {
1539 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1541 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1542 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1543 Builder.setFastMathFlags(FMF);
1544 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1547 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1549 return replaceInstUsesWith(SI, NewSI);
1551 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1552 return replaceInstUsesWith(SI, NewCast);
1557 // MAX(MAX(a, b), a) -> MAX(a, b)
1558 // MIN(MIN(a, b), a) -> MIN(a, b)
1559 // MAX(MIN(a, b), a) -> a
1560 // MIN(MAX(a, b), a) -> a
1561 // ABS(ABS(a)) -> ABS(a)
1562 // NABS(NABS(a)) -> NABS(a)
1563 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1564 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1567 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1568 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1573 // MAX(~a, ~b) -> ~MIN(a, b)
1574 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1575 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1576 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1577 // For this transform to be profitable, we need to eliminate at least two
1578 // 'not' instructions if we're going to add one 'not' instruction.
1580 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1581 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
1582 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1584 if (NumberOfNots >= 2) {
1585 Value *NewLHS = Builder.CreateNot(LHS);
1586 Value *NewRHS = Builder.CreateNot(RHS);
1587 Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1588 : Builder.CreateICmpULT(NewLHS, NewRHS);
1590 Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
1591 return replaceInstUsesWith(SI, NewSI);
1596 // ABS(-X) -> ABS(X)
1599 // See if we can fold the select into a phi node if the condition is a select.
1600 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1601 // The true/false values have to be live in the PHI predecessor's blocks.
1602 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1603 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1604 if (Instruction *NV = foldOpIntoPhi(SI, PN))
1607 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1608 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1609 // select(C, select(C, a, b), c) -> select(C, a, c)
1610 if (TrueSI->getCondition() == CondVal) {
1611 if (SI.getTrueValue() == TrueSI->getTrueValue())
1613 SI.setOperand(1, TrueSI->getTrueValue());
1616 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1617 // We choose this as normal form to enable folding on the And and shortening
1618 // paths for the values (this helps GetUnderlyingObjects() for example).
1619 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1620 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1621 SI.setOperand(0, And);
1622 SI.setOperand(1, TrueSI->getTrueValue());
1627 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1628 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1629 // select(C, a, select(C, b, c)) -> select(C, a, c)
1630 if (FalseSI->getCondition() == CondVal) {
1631 if (SI.getFalseValue() == FalseSI->getFalseValue())
1633 SI.setOperand(2, FalseSI->getFalseValue());
1636 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1637 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1638 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1639 SI.setOperand(0, Or);
1640 SI.setOperand(2, FalseSI->getFalseValue());
1646 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1647 // The select might be preventing a division by 0.
1648 switch (BO->getOpcode()) {
1651 case Instruction::SRem:
1652 case Instruction::URem:
1653 case Instruction::SDiv:
1654 case Instruction::UDiv:
1659 // Try to simplify a binop sandwiched between 2 selects with the same
1661 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1662 BinaryOperator *TrueBO;
1663 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1664 canMergeSelectThroughBinop(TrueBO)) {
1665 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1666 if (TrueBOSI->getCondition() == CondVal) {
1667 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1668 Worklist.Add(TrueBO);
1672 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1673 if (TrueBOSI->getCondition() == CondVal) {
1674 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1675 Worklist.Add(TrueBO);
1681 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1682 BinaryOperator *FalseBO;
1683 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1684 canMergeSelectThroughBinop(FalseBO)) {
1685 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1686 if (FalseBOSI->getCondition() == CondVal) {
1687 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1688 Worklist.Add(FalseBO);
1692 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1693 if (FalseBOSI->getCondition() == CondVal) {
1694 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1695 Worklist.Add(FalseBO);
1701 if (BinaryOperator::isNot(CondVal)) {
1702 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1703 SI.setOperand(1, FalseVal);
1704 SI.setOperand(2, TrueVal);
1708 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1709 unsigned VWidth = VecTy->getNumElements();
1710 APInt UndefElts(VWidth, 0);
1711 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1712 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1714 return replaceInstUsesWith(SI, V);
1719 // See if we can determine the result of this select based on a dominating
1721 BasicBlock *Parent = SI.getParent();
1722 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1723 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1724 if (PBI && PBI->isConditional() &&
1725 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1726 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1727 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
1728 Optional<bool> Implication = isImpliedCondition(
1729 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
1731 Value *V = *Implication ? TrueVal : FalseVal;
1732 return replaceInstUsesWith(SI, V);
1737 // If we can compute the condition, there's no need for a select.
1738 // Like the above fold, we are attempting to reduce compile-time cost by
1739 // putting this fold here with limitations rather than in InstSimplify.
1740 // The motivation for this call into value tracking is to take advantage of
1741 // the assumption cache, so make sure that is populated.
1742 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1744 computeKnownBits(CondVal, Known, 0, &SI);
1745 if (Known.One.isOneValue())
1746 return replaceInstUsesWith(SI, TrueVal);
1747 if (Known.Zero.isOneValue())
1748 return replaceInstUsesWith(SI, FalseVal);
1751 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
1754 // Simplify selects that test the returned flag of cmpxchg instructions.
1755 if (Instruction *Select = foldSelectCmpXchg(SI))