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)) {
295 if (B->getOperand(0) == Op)
296 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), DL, TLI);
297 if (B->getOperand(1) == Op)
298 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, DL, TLI);
301 // Same for CmpInsts.
302 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
303 if (C->getOperand(0) == Op)
304 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), DL,
306 if (C->getOperand(1) == Op)
307 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, DL,
311 // TODO: We could hand off more cases to instsimplify here.
313 // If all operands are constant after substituting Op for RepOp then we can
314 // constant fold the instruction.
315 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
316 // Build a list of all constant operands.
317 SmallVector<Constant*, 8> ConstOps;
318 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
319 if (I->getOperand(i) == Op)
320 ConstOps.push_back(CRepOp);
321 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
322 ConstOps.push_back(COp);
327 // All operands were constants, fold it.
328 if (ConstOps.size() == I->getNumOperands()) {
329 if (CmpInst *C = dyn_cast<CmpInst>(I))
330 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
331 ConstOps[1], DL, TLI);
333 if (LoadInst *LI = dyn_cast<LoadInst>(I))
334 if (!LI->isVolatile())
335 return ConstantFoldLoadFromConstPtr(ConstOps[0], DL);
337 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
345 /// foldSelectICmpAndOr - We want to turn:
346 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
348 /// (or (shl (and X, C1), C3), y)
350 /// C1 and C2 are both powers of 2
352 /// C3 = Log(C2) - Log(C1)
354 /// This transform handles cases where:
355 /// 1. The icmp predicate is inverted
356 /// 2. The select operands are reversed
357 /// 3. The magnitude of C2 and C1 are flipped
358 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
360 InstCombiner::BuilderTy *Builder) {
361 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
362 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
365 Value *CmpLHS = IC->getOperand(0);
366 Value *CmpRHS = IC->getOperand(1);
368 if (!match(CmpRHS, m_Zero()))
373 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
377 bool OrOnTrueVal = false;
378 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
380 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
382 if (!OrOnFalseVal && !OrOnTrueVal)
386 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
388 unsigned C1Log = C1->logBase2();
389 unsigned C2Log = C2->logBase2();
391 V = Builder->CreateZExtOrTrunc(V, Y->getType());
392 V = Builder->CreateShl(V, C2Log - C1Log);
393 } else if (C1Log > C2Log) {
394 V = Builder->CreateLShr(V, C1Log - C2Log);
395 V = Builder->CreateZExtOrTrunc(V, Y->getType());
397 V = Builder->CreateZExtOrTrunc(V, Y->getType());
399 ICmpInst::Predicate Pred = IC->getPredicate();
400 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
401 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
402 V = Builder->CreateXor(V, *C2);
404 return Builder->CreateOr(V, Y);
407 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
408 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
410 /// For example, we can fold the following code sequence:
412 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
413 /// %1 = icmp ne i32 %x, 0
414 /// %2 = select i1 %1, i32 %0, i32 32
418 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
419 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
420 InstCombiner::BuilderTy *Builder) {
421 ICmpInst::Predicate Pred = ICI->getPredicate();
422 Value *CmpLHS = ICI->getOperand(0);
423 Value *CmpRHS = ICI->getOperand(1);
425 // Check if the condition value compares a value for equality against zero.
426 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
429 Value *Count = FalseVal;
430 Value *ValueOnZero = TrueVal;
431 if (Pred == ICmpInst::ICMP_NE)
432 std::swap(Count, ValueOnZero);
434 // Skip zero extend/truncate.
436 if (match(Count, m_ZExt(m_Value(V))) ||
437 match(Count, m_Trunc(m_Value(V))))
440 // Check if the value propagated on zero is a constant number equal to the
441 // sizeof in bits of 'Count'.
442 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
443 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
446 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
447 // input to the cttz/ctlz is used as LHS for the compare instruction.
448 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
449 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
450 IntrinsicInst *II = cast<IntrinsicInst>(Count);
451 IRBuilder<> Builder(II);
452 // Explicitly clear the 'undef_on_zero' flag.
453 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
454 Type *Ty = NewI->getArgOperand(1)->getType();
455 NewI->setArgOperand(1, Constant::getNullValue(Ty));
456 Builder.Insert(NewI);
457 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
463 /// visitSelectInstWithICmp - Visit a SelectInst that has an
464 /// ICmpInst as its first operand.
466 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
468 bool Changed = false;
469 ICmpInst::Predicate Pred = ICI->getPredicate();
470 Value *CmpLHS = ICI->getOperand(0);
471 Value *CmpRHS = ICI->getOperand(1);
472 Value *TrueVal = SI.getTrueValue();
473 Value *FalseVal = SI.getFalseValue();
475 // Check cases where the comparison is with a constant that
476 // can be adjusted to fit the min/max idiom. We may move or edit ICI
477 // here, so make sure the select is the only user.
478 if (ICI->hasOneUse())
479 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
480 // X < MIN ? T : F --> F
481 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
482 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
483 return ReplaceInstUsesWith(SI, FalseVal);
484 // X > MAX ? T : F --> F
485 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
486 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
487 return ReplaceInstUsesWith(SI, FalseVal);
490 case ICmpInst::ICMP_ULT:
491 case ICmpInst::ICMP_SLT:
492 case ICmpInst::ICMP_UGT:
493 case ICmpInst::ICMP_SGT: {
494 // These transformations only work for selects over integers.
495 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
499 Constant *AdjustedRHS;
500 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
501 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
502 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
503 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
505 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
506 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
507 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
508 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
509 ; // Nothing to do here. Values match without any sign/zero extension.
511 // Types do not match. Instead of calculating this with mixed types
512 // promote all to the larger type. This enables scalar evolution to
513 // analyze this expression.
514 else if (CmpRHS->getType()->getScalarSizeInBits()
515 < SelectTy->getBitWidth()) {
516 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
518 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
519 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
520 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
521 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
522 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
523 sextRHS == FalseVal) {
525 AdjustedRHS = sextRHS;
526 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
527 sextRHS == TrueVal) {
529 AdjustedRHS = sextRHS;
530 } else if (ICI->isUnsigned()) {
531 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
532 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
533 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
534 // zext + signed compare cannot be changed:
535 // 0xff <s 0x00, but 0x00ff >s 0x0000
536 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
537 zextRHS == FalseVal) {
539 AdjustedRHS = zextRHS;
540 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
541 zextRHS == TrueVal) {
543 AdjustedRHS = zextRHS;
551 Pred = ICmpInst::getSwappedPredicate(Pred);
552 CmpRHS = AdjustedRHS;
553 std::swap(FalseVal, TrueVal);
554 ICI->setPredicate(Pred);
555 ICI->setOperand(0, CmpLHS);
556 ICI->setOperand(1, CmpRHS);
557 SI.setOperand(1, TrueVal);
558 SI.setOperand(2, FalseVal);
560 // Move ICI instruction right before the select instruction. Otherwise
561 // the sext/zext value may be defined after the ICI instruction uses it.
562 ICI->moveBefore(&SI);
570 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
571 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
572 // FIXME: Type and constness constraints could be lifted, but we have to
573 // watch code size carefully. We should consider xor instead of
574 // sub/add when we decide to do that.
575 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
576 if (TrueVal->getType() == Ty) {
577 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
578 ConstantInt *C1 = nullptr, *C2 = nullptr;
579 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
580 C1 = dyn_cast<ConstantInt>(TrueVal);
581 C2 = dyn_cast<ConstantInt>(FalseVal);
582 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
583 C1 = dyn_cast<ConstantInt>(FalseVal);
584 C2 = dyn_cast<ConstantInt>(TrueVal);
587 // This shift results in either -1 or 0.
588 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
590 // Check if we can express the operation with a single or.
591 if (C2->isAllOnesValue())
592 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
594 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
595 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
601 // If we have an equality comparison then we know the value in one of the
602 // arms of the select. See if substituting this value into the arm and
603 // simplifying the result yields the same value as the other arm.
604 if (Pred == ICmpInst::ICMP_EQ) {
605 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
607 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
609 return ReplaceInstUsesWith(SI, FalseVal);
610 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
612 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
614 return ReplaceInstUsesWith(SI, FalseVal);
615 } else if (Pred == ICmpInst::ICMP_NE) {
616 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
618 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
620 return ReplaceInstUsesWith(SI, TrueVal);
621 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
623 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
625 return ReplaceInstUsesWith(SI, TrueVal);
628 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
630 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
631 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
632 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
633 SI.setOperand(1, CmpRHS);
635 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
636 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
637 SI.setOperand(2, CmpRHS);
642 if (unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits()) {
643 APInt MinSignedValue = APInt::getSignBit(BitWidth);
647 bool IsBitTest = false;
648 if (ICmpInst::isEquality(Pred) &&
649 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
650 match(CmpRHS, m_Zero())) {
652 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
653 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
657 TrueWhenUnset = false;
658 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
662 TrueWhenUnset = true;
666 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
667 if (TrueWhenUnset && TrueVal == X &&
668 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
669 V = Builder->CreateAnd(X, ~(*Y));
670 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
671 else if (!TrueWhenUnset && FalseVal == X &&
672 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
673 V = Builder->CreateAnd(X, ~(*Y));
674 // (X & Y) == 0 ? X ^ Y : X --> X | Y
675 else if (TrueWhenUnset && FalseVal == X &&
676 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
677 V = Builder->CreateOr(X, *Y);
678 // (X & Y) != 0 ? X : X ^ Y --> X | Y
679 else if (!TrueWhenUnset && TrueVal == X &&
680 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
681 V = Builder->CreateOr(X, *Y);
684 return ReplaceInstUsesWith(SI, V);
688 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
689 return ReplaceInstUsesWith(SI, V);
691 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
692 return ReplaceInstUsesWith(SI, V);
694 return Changed ? &SI : nullptr;
698 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
699 /// PHI node (but the two may be in different blocks). See if the true/false
700 /// values (V) are live in all of the predecessor blocks of the PHI. For
701 /// example, cases like this cannot be mapped:
703 /// X = phi [ C1, BB1], [C2, BB2]
705 /// Z = select X, Y, 0
707 /// because Y is not live in BB1/BB2.
709 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
710 const SelectInst &SI) {
711 // If the value is a non-instruction value like a constant or argument, it
712 // can always be mapped.
713 const Instruction *I = dyn_cast<Instruction>(V);
716 // If V is a PHI node defined in the same block as the condition PHI, we can
717 // map the arguments.
718 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
720 if (const PHINode *VP = dyn_cast<PHINode>(I))
721 if (VP->getParent() == CondPHI->getParent())
724 // Otherwise, if the PHI and select are defined in the same block and if V is
725 // defined in a different block, then we can transform it.
726 if (SI.getParent() == CondPHI->getParent() &&
727 I->getParent() != CondPHI->getParent())
730 // Otherwise we have a 'hard' case and we can't tell without doing more
731 // detailed dominator based analysis, punt.
735 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
736 /// SPF2(SPF1(A, B), C)
737 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
738 SelectPatternFlavor SPF1,
741 SelectPatternFlavor SPF2, Value *C) {
742 if (C == A || C == B) {
743 // MAX(MAX(A, B), B) -> MAX(A, B)
744 // MIN(MIN(a, b), a) -> MIN(a, b)
746 return ReplaceInstUsesWith(Outer, Inner);
748 // MAX(MIN(a, b), a) -> a
749 // MIN(MAX(a, b), a) -> a
750 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
751 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
752 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
753 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
754 return ReplaceInstUsesWith(Outer, C);
758 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
759 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
760 APInt ACB = CB->getValue();
761 APInt ACC = CC->getValue();
763 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
764 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
765 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
766 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
767 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
768 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
769 return ReplaceInstUsesWith(Outer, Inner);
771 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
772 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
773 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
774 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
775 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
776 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
777 Outer.replaceUsesOfWith(Inner, A);
784 // ABS(ABS(X)) -> ABS(X)
785 // NABS(NABS(X)) -> NABS(X)
786 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
787 return ReplaceInstUsesWith(Outer, Inner);
790 // ABS(NABS(X)) -> ABS(X)
791 // NABS(ABS(X)) -> NABS(X)
792 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
793 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
794 SelectInst *SI = cast<SelectInst>(Inner);
795 Value *NewSI = Builder->CreateSelect(
796 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
797 return ReplaceInstUsesWith(Outer, NewSI);
800 auto IsFreeOrProfitableToInvert =
801 [&](Value *V, Value *&NotV, bool &ElidesXor) {
802 if (match(V, m_Not(m_Value(NotV)))) {
803 // If V has at most 2 uses then we can get rid of the xor operation
805 ElidesXor |= !V->hasNUsesOrMore(3);
809 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
817 Value *NotA, *NotB, *NotC;
818 bool ElidesXor = false;
820 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
821 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
822 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
823 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
825 // This transform is performance neutral if we can elide at least one xor from
826 // the set of three operands, since we'll be tacking on an xor at the very
828 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
829 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
830 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
832 NotA = Builder->CreateNot(A);
834 NotB = Builder->CreateNot(B);
836 NotC = Builder->CreateNot(C);
838 Value *NewInner = generateMinMaxSelectPattern(
839 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
840 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
841 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
842 return ReplaceInstUsesWith(Outer, NewOuter);
848 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
849 /// both be) and we have an icmp instruction with zero, and we have an 'and'
850 /// with the non-constant value and a power of two we can turn the select
851 /// into a shift on the result of the 'and'.
852 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
853 ConstantInt *FalseVal,
854 InstCombiner::BuilderTy *Builder) {
855 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
856 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
859 if (!match(IC->getOperand(1), m_Zero()))
863 Value *LHS = IC->getOperand(0);
864 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
867 // If both select arms are non-zero see if we have a select of the form
868 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
869 // for 'x ? 2^n : 0' and fix the thing up at the end.
870 ConstantInt *Offset = nullptr;
871 if (!TrueVal->isZero() && !FalseVal->isZero()) {
872 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
874 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
879 // Adjust TrueVal and FalseVal to the offset.
880 TrueVal = ConstantInt::get(Builder->getContext(),
881 TrueVal->getValue() - Offset->getValue());
882 FalseVal = ConstantInt::get(Builder->getContext(),
883 FalseVal->getValue() - Offset->getValue());
886 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
887 if (!AndRHS->getValue().isPowerOf2() ||
888 (!TrueVal->getValue().isPowerOf2() &&
889 !FalseVal->getValue().isPowerOf2()))
892 // Determine which shift is needed to transform result of the 'and' into the
894 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
895 unsigned ValZeros = ValC->getValue().logBase2();
896 unsigned AndZeros = AndRHS->getValue().logBase2();
898 // If types don't match we can still convert the select by introducing a zext
899 // or a trunc of the 'and'. The trunc case requires that all of the truncated
900 // bits are zero, we can figure that out by looking at the 'and' mask.
901 if (AndZeros >= ValC->getBitWidth())
904 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
905 if (ValZeros > AndZeros)
906 V = Builder->CreateShl(V, ValZeros - AndZeros);
907 else if (ValZeros < AndZeros)
908 V = Builder->CreateLShr(V, AndZeros - ValZeros);
910 // Okay, now we know that everything is set up, we just don't know whether we
911 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
912 bool ShouldNotVal = !TrueVal->isZero();
913 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
915 V = Builder->CreateXor(V, ValC);
917 // Apply an offset if needed.
919 V = Builder->CreateAdd(V, Offset);
923 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
924 Value *CondVal = SI.getCondition();
925 Value *TrueVal = SI.getTrueValue();
926 Value *FalseVal = SI.getFalseValue();
929 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
930 return ReplaceInstUsesWith(SI, V);
932 if (SI.getType()->isIntegerTy(1)) {
933 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
934 if (C->getZExtValue()) {
935 // Change: A = select B, true, C --> A = or B, C
936 return BinaryOperator::CreateOr(CondVal, FalseVal);
938 // Change: A = select B, false, C --> A = and !B, C
939 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
940 return BinaryOperator::CreateAnd(NotCond, FalseVal);
942 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
943 if (!C->getZExtValue()) {
944 // Change: A = select B, C, false --> A = and B, C
945 return BinaryOperator::CreateAnd(CondVal, TrueVal);
947 // Change: A = select B, C, true --> A = or !B, C
948 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
949 return BinaryOperator::CreateOr(NotCond, TrueVal);
952 // select a, b, a -> a&b
953 // select a, a, b -> a|b
954 if (CondVal == TrueVal)
955 return BinaryOperator::CreateOr(CondVal, FalseVal);
956 if (CondVal == FalseVal)
957 return BinaryOperator::CreateAnd(CondVal, TrueVal);
959 // select a, ~a, b -> (~a)&b
960 // select a, b, ~a -> (~a)|b
961 if (match(TrueVal, m_Not(m_Specific(CondVal))))
962 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
963 if (match(FalseVal, m_Not(m_Specific(CondVal))))
964 return BinaryOperator::CreateOr(TrueVal, FalseVal);
967 // Selecting between two integer constants?
968 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
969 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
970 // select C, 1, 0 -> zext C to int
971 if (FalseValC->isZero() && TrueValC->getValue() == 1)
972 return new ZExtInst(CondVal, SI.getType());
974 // select C, -1, 0 -> sext C to int
975 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
976 return new SExtInst(CondVal, SI.getType());
978 // select C, 0, 1 -> zext !C to int
979 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
980 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
981 return new ZExtInst(NotCond, SI.getType());
984 // select C, 0, -1 -> sext !C to int
985 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
986 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
987 return new SExtInst(NotCond, SI.getType());
990 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
991 return ReplaceInstUsesWith(SI, V);
994 // See if we are selecting two values based on a comparison of the two values.
995 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
996 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
997 // Transform (X == Y) ? X : Y -> Y
998 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
999 // This is not safe in general for floating point:
1000 // consider X== -0, Y== +0.
1001 // It becomes safe if either operand is a nonzero constant.
1002 ConstantFP *CFPt, *CFPf;
1003 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1004 !CFPt->getValueAPF().isZero()) ||
1005 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1006 !CFPf->getValueAPF().isZero()))
1007 return ReplaceInstUsesWith(SI, FalseVal);
1009 // Transform (X une Y) ? X : Y -> X
1010 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1011 // This is not safe in general for floating point:
1012 // consider X== -0, Y== +0.
1013 // It becomes safe if either operand is a nonzero constant.
1014 ConstantFP *CFPt, *CFPf;
1015 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1016 !CFPt->getValueAPF().isZero()) ||
1017 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1018 !CFPf->getValueAPF().isZero()))
1019 return ReplaceInstUsesWith(SI, TrueVal);
1022 // Canonicalize to use ordered comparisons by swapping the select
1026 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1027 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1028 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1029 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1030 FCI->getName() + ".inv");
1032 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1033 SI.getName() + ".p");
1036 // NOTE: if we wanted to, this is where to detect MIN/MAX
1037 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1038 // Transform (X == Y) ? Y : X -> X
1039 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1040 // This is not safe in general for floating point:
1041 // consider X== -0, Y== +0.
1042 // It becomes safe if either operand is a nonzero constant.
1043 ConstantFP *CFPt, *CFPf;
1044 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1045 !CFPt->getValueAPF().isZero()) ||
1046 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1047 !CFPf->getValueAPF().isZero()))
1048 return ReplaceInstUsesWith(SI, FalseVal);
1050 // Transform (X une Y) ? Y : X -> Y
1051 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1052 // This is not safe in general for floating point:
1053 // consider X== -0, Y== +0.
1054 // It becomes safe if either operand is a nonzero constant.
1055 ConstantFP *CFPt, *CFPf;
1056 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1057 !CFPt->getValueAPF().isZero()) ||
1058 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1059 !CFPf->getValueAPF().isZero()))
1060 return ReplaceInstUsesWith(SI, TrueVal);
1063 // Canonicalize to use ordered comparisons by swapping the select
1067 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1068 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1069 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1070 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1071 FCI->getName() + ".inv");
1073 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1074 SI.getName() + ".p");
1077 // NOTE: if we wanted to, this is where to detect MIN/MAX
1079 // NOTE: if we wanted to, this is where to detect ABS
1082 // See if we are selecting two values based on a comparison of the two values.
1083 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1084 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1087 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
1088 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
1089 if (TI->hasOneUse() && FI->hasOneUse()) {
1090 Instruction *AddOp = nullptr, *SubOp = nullptr;
1092 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1093 if (TI->getOpcode() == FI->getOpcode())
1094 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1097 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
1098 // even legal for FP.
1099 if ((TI->getOpcode() == Instruction::Sub &&
1100 FI->getOpcode() == Instruction::Add) ||
1101 (TI->getOpcode() == Instruction::FSub &&
1102 FI->getOpcode() == Instruction::FAdd)) {
1103 AddOp = FI; SubOp = TI;
1104 } else if ((FI->getOpcode() == Instruction::Sub &&
1105 TI->getOpcode() == Instruction::Add) ||
1106 (FI->getOpcode() == Instruction::FSub &&
1107 TI->getOpcode() == Instruction::FAdd)) {
1108 AddOp = TI; SubOp = FI;
1112 Value *OtherAddOp = nullptr;
1113 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1114 OtherAddOp = AddOp->getOperand(1);
1115 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1116 OtherAddOp = AddOp->getOperand(0);
1120 // So at this point we know we have (Y -> OtherAddOp):
1121 // select C, (add X, Y), (sub X, Z)
1122 Value *NegVal; // Compute -Z
1123 if (SI.getType()->isFPOrFPVectorTy()) {
1124 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
1125 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1126 FastMathFlags Flags = AddOp->getFastMathFlags();
1127 Flags &= SubOp->getFastMathFlags();
1128 NegInst->setFastMathFlags(Flags);
1131 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
1134 Value *NewTrueOp = OtherAddOp;
1135 Value *NewFalseOp = NegVal;
1137 std::swap(NewTrueOp, NewFalseOp);
1139 Builder->CreateSelect(CondVal, NewTrueOp,
1140 NewFalseOp, SI.getName() + ".p");
1142 if (SI.getType()->isFPOrFPVectorTy()) {
1144 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1146 FastMathFlags Flags = AddOp->getFastMathFlags();
1147 Flags &= SubOp->getFastMathFlags();
1148 RI->setFastMathFlags(Flags);
1151 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1156 // See if we can fold the select into one of our operands.
1157 if (SI.getType()->isIntegerTy()) {
1158 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1161 Value *LHS, *RHS, *LHS2, *RHS2;
1162 SelectPatternFlavor SPF = matchSelectPattern(&SI, LHS, RHS);
1164 // MAX(MAX(a, b), a) -> MAX(a, b)
1165 // MIN(MIN(a, b), a) -> MIN(a, b)
1166 // MAX(MIN(a, b), a) -> a
1167 // MIN(MAX(a, b), a) -> a
1169 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2))
1170 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1173 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2))
1174 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1179 // MAX(~a, ~b) -> ~MIN(a, b)
1180 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1181 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1182 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1184 // This transform adds a xor operation and that extra cost needs to be
1185 // justified. We look for simplifications that will result from
1186 // applying this rule:
1189 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1190 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1191 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1194 Value *NewLHS = Builder->CreateNot(LHS);
1195 Value *NewRHS = Builder->CreateNot(RHS);
1196 Value *NewCmp = SPF == SPF_SMAX
1197 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1198 : Builder->CreateICmpULT(NewLHS, NewRHS);
1200 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1201 return ReplaceInstUsesWith(SI, NewSI);
1207 // ABS(-X) -> ABS(X)
1210 // See if we can fold the select into a phi node if the condition is a select.
1211 if (isa<PHINode>(SI.getCondition()))
1212 // The true/false values have to be live in the PHI predecessor's blocks.
1213 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1214 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1215 if (Instruction *NV = FoldOpIntoPhi(SI))
1218 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1219 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1220 // select(C, select(C, a, b), c) -> select(C, a, c)
1221 if (TrueSI->getCondition() == CondVal) {
1222 if (SI.getTrueValue() == TrueSI->getTrueValue())
1224 SI.setOperand(1, TrueSI->getTrueValue());
1227 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1228 // We choose this as normal form to enable folding on the And and shortening
1229 // paths for the values (this helps GetUnderlyingObjects() for example).
1230 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1231 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1232 SI.setOperand(0, And);
1233 SI.setOperand(1, TrueSI->getTrueValue());
1238 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1239 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1240 // select(C, a, select(C, b, c)) -> select(C, a, c)
1241 if (FalseSI->getCondition() == CondVal) {
1242 if (SI.getFalseValue() == FalseSI->getFalseValue())
1244 SI.setOperand(2, FalseSI->getFalseValue());
1247 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1248 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1249 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1250 SI.setOperand(0, Or);
1251 SI.setOperand(2, FalseSI->getFalseValue());
1257 if (BinaryOperator::isNot(CondVal)) {
1258 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1259 SI.setOperand(1, FalseVal);
1260 SI.setOperand(2, TrueVal);
1264 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1265 unsigned VWidth = VecTy->getNumElements();
1266 APInt UndefElts(VWidth, 0);
1267 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1268 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1270 return ReplaceInstUsesWith(SI, V);
1274 if (isa<ConstantAggregateZero>(CondVal)) {
1275 return ReplaceInstUsesWith(SI, FalseVal);