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/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
24 static SelectPatternFlavor
25 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
28 llvm_unreachable("unhandled!");
41 static CmpInst::Predicate getICmpPredicateForMinMax(SelectPatternFlavor SPF) {
44 llvm_unreachable("unhandled!");
47 return ICmpInst::ICMP_SLT;
49 return ICmpInst::ICMP_ULT;
51 return ICmpInst::ICMP_SGT;
53 return ICmpInst::ICMP_UGT;
57 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
58 SelectPatternFlavor SPF, Value *A,
60 CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
61 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
64 /// GetSelectFoldableOperands - We want to turn code that looks like this:
66 /// %D = select %cond, %C, %A
68 /// %C = select %cond, %B, 0
71 /// Assuming that the specified instruction is an operand to the select, return
72 /// a bitmask indicating which operands of this instruction are foldable if they
73 /// equal the other incoming value of the select.
75 static unsigned GetSelectFoldableOperands(Instruction *I) {
76 switch (I->getOpcode()) {
77 case Instruction::Add:
78 case Instruction::Mul:
79 case Instruction::And:
81 case Instruction::Xor:
82 return 3; // Can fold through either operand.
83 case Instruction::Sub: // Can only fold on the amount subtracted.
84 case Instruction::Shl: // Can only fold on the shift amount.
85 case Instruction::LShr:
86 case Instruction::AShr:
89 return 0; // Cannot fold
93 /// GetSelectFoldableConstant - For the same transformation as the previous
94 /// function, return the identity constant that goes into the select.
95 static Constant *GetSelectFoldableConstant(Instruction *I) {
96 switch (I->getOpcode()) {
97 default: llvm_unreachable("This cannot happen!");
98 case Instruction::Add:
99 case Instruction::Sub:
100 case Instruction::Or:
101 case Instruction::Xor:
102 case Instruction::Shl:
103 case Instruction::LShr:
104 case Instruction::AShr:
105 return Constant::getNullValue(I->getType());
106 case Instruction::And:
107 return Constant::getAllOnesValue(I->getType());
108 case Instruction::Mul:
109 return ConstantInt::get(I->getType(), 1);
113 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
114 /// have the same opcode and only one use each. Try to simplify this.
115 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
117 if (TI->getNumOperands() == 1) {
118 // If this is a non-volatile load or a cast from the same type,
121 Type *FIOpndTy = FI->getOperand(0)->getType();
122 if (TI->getOperand(0)->getType() != FIOpndTy)
124 // The select condition may be a vector. We may only change the operand
125 // type if the vector width remains the same (and matches the condition).
126 Type *CondTy = SI.getCondition()->getType();
127 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
128 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
131 return nullptr; // unknown unary op.
134 // Fold this by inserting a select from the input values.
135 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
136 FI->getOperand(0), SI.getName()+".v");
137 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
141 // Only handle binary operators here.
142 if (!isa<BinaryOperator>(TI))
145 // Figure out if the operations have any operands in common.
146 Value *MatchOp, *OtherOpT, *OtherOpF;
148 if (TI->getOperand(0) == FI->getOperand(0)) {
149 MatchOp = TI->getOperand(0);
150 OtherOpT = TI->getOperand(1);
151 OtherOpF = FI->getOperand(1);
152 MatchIsOpZero = true;
153 } else if (TI->getOperand(1) == FI->getOperand(1)) {
154 MatchOp = TI->getOperand(1);
155 OtherOpT = TI->getOperand(0);
156 OtherOpF = FI->getOperand(0);
157 MatchIsOpZero = false;
158 } else if (!TI->isCommutative()) {
160 } else if (TI->getOperand(0) == FI->getOperand(1)) {
161 MatchOp = TI->getOperand(0);
162 OtherOpT = TI->getOperand(1);
163 OtherOpF = FI->getOperand(0);
164 MatchIsOpZero = true;
165 } else if (TI->getOperand(1) == FI->getOperand(0)) {
166 MatchOp = TI->getOperand(1);
167 OtherOpT = TI->getOperand(0);
168 OtherOpF = FI->getOperand(1);
169 MatchIsOpZero = true;
174 // If we reach here, they do have operations in common.
175 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
176 OtherOpF, SI.getName()+".v");
178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
180 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
182 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
184 llvm_unreachable("Shouldn't get here");
187 static bool isSelect01(Constant *C1, Constant *C2) {
188 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
191 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
194 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
196 return C1I->isOne() || C1I->isAllOnesValue() ||
197 C2I->isOne() || C2I->isAllOnesValue();
200 /// FoldSelectIntoOp - Try fold the select into one of the operands to
201 /// facilitate further optimization.
202 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
204 // See the comment above GetSelectFoldableOperands for a description of the
205 // transformation we are doing here.
206 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
207 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
208 !isa<Constant>(FalseVal)) {
209 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
210 unsigned OpToFold = 0;
211 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
213 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
218 Constant *C = GetSelectFoldableConstant(TVI);
219 Value *OOp = TVI->getOperand(2-OpToFold);
220 // Avoid creating select between 2 constants unless it's selecting
221 // between 0, 1 and -1.
222 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
223 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
224 NewSel->takeName(TVI);
225 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
226 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
228 if (isa<PossiblyExactOperator>(BO))
229 BO->setIsExact(TVI_BO->isExact());
230 if (isa<OverflowingBinaryOperator>(BO)) {
231 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
232 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
241 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
242 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
243 !isa<Constant>(TrueVal)) {
244 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
245 unsigned OpToFold = 0;
246 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
248 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
253 Constant *C = GetSelectFoldableConstant(FVI);
254 Value *OOp = FVI->getOperand(2-OpToFold);
255 // Avoid creating select between 2 constants unless it's selecting
256 // between 0, 1 and -1.
257 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
258 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
259 NewSel->takeName(FVI);
260 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
261 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
263 if (isa<PossiblyExactOperator>(BO))
264 BO->setIsExact(FVI_BO->isExact());
265 if (isa<OverflowingBinaryOperator>(BO)) {
266 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
267 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
279 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
280 /// replaced with RepOp.
281 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
282 const TargetLibraryInfo *TLI,
283 const DataLayout &DL, DominatorTree *DT,
284 AssumptionCache *AC) {
285 // Trivial replacement.
289 Instruction *I = dyn_cast<Instruction>(V);
293 // If this is a binary operator, try to simplify it with the replaced op.
294 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
296 // %cmp = icmp eq i32 %x, 2147483647
297 // %add = add nsw i32 %x, 1
298 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
300 // We can't replace %sel with %add unless we strip away the flags.
301 if (isa<OverflowingBinaryOperator>(B))
302 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
304 if (isa<PossiblyExactOperator>(B))
308 if (B->getOperand(0) == Op)
309 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), DL, TLI);
310 if (B->getOperand(1) == Op)
311 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, DL, TLI);
314 // Same for CmpInsts.
315 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
316 if (C->getOperand(0) == Op)
317 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), DL,
319 if (C->getOperand(1) == Op)
320 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, DL,
324 // TODO: We could hand off more cases to instsimplify here.
326 // If all operands are constant after substituting Op for RepOp then we can
327 // constant fold the instruction.
328 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
329 // Build a list of all constant operands.
330 SmallVector<Constant*, 8> ConstOps;
331 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
332 if (I->getOperand(i) == Op)
333 ConstOps.push_back(CRepOp);
334 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
335 ConstOps.push_back(COp);
340 // All operands were constants, fold it.
341 if (ConstOps.size() == I->getNumOperands()) {
342 if (CmpInst *C = dyn_cast<CmpInst>(I))
343 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
344 ConstOps[1], DL, TLI);
346 if (LoadInst *LI = dyn_cast<LoadInst>(I))
347 if (!LI->isVolatile())
348 return ConstantFoldLoadFromConstPtr(ConstOps[0], DL);
350 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
358 /// foldSelectICmpAndOr - We want to turn:
359 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
361 /// (or (shl (and X, C1), C3), y)
363 /// C1 and C2 are both powers of 2
365 /// C3 = Log(C2) - Log(C1)
367 /// This transform handles cases where:
368 /// 1. The icmp predicate is inverted
369 /// 2. The select operands are reversed
370 /// 3. The magnitude of C2 and C1 are flipped
371 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
373 InstCombiner::BuilderTy *Builder) {
374 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
375 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
378 Value *CmpLHS = IC->getOperand(0);
379 Value *CmpRHS = IC->getOperand(1);
381 if (!match(CmpRHS, m_Zero()))
386 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
390 bool OrOnTrueVal = false;
391 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
393 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
395 if (!OrOnFalseVal && !OrOnTrueVal)
399 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
401 unsigned C1Log = C1->logBase2();
402 unsigned C2Log = C2->logBase2();
404 V = Builder->CreateZExtOrTrunc(V, Y->getType());
405 V = Builder->CreateShl(V, C2Log - C1Log);
406 } else if (C1Log > C2Log) {
407 V = Builder->CreateLShr(V, C1Log - C2Log);
408 V = Builder->CreateZExtOrTrunc(V, Y->getType());
410 V = Builder->CreateZExtOrTrunc(V, Y->getType());
412 ICmpInst::Predicate Pred = IC->getPredicate();
413 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
414 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
415 V = Builder->CreateXor(V, *C2);
417 return Builder->CreateOr(V, Y);
420 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
421 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
423 /// For example, we can fold the following code sequence:
425 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
426 /// %1 = icmp ne i32 %x, 0
427 /// %2 = select i1 %1, i32 %0, i32 32
431 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
432 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
433 InstCombiner::BuilderTy *Builder) {
434 ICmpInst::Predicate Pred = ICI->getPredicate();
435 Value *CmpLHS = ICI->getOperand(0);
436 Value *CmpRHS = ICI->getOperand(1);
438 // Check if the condition value compares a value for equality against zero.
439 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
442 Value *Count = FalseVal;
443 Value *ValueOnZero = TrueVal;
444 if (Pred == ICmpInst::ICMP_NE)
445 std::swap(Count, ValueOnZero);
447 // Skip zero extend/truncate.
449 if (match(Count, m_ZExt(m_Value(V))) ||
450 match(Count, m_Trunc(m_Value(V))))
453 // Check if the value propagated on zero is a constant number equal to the
454 // sizeof in bits of 'Count'.
455 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
456 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
459 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
460 // input to the cttz/ctlz is used as LHS for the compare instruction.
461 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
462 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
463 IntrinsicInst *II = cast<IntrinsicInst>(Count);
464 IRBuilder<> Builder(II);
465 // Explicitly clear the 'undef_on_zero' flag.
466 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
467 Type *Ty = NewI->getArgOperand(1)->getType();
468 NewI->setArgOperand(1, Constant::getNullValue(Ty));
469 Builder.Insert(NewI);
470 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
476 /// visitSelectInstWithICmp - Visit a SelectInst that has an
477 /// ICmpInst as its first operand.
479 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
481 bool Changed = false;
482 ICmpInst::Predicate Pred = ICI->getPredicate();
483 Value *CmpLHS = ICI->getOperand(0);
484 Value *CmpRHS = ICI->getOperand(1);
485 Value *TrueVal = SI.getTrueValue();
486 Value *FalseVal = SI.getFalseValue();
488 // Check cases where the comparison is with a constant that
489 // can be adjusted to fit the min/max idiom. We may move or edit ICI
490 // here, so make sure the select is the only user.
491 if (ICI->hasOneUse())
492 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
493 // X < MIN ? T : F --> F
494 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
495 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
496 return ReplaceInstUsesWith(SI, FalseVal);
497 // X > MAX ? T : F --> F
498 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
499 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
500 return ReplaceInstUsesWith(SI, FalseVal);
503 case ICmpInst::ICMP_ULT:
504 case ICmpInst::ICMP_SLT:
505 case ICmpInst::ICMP_UGT:
506 case ICmpInst::ICMP_SGT: {
507 // These transformations only work for selects over integers.
508 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
512 Constant *AdjustedRHS;
513 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
514 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
515 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
516 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
518 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
519 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
520 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
521 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
522 ; // Nothing to do here. Values match without any sign/zero extension.
524 // Types do not match. Instead of calculating this with mixed types
525 // promote all to the larger type. This enables scalar evolution to
526 // analyze this expression.
527 else if (CmpRHS->getType()->getScalarSizeInBits()
528 < SelectTy->getBitWidth()) {
529 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
531 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
532 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
533 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
534 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
535 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
536 sextRHS == FalseVal) {
538 AdjustedRHS = sextRHS;
539 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
540 sextRHS == TrueVal) {
542 AdjustedRHS = sextRHS;
543 } else if (ICI->isUnsigned()) {
544 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
545 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
546 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
547 // zext + signed compare cannot be changed:
548 // 0xff <s 0x00, but 0x00ff >s 0x0000
549 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
550 zextRHS == FalseVal) {
552 AdjustedRHS = zextRHS;
553 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
554 zextRHS == TrueVal) {
556 AdjustedRHS = zextRHS;
564 Pred = ICmpInst::getSwappedPredicate(Pred);
565 CmpRHS = AdjustedRHS;
566 std::swap(FalseVal, TrueVal);
567 ICI->setPredicate(Pred);
568 ICI->setOperand(0, CmpLHS);
569 ICI->setOperand(1, CmpRHS);
570 SI.setOperand(1, TrueVal);
571 SI.setOperand(2, FalseVal);
573 // Move ICI instruction right before the select instruction. Otherwise
574 // the sext/zext value may be defined after the ICI instruction uses it.
575 ICI->moveBefore(&SI);
583 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
584 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
585 // FIXME: Type and constness constraints could be lifted, but we have to
586 // watch code size carefully. We should consider xor instead of
587 // sub/add when we decide to do that.
588 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
589 if (TrueVal->getType() == Ty) {
590 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
591 ConstantInt *C1 = nullptr, *C2 = nullptr;
592 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
593 C1 = dyn_cast<ConstantInt>(TrueVal);
594 C2 = dyn_cast<ConstantInt>(FalseVal);
595 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
596 C1 = dyn_cast<ConstantInt>(FalseVal);
597 C2 = dyn_cast<ConstantInt>(TrueVal);
600 // This shift results in either -1 or 0.
601 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
603 // Check if we can express the operation with a single or.
604 if (C2->isAllOnesValue())
605 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
607 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
608 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
614 // If we have an equality comparison then we know the value in one of the
615 // arms of the select. See if substituting this value into the arm and
616 // simplifying the result yields the same value as the other arm.
617 if (Pred == ICmpInst::ICMP_EQ) {
618 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
620 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
622 return ReplaceInstUsesWith(SI, FalseVal);
623 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
625 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
627 return ReplaceInstUsesWith(SI, FalseVal);
628 } else if (Pred == ICmpInst::ICMP_NE) {
629 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
631 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
633 return ReplaceInstUsesWith(SI, TrueVal);
634 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
636 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
638 return ReplaceInstUsesWith(SI, TrueVal);
641 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
643 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
644 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
645 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
646 SI.setOperand(1, CmpRHS);
648 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
649 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
650 SI.setOperand(2, CmpRHS);
655 if (unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits()) {
656 APInt MinSignedValue = APInt::getSignBit(BitWidth);
660 bool IsBitTest = false;
661 if (ICmpInst::isEquality(Pred) &&
662 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
663 match(CmpRHS, m_Zero())) {
665 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
666 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
670 TrueWhenUnset = false;
671 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
675 TrueWhenUnset = true;
679 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
680 if (TrueWhenUnset && TrueVal == X &&
681 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
682 V = Builder->CreateAnd(X, ~(*Y));
683 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
684 else if (!TrueWhenUnset && FalseVal == X &&
685 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
686 V = Builder->CreateAnd(X, ~(*Y));
687 // (X & Y) == 0 ? X ^ Y : X --> X | Y
688 else if (TrueWhenUnset && FalseVal == X &&
689 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
690 V = Builder->CreateOr(X, *Y);
691 // (X & Y) != 0 ? X : X ^ Y --> X | Y
692 else if (!TrueWhenUnset && TrueVal == X &&
693 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
694 V = Builder->CreateOr(X, *Y);
697 return ReplaceInstUsesWith(SI, V);
701 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
702 return ReplaceInstUsesWith(SI, V);
704 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
705 return ReplaceInstUsesWith(SI, V);
707 return Changed ? &SI : nullptr;
711 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
712 /// PHI node (but the two may be in different blocks). See if the true/false
713 /// values (V) are live in all of the predecessor blocks of the PHI. For
714 /// example, cases like this cannot be mapped:
716 /// X = phi [ C1, BB1], [C2, BB2]
718 /// Z = select X, Y, 0
720 /// because Y is not live in BB1/BB2.
722 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
723 const SelectInst &SI) {
724 // If the value is a non-instruction value like a constant or argument, it
725 // can always be mapped.
726 const Instruction *I = dyn_cast<Instruction>(V);
729 // If V is a PHI node defined in the same block as the condition PHI, we can
730 // map the arguments.
731 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
733 if (const PHINode *VP = dyn_cast<PHINode>(I))
734 if (VP->getParent() == CondPHI->getParent())
737 // Otherwise, if the PHI and select are defined in the same block and if V is
738 // defined in a different block, then we can transform it.
739 if (SI.getParent() == CondPHI->getParent() &&
740 I->getParent() != CondPHI->getParent())
743 // Otherwise we have a 'hard' case and we can't tell without doing more
744 // detailed dominator based analysis, punt.
748 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
749 /// SPF2(SPF1(A, B), C)
750 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
751 SelectPatternFlavor SPF1,
754 SelectPatternFlavor SPF2, Value *C) {
755 if (C == A || C == B) {
756 // MAX(MAX(A, B), B) -> MAX(A, B)
757 // MIN(MIN(a, b), a) -> MIN(a, b)
759 return ReplaceInstUsesWith(Outer, Inner);
761 // MAX(MIN(a, b), a) -> a
762 // MIN(MAX(a, b), a) -> a
763 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
764 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
765 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
766 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
767 return ReplaceInstUsesWith(Outer, C);
771 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
772 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
773 APInt ACB = CB->getValue();
774 APInt ACC = CC->getValue();
776 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
777 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
778 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
779 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
780 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
781 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
782 return ReplaceInstUsesWith(Outer, Inner);
784 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
785 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
786 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
787 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
788 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
789 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
790 Outer.replaceUsesOfWith(Inner, A);
797 // ABS(ABS(X)) -> ABS(X)
798 // NABS(NABS(X)) -> NABS(X)
799 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
800 return ReplaceInstUsesWith(Outer, Inner);
803 // ABS(NABS(X)) -> ABS(X)
804 // NABS(ABS(X)) -> NABS(X)
805 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
806 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
807 SelectInst *SI = cast<SelectInst>(Inner);
808 Value *NewSI = Builder->CreateSelect(
809 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
810 return ReplaceInstUsesWith(Outer, NewSI);
813 auto IsFreeOrProfitableToInvert =
814 [&](Value *V, Value *&NotV, bool &ElidesXor) {
815 if (match(V, m_Not(m_Value(NotV)))) {
816 // If V has at most 2 uses then we can get rid of the xor operation
818 ElidesXor |= !V->hasNUsesOrMore(3);
822 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
830 Value *NotA, *NotB, *NotC;
831 bool ElidesXor = false;
833 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
834 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
835 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
836 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
838 // This transform is performance neutral if we can elide at least one xor from
839 // the set of three operands, since we'll be tacking on an xor at the very
841 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
842 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
843 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
845 NotA = Builder->CreateNot(A);
847 NotB = Builder->CreateNot(B);
849 NotC = Builder->CreateNot(C);
851 Value *NewInner = generateMinMaxSelectPattern(
852 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
853 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
854 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
855 return ReplaceInstUsesWith(Outer, NewOuter);
861 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
862 /// both be) and we have an icmp instruction with zero, and we have an 'and'
863 /// with the non-constant value and a power of two we can turn the select
864 /// into a shift on the result of the 'and'.
865 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
866 ConstantInt *FalseVal,
867 InstCombiner::BuilderTy *Builder) {
868 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
869 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
872 if (!match(IC->getOperand(1), m_Zero()))
876 Value *LHS = IC->getOperand(0);
877 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
880 // If both select arms are non-zero see if we have a select of the form
881 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
882 // for 'x ? 2^n : 0' and fix the thing up at the end.
883 ConstantInt *Offset = nullptr;
884 if (!TrueVal->isZero() && !FalseVal->isZero()) {
885 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
887 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
892 // Adjust TrueVal and FalseVal to the offset.
893 TrueVal = ConstantInt::get(Builder->getContext(),
894 TrueVal->getValue() - Offset->getValue());
895 FalseVal = ConstantInt::get(Builder->getContext(),
896 FalseVal->getValue() - Offset->getValue());
899 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
900 if (!AndRHS->getValue().isPowerOf2() ||
901 (!TrueVal->getValue().isPowerOf2() &&
902 !FalseVal->getValue().isPowerOf2()))
905 // Determine which shift is needed to transform result of the 'and' into the
907 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
908 unsigned ValZeros = ValC->getValue().logBase2();
909 unsigned AndZeros = AndRHS->getValue().logBase2();
911 // If types don't match we can still convert the select by introducing a zext
912 // or a trunc of the 'and'. The trunc case requires that all of the truncated
913 // bits are zero, we can figure that out by looking at the 'and' mask.
914 if (AndZeros >= ValC->getBitWidth())
917 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
918 if (ValZeros > AndZeros)
919 V = Builder->CreateShl(V, ValZeros - AndZeros);
920 else if (ValZeros < AndZeros)
921 V = Builder->CreateLShr(V, AndZeros - ValZeros);
923 // Okay, now we know that everything is set up, we just don't know whether we
924 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
925 bool ShouldNotVal = !TrueVal->isZero();
926 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
928 V = Builder->CreateXor(V, ValC);
930 // Apply an offset if needed.
932 V = Builder->CreateAdd(V, Offset);
936 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
937 Value *CondVal = SI.getCondition();
938 Value *TrueVal = SI.getTrueValue();
939 Value *FalseVal = SI.getFalseValue();
942 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
943 return ReplaceInstUsesWith(SI, V);
945 if (SI.getType()->isIntegerTy(1)) {
946 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
947 if (C->getZExtValue()) {
948 // Change: A = select B, true, C --> A = or B, C
949 return BinaryOperator::CreateOr(CondVal, FalseVal);
951 // Change: A = select B, false, C --> A = and !B, C
952 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
953 return BinaryOperator::CreateAnd(NotCond, FalseVal);
955 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
956 if (!C->getZExtValue()) {
957 // Change: A = select B, C, false --> A = and B, C
958 return BinaryOperator::CreateAnd(CondVal, TrueVal);
960 // Change: A = select B, C, true --> A = or !B, C
961 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
962 return BinaryOperator::CreateOr(NotCond, TrueVal);
965 // select a, b, a -> a&b
966 // select a, a, b -> a|b
967 if (CondVal == TrueVal)
968 return BinaryOperator::CreateOr(CondVal, FalseVal);
969 if (CondVal == FalseVal)
970 return BinaryOperator::CreateAnd(CondVal, TrueVal);
972 // select a, ~a, b -> (~a)&b
973 // select a, b, ~a -> (~a)|b
974 if (match(TrueVal, m_Not(m_Specific(CondVal))))
975 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
976 if (match(FalseVal, m_Not(m_Specific(CondVal))))
977 return BinaryOperator::CreateOr(TrueVal, FalseVal);
980 // Selecting between two integer constants?
981 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
982 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
983 // select C, 1, 0 -> zext C to int
984 if (FalseValC->isZero() && TrueValC->getValue() == 1)
985 return new ZExtInst(CondVal, SI.getType());
987 // select C, -1, 0 -> sext C to int
988 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
989 return new SExtInst(CondVal, SI.getType());
991 // select C, 0, 1 -> zext !C to int
992 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
993 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
994 return new ZExtInst(NotCond, SI.getType());
997 // select C, 0, -1 -> sext !C to int
998 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
999 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
1000 return new SExtInst(NotCond, SI.getType());
1003 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
1004 return ReplaceInstUsesWith(SI, V);
1007 // See if we are selecting two values based on a comparison of the two values.
1008 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1009 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1010 // Transform (X == Y) ? X : Y -> Y
1011 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1012 // This is not safe in general for floating point:
1013 // consider X== -0, Y== +0.
1014 // It becomes safe if either operand is a nonzero constant.
1015 ConstantFP *CFPt, *CFPf;
1016 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1017 !CFPt->getValueAPF().isZero()) ||
1018 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1019 !CFPf->getValueAPF().isZero()))
1020 return ReplaceInstUsesWith(SI, FalseVal);
1022 // Transform (X une Y) ? X : Y -> X
1023 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1024 // This is not safe in general for floating point:
1025 // consider X== -0, Y== +0.
1026 // It becomes safe if either operand is a nonzero constant.
1027 ConstantFP *CFPt, *CFPf;
1028 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1029 !CFPt->getValueAPF().isZero()) ||
1030 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1031 !CFPf->getValueAPF().isZero()))
1032 return ReplaceInstUsesWith(SI, TrueVal);
1035 // Canonicalize to use ordered comparisons by swapping the select
1039 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1040 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1041 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1042 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1043 FCI->getName() + ".inv");
1045 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1046 SI.getName() + ".p");
1049 // NOTE: if we wanted to, this is where to detect MIN/MAX
1050 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1051 // Transform (X == Y) ? Y : X -> X
1052 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1053 // This is not safe in general for floating point:
1054 // consider X== -0, Y== +0.
1055 // It becomes safe if either operand is a nonzero constant.
1056 ConstantFP *CFPt, *CFPf;
1057 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1058 !CFPt->getValueAPF().isZero()) ||
1059 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1060 !CFPf->getValueAPF().isZero()))
1061 return ReplaceInstUsesWith(SI, FalseVal);
1063 // Transform (X une Y) ? Y : X -> Y
1064 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1065 // This is not safe in general for floating point:
1066 // consider X== -0, Y== +0.
1067 // It becomes safe if either operand is a nonzero constant.
1068 ConstantFP *CFPt, *CFPf;
1069 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1070 !CFPt->getValueAPF().isZero()) ||
1071 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1072 !CFPf->getValueAPF().isZero()))
1073 return ReplaceInstUsesWith(SI, TrueVal);
1076 // Canonicalize to use ordered comparisons by swapping the select
1080 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1081 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1082 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1083 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1084 FCI->getName() + ".inv");
1086 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1087 SI.getName() + ".p");
1090 // NOTE: if we wanted to, this is where to detect MIN/MAX
1092 // NOTE: if we wanted to, this is where to detect ABS
1095 // See if we are selecting two values based on a comparison of the two values.
1096 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1097 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1100 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
1101 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
1102 if (TI->hasOneUse() && FI->hasOneUse()) {
1103 Instruction *AddOp = nullptr, *SubOp = nullptr;
1105 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1106 if (TI->getOpcode() == FI->getOpcode())
1107 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1110 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
1111 // even legal for FP.
1112 if ((TI->getOpcode() == Instruction::Sub &&
1113 FI->getOpcode() == Instruction::Add) ||
1114 (TI->getOpcode() == Instruction::FSub &&
1115 FI->getOpcode() == Instruction::FAdd)) {
1116 AddOp = FI; SubOp = TI;
1117 } else if ((FI->getOpcode() == Instruction::Sub &&
1118 TI->getOpcode() == Instruction::Add) ||
1119 (FI->getOpcode() == Instruction::FSub &&
1120 TI->getOpcode() == Instruction::FAdd)) {
1121 AddOp = TI; SubOp = FI;
1125 Value *OtherAddOp = nullptr;
1126 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1127 OtherAddOp = AddOp->getOperand(1);
1128 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1129 OtherAddOp = AddOp->getOperand(0);
1133 // So at this point we know we have (Y -> OtherAddOp):
1134 // select C, (add X, Y), (sub X, Z)
1135 Value *NegVal; // Compute -Z
1136 if (SI.getType()->isFPOrFPVectorTy()) {
1137 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
1138 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1139 FastMathFlags Flags = AddOp->getFastMathFlags();
1140 Flags &= SubOp->getFastMathFlags();
1141 NegInst->setFastMathFlags(Flags);
1144 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
1147 Value *NewTrueOp = OtherAddOp;
1148 Value *NewFalseOp = NegVal;
1150 std::swap(NewTrueOp, NewFalseOp);
1152 Builder->CreateSelect(CondVal, NewTrueOp,
1153 NewFalseOp, SI.getName() + ".p");
1155 if (SI.getType()->isFPOrFPVectorTy()) {
1157 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1159 FastMathFlags Flags = AddOp->getFastMathFlags();
1160 Flags &= SubOp->getFastMathFlags();
1161 RI->setFastMathFlags(Flags);
1164 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1169 // See if we can fold the select into one of our operands.
1170 if (SI.getType()->isIntOrIntVectorTy()) {
1171 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1174 Value *LHS, *RHS, *LHS2, *RHS2;
1175 Instruction::CastOps CastOp;
1176 SelectPatternFlavor SPF = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1179 // Canonicalize so that type casts are outside select patterns.
1180 if (LHS->getType()->getPrimitiveSizeInBits() !=
1181 SI.getType()->getPrimitiveSizeInBits()) {
1182 CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
1183 Value *Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1184 Value *NewSI = Builder->CreateCast(CastOp,
1185 Builder->CreateSelect(Cmp, LHS, RHS),
1187 return ReplaceInstUsesWith(SI, NewSI);
1190 // MAX(MAX(a, b), a) -> MAX(a, b)
1191 // MIN(MIN(a, b), a) -> MIN(a, b)
1192 // MAX(MIN(a, b), a) -> a
1193 // MIN(MAX(a, b), a) -> a
1194 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2))
1195 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1198 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2))
1199 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1204 // MAX(~a, ~b) -> ~MIN(a, b)
1205 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1206 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1207 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1209 // This transform adds a xor operation and that extra cost needs to be
1210 // justified. We look for simplifications that will result from
1211 // applying this rule:
1214 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1215 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1216 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1219 Value *NewLHS = Builder->CreateNot(LHS);
1220 Value *NewRHS = Builder->CreateNot(RHS);
1221 Value *NewCmp = SPF == SPF_SMAX
1222 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1223 : Builder->CreateICmpULT(NewLHS, NewRHS);
1225 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1226 return ReplaceInstUsesWith(SI, NewSI);
1232 // ABS(-X) -> ABS(X)
1235 // See if we can fold the select into a phi node if the condition is a select.
1236 if (isa<PHINode>(SI.getCondition()))
1237 // The true/false values have to be live in the PHI predecessor's blocks.
1238 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1239 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1240 if (Instruction *NV = FoldOpIntoPhi(SI))
1243 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1244 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1245 // select(C, select(C, a, b), c) -> select(C, a, c)
1246 if (TrueSI->getCondition() == CondVal) {
1247 if (SI.getTrueValue() == TrueSI->getTrueValue())
1249 SI.setOperand(1, TrueSI->getTrueValue());
1252 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1253 // We choose this as normal form to enable folding on the And and shortening
1254 // paths for the values (this helps GetUnderlyingObjects() for example).
1255 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1256 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1257 SI.setOperand(0, And);
1258 SI.setOperand(1, TrueSI->getTrueValue());
1263 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1264 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1265 // select(C, a, select(C, b, c)) -> select(C, a, c)
1266 if (FalseSI->getCondition() == CondVal) {
1267 if (SI.getFalseValue() == FalseSI->getFalseValue())
1269 SI.setOperand(2, FalseSI->getFalseValue());
1272 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1273 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1274 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1275 SI.setOperand(0, Or);
1276 SI.setOperand(2, FalseSI->getFalseValue());
1282 if (BinaryOperator::isNot(CondVal)) {
1283 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1284 SI.setOperand(1, FalseVal);
1285 SI.setOperand(2, TrueVal);
1289 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1290 unsigned VWidth = VecTy->getNumElements();
1291 APInt UndefElts(VWidth, 0);
1292 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1293 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1295 return ReplaceInstUsesWith(SI, V);
1299 if (isa<ConstantAggregateZero>(CondVal)) {
1300 return ReplaceInstUsesWith(SI, FalseVal);