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 "InstCombine.h"
15 #include "llvm/Support/PatternMatch.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
18 using namespace PatternMatch;
20 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
21 /// returning the kind and providing the out parameter results if we
22 /// successfully match.
23 static SelectPatternFlavor
24 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
25 SelectInst *SI = dyn_cast<SelectInst>(V);
26 if (SI == 0) return SPF_UNKNOWN;
28 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
29 if (ICI == 0) return SPF_UNKNOWN;
31 LHS = ICI->getOperand(0);
32 RHS = ICI->getOperand(1);
34 // (icmp X, Y) ? X : Y
35 if (SI->getTrueValue() == ICI->getOperand(0) &&
36 SI->getFalseValue() == ICI->getOperand(1)) {
37 switch (ICI->getPredicate()) {
38 default: return SPF_UNKNOWN; // Equality.
39 case ICmpInst::ICMP_UGT:
40 case ICmpInst::ICMP_UGE: return SPF_UMAX;
41 case ICmpInst::ICMP_SGT:
42 case ICmpInst::ICMP_SGE: return SPF_SMAX;
43 case ICmpInst::ICMP_ULT:
44 case ICmpInst::ICMP_ULE: return SPF_UMIN;
45 case ICmpInst::ICMP_SLT:
46 case ICmpInst::ICMP_SLE: return SPF_SMIN;
50 // (icmp X, Y) ? Y : X
51 if (SI->getTrueValue() == ICI->getOperand(1) &&
52 SI->getFalseValue() == ICI->getOperand(0)) {
53 switch (ICI->getPredicate()) {
54 default: return SPF_UNKNOWN; // Equality.
55 case ICmpInst::ICMP_UGT:
56 case ICmpInst::ICMP_UGE: return SPF_UMIN;
57 case ICmpInst::ICMP_SGT:
58 case ICmpInst::ICMP_SGE: return SPF_SMIN;
59 case ICmpInst::ICMP_ULT:
60 case ICmpInst::ICMP_ULE: return SPF_UMAX;
61 case ICmpInst::ICMP_SLT:
62 case ICmpInst::ICMP_SLE: return SPF_SMAX;
66 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
72 /// GetSelectFoldableOperands - We want to turn code that looks like this:
74 /// %D = select %cond, %C, %A
76 /// %C = select %cond, %B, 0
79 /// Assuming that the specified instruction is an operand to the select, return
80 /// a bitmask indicating which operands of this instruction are foldable if they
81 /// equal the other incoming value of the select.
83 static unsigned GetSelectFoldableOperands(Instruction *I) {
84 switch (I->getOpcode()) {
85 case Instruction::Add:
86 case Instruction::Mul:
87 case Instruction::And:
89 case Instruction::Xor:
90 return 3; // Can fold through either operand.
91 case Instruction::Sub: // Can only fold on the amount subtracted.
92 case Instruction::Shl: // Can only fold on the shift amount.
93 case Instruction::LShr:
94 case Instruction::AShr:
97 return 0; // Cannot fold
101 /// GetSelectFoldableConstant - For the same transformation as the previous
102 /// function, return the identity constant that goes into the select.
103 static Constant *GetSelectFoldableConstant(Instruction *I) {
104 switch (I->getOpcode()) {
105 default: llvm_unreachable("This cannot happen!");
106 case Instruction::Add:
107 case Instruction::Sub:
108 case Instruction::Or:
109 case Instruction::Xor:
110 case Instruction::Shl:
111 case Instruction::LShr:
112 case Instruction::AShr:
113 return Constant::getNullValue(I->getType());
114 case Instruction::And:
115 return Constant::getAllOnesValue(I->getType());
116 case Instruction::Mul:
117 return ConstantInt::get(I->getType(), 1);
121 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
122 /// have the same opcode and only one use each. Try to simplify this.
123 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
125 if (TI->getNumOperands() == 1) {
126 // If this is a non-volatile load or a cast from the same type,
129 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
132 return 0; // unknown unary op.
135 // Fold this by inserting a select from the input values.
136 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
137 FI->getOperand(0), SI.getName()+".v");
138 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
142 // Only handle binary operators here.
143 if (!isa<BinaryOperator>(TI))
146 // Figure out if the operations have any operands in common.
147 Value *MatchOp, *OtherOpT, *OtherOpF;
149 if (TI->getOperand(0) == FI->getOperand(0)) {
150 MatchOp = TI->getOperand(0);
151 OtherOpT = TI->getOperand(1);
152 OtherOpF = FI->getOperand(1);
153 MatchIsOpZero = true;
154 } else if (TI->getOperand(1) == FI->getOperand(1)) {
155 MatchOp = TI->getOperand(1);
156 OtherOpT = TI->getOperand(0);
157 OtherOpF = FI->getOperand(0);
158 MatchIsOpZero = false;
159 } else if (!TI->isCommutative()) {
161 } else if (TI->getOperand(0) == FI->getOperand(1)) {
162 MatchOp = TI->getOperand(0);
163 OtherOpT = TI->getOperand(1);
164 OtherOpF = FI->getOperand(0);
165 MatchIsOpZero = true;
166 } else if (TI->getOperand(1) == FI->getOperand(0)) {
167 MatchOp = TI->getOperand(1);
168 OtherOpT = TI->getOperand(0);
169 OtherOpF = FI->getOperand(1);
170 MatchIsOpZero = true;
175 // If we reach here, they do have operations in common.
176 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
177 OtherOpF, SI.getName()+".v");
179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
181 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
183 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
185 llvm_unreachable("Shouldn't get here");
189 static bool isSelect01(Constant *C1, Constant *C2) {
190 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
193 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
196 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
198 return C1I->isOne() || C1I->isAllOnesValue() ||
199 C2I->isOne() || C2I->isAllOnesValue();
202 /// FoldSelectIntoOp - Try fold the select into one of the operands to
203 /// facilitate further optimization.
204 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
206 // See the comment above GetSelectFoldableOperands for a description of the
207 // transformation we are doing here.
208 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
209 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
210 !isa<Constant>(FalseVal)) {
211 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
212 unsigned OpToFold = 0;
213 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
215 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
220 Constant *C = GetSelectFoldableConstant(TVI);
221 Value *OOp = TVI->getOperand(2-OpToFold);
222 // Avoid creating select between 2 constants unless it's selecting
223 // between 0, 1 and -1.
224 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
225 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
226 NewSel->takeName(TVI);
227 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
228 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
230 if (isa<PossiblyExactOperator>(BO))
231 BO->setIsExact(TVI_BO->isExact());
232 if (isa<OverflowingBinaryOperator>(BO)) {
233 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
234 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
243 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
244 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
245 !isa<Constant>(TrueVal)) {
246 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
247 unsigned OpToFold = 0;
248 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
250 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
255 Constant *C = GetSelectFoldableConstant(FVI);
256 Value *OOp = FVI->getOperand(2-OpToFold);
257 // Avoid creating select between 2 constants unless it's selecting
258 // between 0, 1 and -1.
259 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
260 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
261 NewSel->takeName(FVI);
262 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
263 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
265 if (isa<PossiblyExactOperator>(BO))
266 BO->setIsExact(FVI_BO->isExact());
267 if (isa<OverflowingBinaryOperator>(BO)) {
268 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
269 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
281 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
282 /// replaced with RepOp.
283 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
284 const TargetData *TD) {
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), TD);
297 if (B->getOperand(1) == Op)
298 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD);
301 // If all operands are constant after substituting Op for RepOp then we can
302 // constant fold the instruction.
303 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
304 // Build a list of all constant operands.
305 SmallVector<Constant*, 8> ConstOps;
306 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
307 if (I->getOperand(i) == Op)
308 ConstOps.push_back(CRepOp);
309 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
310 ConstOps.push_back(COp);
315 // All operands were constants, fold it.
316 if (ConstOps.size() == I->getNumOperands())
317 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
318 ConstOps.data(), ConstOps.size(), TD);
324 /// visitSelectInstWithICmp - Visit a SelectInst that has an
325 /// ICmpInst as its first operand.
327 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
329 bool Changed = false;
330 ICmpInst::Predicate Pred = ICI->getPredicate();
331 Value *CmpLHS = ICI->getOperand(0);
332 Value *CmpRHS = ICI->getOperand(1);
333 Value *TrueVal = SI.getTrueValue();
334 Value *FalseVal = SI.getFalseValue();
336 // Check cases where the comparison is with a constant that
337 // can be adjusted to fit the min/max idiom. We may move or edit ICI
338 // here, so make sure the select is the only user.
339 if (ICI->hasOneUse())
340 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
341 // X < MIN ? T : F --> F
342 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
343 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
344 return ReplaceInstUsesWith(SI, FalseVal);
345 // X > MAX ? T : F --> F
346 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
347 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
348 return ReplaceInstUsesWith(SI, FalseVal);
351 case ICmpInst::ICMP_ULT:
352 case ICmpInst::ICMP_SLT:
353 case ICmpInst::ICMP_UGT:
354 case ICmpInst::ICMP_SGT: {
355 // These transformations only work for selects over integers.
356 const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
360 Constant *AdjustedRHS;
361 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
362 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
363 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
364 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
366 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
367 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
368 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
369 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
370 ; // Nothing to do here. Values match without any sign/zero extension.
372 // Types do not match. Instead of calculating this with mixed types
373 // promote all to the larger type. This enables scalar evolution to
374 // analyze this expression.
375 else if (CmpRHS->getType()->getScalarSizeInBits()
376 < SelectTy->getBitWidth()) {
377 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
379 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
380 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
381 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
382 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
383 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
384 sextRHS == FalseVal) {
386 AdjustedRHS = sextRHS;
387 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
388 sextRHS == TrueVal) {
390 AdjustedRHS = sextRHS;
391 } else if (ICI->isUnsigned()) {
392 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
393 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
394 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
395 // zext + signed compare cannot be changed:
396 // 0xff <s 0x00, but 0x00ff >s 0x0000
397 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
398 zextRHS == FalseVal) {
400 AdjustedRHS = zextRHS;
401 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
402 zextRHS == TrueVal) {
404 AdjustedRHS = zextRHS;
412 Pred = ICmpInst::getSwappedPredicate(Pred);
413 CmpRHS = AdjustedRHS;
414 std::swap(FalseVal, TrueVal);
415 ICI->setPredicate(Pred);
416 ICI->setOperand(0, CmpLHS);
417 ICI->setOperand(1, CmpRHS);
418 SI.setOperand(1, TrueVal);
419 SI.setOperand(2, FalseVal);
421 // Move ICI instruction right before the select instruction. Otherwise
422 // the sext/zext value may be defined after the ICI instruction uses it.
423 ICI->moveBefore(&SI);
431 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
432 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
433 // FIXME: Type and constness constraints could be lifted, but we have to
434 // watch code size carefully. We should consider xor instead of
435 // sub/add when we decide to do that.
436 if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
437 if (TrueVal->getType() == Ty) {
438 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
439 ConstantInt *C1 = NULL, *C2 = NULL;
440 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
441 C1 = dyn_cast<ConstantInt>(TrueVal);
442 C2 = dyn_cast<ConstantInt>(FalseVal);
443 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
444 C1 = dyn_cast<ConstantInt>(FalseVal);
445 C2 = dyn_cast<ConstantInt>(TrueVal);
448 // This shift results in either -1 or 0.
449 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
451 // Check if we can express the operation with a single or.
452 if (C2->isAllOnesValue())
453 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
455 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
456 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
462 // If we have an equality comparison then we know the value in one of the
463 // arms of the select. See if substituting this value into the arm and
464 // simplifying the result yields the same value as the other arm.
465 if (Pred == ICmpInst::ICMP_EQ) {
466 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) == TrueVal ||
467 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) == TrueVal)
468 return ReplaceInstUsesWith(SI, FalseVal);
469 } else if (Pred == ICmpInst::ICMP_NE) {
470 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) == FalseVal ||
471 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) == FalseVal)
472 return ReplaceInstUsesWith(SI, TrueVal);
475 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
477 if (isa<Constant>(CmpRHS)) {
478 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
479 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
480 SI.setOperand(1, CmpRHS);
482 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
483 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
484 SI.setOperand(2, CmpRHS);
489 return Changed ? &SI : 0;
493 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
494 /// PHI node (but the two may be in different blocks). See if the true/false
495 /// values (V) are live in all of the predecessor blocks of the PHI. For
496 /// example, cases like this cannot be mapped:
498 /// X = phi [ C1, BB1], [C2, BB2]
500 /// Z = select X, Y, 0
502 /// because Y is not live in BB1/BB2.
504 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
505 const SelectInst &SI) {
506 // If the value is a non-instruction value like a constant or argument, it
507 // can always be mapped.
508 const Instruction *I = dyn_cast<Instruction>(V);
509 if (I == 0) return true;
511 // If V is a PHI node defined in the same block as the condition PHI, we can
512 // map the arguments.
513 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
515 if (const PHINode *VP = dyn_cast<PHINode>(I))
516 if (VP->getParent() == CondPHI->getParent())
519 // Otherwise, if the PHI and select are defined in the same block and if V is
520 // defined in a different block, then we can transform it.
521 if (SI.getParent() == CondPHI->getParent() &&
522 I->getParent() != CondPHI->getParent())
525 // Otherwise we have a 'hard' case and we can't tell without doing more
526 // detailed dominator based analysis, punt.
530 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
531 /// SPF2(SPF1(A, B), C)
532 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
533 SelectPatternFlavor SPF1,
536 SelectPatternFlavor SPF2, Value *C) {
537 if (C == A || C == B) {
538 // MAX(MAX(A, B), B) -> MAX(A, B)
539 // MIN(MIN(a, b), a) -> MIN(a, b)
541 return ReplaceInstUsesWith(Outer, Inner);
543 // MAX(MIN(a, b), a) -> a
544 // MIN(MAX(a, b), a) -> a
545 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
546 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
547 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
548 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
549 return ReplaceInstUsesWith(Outer, C);
552 // TODO: MIN(MIN(A, 23), 97)
557 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
558 /// both be) and we have an icmp instruction with zero, and we have an 'and'
559 /// with the non-constant value and a power of two we can turn the select
560 /// into a shift on the result of the 'and'.
561 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
562 ConstantInt *FalseVal,
563 InstCombiner::BuilderTy *Builder) {
564 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
565 if (!IC || !IC->isEquality())
568 if (!match(IC->getOperand(1), m_Zero()))
572 Value *LHS = IC->getOperand(0);
573 if (LHS->getType() != SI.getType() ||
574 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
577 // If both select arms are non-zero see if we have a select of the form
578 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
579 // for 'x ? 2^n : 0' and fix the thing up at the end.
580 ConstantInt *Offset = 0;
581 if (!TrueVal->isZero() && !FalseVal->isZero()) {
582 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
584 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
589 // Adjust TrueVal and FalseVal to the offset.
590 TrueVal = ConstantInt::get(Builder->getContext(),
591 TrueVal->getValue() - Offset->getValue());
592 FalseVal = ConstantInt::get(Builder->getContext(),
593 FalseVal->getValue() - Offset->getValue());
596 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
597 if (!AndRHS->getValue().isPowerOf2() ||
598 (!TrueVal->getValue().isPowerOf2() &&
599 !FalseVal->getValue().isPowerOf2()))
602 // Determine which shift is needed to transform result of the 'and' into the
604 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
605 unsigned ValZeros = ValC->getValue().logBase2();
606 unsigned AndZeros = AndRHS->getValue().logBase2();
609 if (ValZeros > AndZeros)
610 V = Builder->CreateShl(V, ValZeros - AndZeros);
611 else if (ValZeros < AndZeros)
612 V = Builder->CreateLShr(V, AndZeros - ValZeros);
614 // Okay, now we know that everything is set up, we just don't know whether we
615 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
616 bool ShouldNotVal = !TrueVal->isZero();
617 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
619 V = Builder->CreateXor(V, ValC);
621 // Apply an offset if needed.
623 V = Builder->CreateAdd(V, Offset);
627 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
628 Value *CondVal = SI.getCondition();
629 Value *TrueVal = SI.getTrueValue();
630 Value *FalseVal = SI.getFalseValue();
632 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
633 return ReplaceInstUsesWith(SI, V);
635 if (SI.getType()->isIntegerTy(1)) {
636 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
637 if (C->getZExtValue()) {
638 // Change: A = select B, true, C --> A = or B, C
639 return BinaryOperator::CreateOr(CondVal, FalseVal);
641 // Change: A = select B, false, C --> A = and !B, C
642 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
643 return BinaryOperator::CreateAnd(NotCond, FalseVal);
644 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
645 if (C->getZExtValue() == false) {
646 // Change: A = select B, C, false --> A = and B, C
647 return BinaryOperator::CreateAnd(CondVal, TrueVal);
649 // Change: A = select B, C, true --> A = or !B, C
650 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
651 return BinaryOperator::CreateOr(NotCond, TrueVal);
654 // select a, b, a -> a&b
655 // select a, a, b -> a|b
656 if (CondVal == TrueVal)
657 return BinaryOperator::CreateOr(CondVal, FalseVal);
658 else if (CondVal == FalseVal)
659 return BinaryOperator::CreateAnd(CondVal, TrueVal);
662 // Selecting between two integer constants?
663 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
664 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
665 // select C, 1, 0 -> zext C to int
666 if (FalseValC->isZero() && TrueValC->getValue() == 1)
667 return new ZExtInst(CondVal, SI.getType());
669 // select C, -1, 0 -> sext C to int
670 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
671 return new SExtInst(CondVal, SI.getType());
673 // select C, 0, 1 -> zext !C to int
674 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
675 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
676 return new ZExtInst(NotCond, SI.getType());
679 // select C, 0, -1 -> sext !C to int
680 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
681 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
682 return new SExtInst(NotCond, SI.getType());
685 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
686 return ReplaceInstUsesWith(SI, V);
689 // See if we are selecting two values based on a comparison of the two values.
690 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
691 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
692 // Transform (X == Y) ? X : Y -> Y
693 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
694 // This is not safe in general for floating point:
695 // consider X== -0, Y== +0.
696 // It becomes safe if either operand is a nonzero constant.
697 ConstantFP *CFPt, *CFPf;
698 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
699 !CFPt->getValueAPF().isZero()) ||
700 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
701 !CFPf->getValueAPF().isZero()))
702 return ReplaceInstUsesWith(SI, FalseVal);
704 // Transform (X une Y) ? X : Y -> X
705 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
706 // This is not safe in general for floating point:
707 // consider X== -0, Y== +0.
708 // It becomes safe if either operand is a nonzero constant.
709 ConstantFP *CFPt, *CFPf;
710 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
711 !CFPt->getValueAPF().isZero()) ||
712 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
713 !CFPf->getValueAPF().isZero()))
714 return ReplaceInstUsesWith(SI, TrueVal);
716 // NOTE: if we wanted to, this is where to detect MIN/MAX
718 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
719 // Transform (X == Y) ? Y : X -> X
720 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
721 // This is not safe in general for floating point:
722 // consider X== -0, Y== +0.
723 // It becomes safe if either operand is a nonzero constant.
724 ConstantFP *CFPt, *CFPf;
725 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
726 !CFPt->getValueAPF().isZero()) ||
727 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
728 !CFPf->getValueAPF().isZero()))
729 return ReplaceInstUsesWith(SI, FalseVal);
731 // Transform (X une Y) ? Y : X -> Y
732 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
733 // This is not safe in general for floating point:
734 // consider X== -0, Y== +0.
735 // It becomes safe if either operand is a nonzero constant.
736 ConstantFP *CFPt, *CFPf;
737 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
738 !CFPt->getValueAPF().isZero()) ||
739 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
740 !CFPf->getValueAPF().isZero()))
741 return ReplaceInstUsesWith(SI, TrueVal);
743 // NOTE: if we wanted to, this is where to detect MIN/MAX
745 // NOTE: if we wanted to, this is where to detect ABS
748 // See if we are selecting two values based on a comparison of the two values.
749 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
750 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
753 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
754 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
755 if (TI->hasOneUse() && FI->hasOneUse()) {
756 Instruction *AddOp = 0, *SubOp = 0;
758 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
759 if (TI->getOpcode() == FI->getOpcode())
760 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
763 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
764 // even legal for FP.
765 if ((TI->getOpcode() == Instruction::Sub &&
766 FI->getOpcode() == Instruction::Add) ||
767 (TI->getOpcode() == Instruction::FSub &&
768 FI->getOpcode() == Instruction::FAdd)) {
769 AddOp = FI; SubOp = TI;
770 } else if ((FI->getOpcode() == Instruction::Sub &&
771 TI->getOpcode() == Instruction::Add) ||
772 (FI->getOpcode() == Instruction::FSub &&
773 TI->getOpcode() == Instruction::FAdd)) {
774 AddOp = TI; SubOp = FI;
778 Value *OtherAddOp = 0;
779 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
780 OtherAddOp = AddOp->getOperand(1);
781 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
782 OtherAddOp = AddOp->getOperand(0);
786 // So at this point we know we have (Y -> OtherAddOp):
787 // select C, (add X, Y), (sub X, Z)
788 Value *NegVal; // Compute -Z
789 if (SI.getType()->isFloatingPointTy()) {
790 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
792 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
795 Value *NewTrueOp = OtherAddOp;
796 Value *NewFalseOp = NegVal;
798 std::swap(NewTrueOp, NewFalseOp);
800 Builder->CreateSelect(CondVal, NewTrueOp,
801 NewFalseOp, SI.getName() + ".p");
803 if (SI.getType()->isFloatingPointTy())
804 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
806 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
811 // See if we can fold the select into one of our operands.
812 if (SI.getType()->isIntegerTy()) {
813 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
816 // MAX(MAX(a, b), a) -> MAX(a, b)
817 // MIN(MIN(a, b), a) -> MIN(a, b)
818 // MAX(MIN(a, b), a) -> a
819 // MIN(MAX(a, b), a) -> a
820 Value *LHS, *RHS, *LHS2, *RHS2;
821 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
822 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
823 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
826 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
827 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
834 // ABS(ABS(X)) -> ABS(X)
837 // See if we can fold the select into a phi node if the condition is a select.
838 if (isa<PHINode>(SI.getCondition()))
839 // The true/false values have to be live in the PHI predecessor's blocks.
840 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
841 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
842 if (Instruction *NV = FoldOpIntoPhi(SI))
845 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
846 if (TrueSI->getCondition() == CondVal) {
847 SI.setOperand(1, TrueSI->getTrueValue());
851 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
852 if (FalseSI->getCondition() == CondVal) {
853 SI.setOperand(2, FalseSI->getFalseValue());
858 if (BinaryOperator::isNot(CondVal)) {
859 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
860 SI.setOperand(1, FalseVal);
861 SI.setOperand(2, TrueVal);