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 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
137 FI->getOperand(0), SI.getName()+".v");
138 InsertNewInstBefore(NewSI, SI);
139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
143 // Only handle binary operators here.
144 if (!isa<BinaryOperator>(TI))
147 // Figure out if the operations have any operands in common.
148 Value *MatchOp, *OtherOpT, *OtherOpF;
150 if (TI->getOperand(0) == FI->getOperand(0)) {
151 MatchOp = TI->getOperand(0);
152 OtherOpT = TI->getOperand(1);
153 OtherOpF = FI->getOperand(1);
154 MatchIsOpZero = true;
155 } else if (TI->getOperand(1) == FI->getOperand(1)) {
156 MatchOp = TI->getOperand(1);
157 OtherOpT = TI->getOperand(0);
158 OtherOpF = FI->getOperand(0);
159 MatchIsOpZero = false;
160 } else if (!TI->isCommutative()) {
162 } else if (TI->getOperand(0) == FI->getOperand(1)) {
163 MatchOp = TI->getOperand(0);
164 OtherOpT = TI->getOperand(1);
165 OtherOpF = FI->getOperand(0);
166 MatchIsOpZero = true;
167 } else if (TI->getOperand(1) == FI->getOperand(0)) {
168 MatchOp = TI->getOperand(1);
169 OtherOpT = TI->getOperand(0);
170 OtherOpF = FI->getOperand(1);
171 MatchIsOpZero = true;
176 // If we reach here, they do have operations in common.
177 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
178 OtherOpF, SI.getName()+".v");
179 InsertNewInstBefore(NewSI, SI);
181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
183 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
185 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
187 llvm_unreachable("Shouldn't get here");
191 static bool isSelect01(Constant *C1, Constant *C2) {
192 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
195 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
198 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
200 return C1I->isOne() || C1I->isAllOnesValue() ||
201 C2I->isOne() || C2I->isAllOnesValue();
204 /// FoldSelectIntoOp - Try fold the select into one of the operands to
205 /// facilitate further optimization.
206 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
208 // See the comment above GetSelectFoldableOperands for a description of the
209 // transformation we are doing here.
210 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
211 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
212 !isa<Constant>(FalseVal)) {
213 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
214 unsigned OpToFold = 0;
215 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
217 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
222 Constant *C = GetSelectFoldableConstant(TVI);
223 Value *OOp = TVI->getOperand(2-OpToFold);
224 // Avoid creating select between 2 constants unless it's selecting
225 // between 0, 1 and -1.
226 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
227 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
228 InsertNewInstBefore(NewSel, SI);
229 NewSel->takeName(TVI);
230 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
231 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
233 if (isa<PossiblyExactOperator>(BO))
234 BO->setIsExact(TVI_BO->isExact());
235 if (isa<OverflowingBinaryOperator>(BO)) {
236 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
237 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
246 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
247 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
248 !isa<Constant>(TrueVal)) {
249 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
250 unsigned OpToFold = 0;
251 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
253 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
258 Constant *C = GetSelectFoldableConstant(FVI);
259 Value *OOp = FVI->getOperand(2-OpToFold);
260 // Avoid creating select between 2 constants unless it's selecting
261 // between 0, 1 and -1.
262 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
263 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
264 InsertNewInstBefore(NewSel, SI);
265 NewSel->takeName(FVI);
266 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
267 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
269 if (isa<PossiblyExactOperator>(BO))
270 BO->setIsExact(FVI_BO->isExact());
271 if (isa<OverflowingBinaryOperator>(BO)) {
272 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
273 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
285 /// visitSelectInstWithICmp - Visit a SelectInst that has an
286 /// ICmpInst as its first operand.
288 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
290 bool Changed = false;
291 ICmpInst::Predicate Pred = ICI->getPredicate();
292 Value *CmpLHS = ICI->getOperand(0);
293 Value *CmpRHS = ICI->getOperand(1);
294 Value *TrueVal = SI.getTrueValue();
295 Value *FalseVal = SI.getFalseValue();
297 // Check cases where the comparison is with a constant that
298 // can be adjusted to fit the min/max idiom. We may move or edit ICI
299 // here, so make sure the select is the only user.
300 if (ICI->hasOneUse())
301 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
302 // X < MIN ? T : F --> F
303 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
304 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
305 return ReplaceInstUsesWith(SI, FalseVal);
306 // X > MAX ? T : F --> F
307 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
308 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
309 return ReplaceInstUsesWith(SI, FalseVal);
312 case ICmpInst::ICMP_ULT:
313 case ICmpInst::ICMP_SLT:
314 case ICmpInst::ICMP_UGT:
315 case ICmpInst::ICMP_SGT: {
316 // These transformations only work for selects over integers.
317 const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
321 Constant *AdjustedRHS;
322 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
323 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
324 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
325 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
327 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
328 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
329 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
330 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
331 ; // Nothing to do here. Values match without any sign/zero extension.
333 // Types do not match. Instead of calculating this with mixed types
334 // promote all to the larger type. This enables scalar evolution to
335 // analyze this expression.
336 else if (CmpRHS->getType()->getScalarSizeInBits()
337 < SelectTy->getBitWidth()) {
338 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
340 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
341 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
342 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
343 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
344 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
345 sextRHS == FalseVal) {
347 AdjustedRHS = sextRHS;
348 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
349 sextRHS == TrueVal) {
351 AdjustedRHS = sextRHS;
352 } else if (ICI->isUnsigned()) {
353 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
354 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
355 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
356 // zext + signed compare cannot be changed:
357 // 0xff <s 0x00, but 0x00ff >s 0x0000
358 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
359 zextRHS == FalseVal) {
361 AdjustedRHS = zextRHS;
362 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
363 zextRHS == TrueVal) {
365 AdjustedRHS = zextRHS;
373 Pred = ICmpInst::getSwappedPredicate(Pred);
374 CmpRHS = AdjustedRHS;
375 std::swap(FalseVal, TrueVal);
376 ICI->setPredicate(Pred);
377 ICI->setOperand(0, CmpLHS);
378 ICI->setOperand(1, CmpRHS);
379 SI.setOperand(1, TrueVal);
380 SI.setOperand(2, FalseVal);
382 // Move ICI instruction right before the select instruction. Otherwise
383 // the sext/zext value may be defined after the ICI instruction uses it.
384 ICI->moveBefore(&SI);
392 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
393 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
394 // FIXME: Type and constness constraints could be lifted, but we have to
395 // watch code size carefully. We should consider xor instead of
396 // sub/add when we decide to do that.
397 if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
398 if (TrueVal->getType() == Ty) {
399 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
400 ConstantInt *C1 = NULL, *C2 = NULL;
401 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
402 C1 = dyn_cast<ConstantInt>(TrueVal);
403 C2 = dyn_cast<ConstantInt>(FalseVal);
404 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
405 C1 = dyn_cast<ConstantInt>(FalseVal);
406 C2 = dyn_cast<ConstantInt>(TrueVal);
409 // This shift results in either -1 or 0.
410 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
412 // Check if we can express the operation with a single or.
413 if (C2->isAllOnesValue())
414 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
416 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
417 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
423 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
424 // Transform (X == Y) ? X : Y -> Y
425 if (Pred == ICmpInst::ICMP_EQ)
426 return ReplaceInstUsesWith(SI, FalseVal);
427 // Transform (X != Y) ? X : Y -> X
428 if (Pred == ICmpInst::ICMP_NE)
429 return ReplaceInstUsesWith(SI, TrueVal);
430 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
432 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
433 // Transform (X == Y) ? Y : X -> X
434 if (Pred == ICmpInst::ICMP_EQ)
435 return ReplaceInstUsesWith(SI, FalseVal);
436 // Transform (X != Y) ? Y : X -> Y
437 if (Pred == ICmpInst::ICMP_NE)
438 return ReplaceInstUsesWith(SI, TrueVal);
439 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
442 if (isa<Constant>(CmpRHS)) {
443 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
444 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
445 SI.setOperand(1, CmpRHS);
447 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
448 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
449 SI.setOperand(2, CmpRHS);
454 return Changed ? &SI : 0;
458 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
459 /// PHI node (but the two may be in different blocks). See if the true/false
460 /// values (V) are live in all of the predecessor blocks of the PHI. For
461 /// example, cases like this cannot be mapped:
463 /// X = phi [ C1, BB1], [C2, BB2]
465 /// Z = select X, Y, 0
467 /// because Y is not live in BB1/BB2.
469 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
470 const SelectInst &SI) {
471 // If the value is a non-instruction value like a constant or argument, it
472 // can always be mapped.
473 const Instruction *I = dyn_cast<Instruction>(V);
474 if (I == 0) return true;
476 // If V is a PHI node defined in the same block as the condition PHI, we can
477 // map the arguments.
478 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
480 if (const PHINode *VP = dyn_cast<PHINode>(I))
481 if (VP->getParent() == CondPHI->getParent())
484 // Otherwise, if the PHI and select are defined in the same block and if V is
485 // defined in a different block, then we can transform it.
486 if (SI.getParent() == CondPHI->getParent() &&
487 I->getParent() != CondPHI->getParent())
490 // Otherwise we have a 'hard' case and we can't tell without doing more
491 // detailed dominator based analysis, punt.
495 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
496 /// SPF2(SPF1(A, B), C)
497 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
498 SelectPatternFlavor SPF1,
501 SelectPatternFlavor SPF2, Value *C) {
502 if (C == A || C == B) {
503 // MAX(MAX(A, B), B) -> MAX(A, B)
504 // MIN(MIN(a, b), a) -> MIN(a, b)
506 return ReplaceInstUsesWith(Outer, Inner);
508 // MAX(MIN(a, b), a) -> a
509 // MIN(MAX(a, b), a) -> a
510 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
511 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
512 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
513 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
514 return ReplaceInstUsesWith(Outer, C);
517 // TODO: MIN(MIN(A, 23), 97)
522 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
523 /// both be) and we have an icmp instruction with zero, and we have an 'and'
524 /// with the non-constant value and a power of two we can turn the select
525 /// into a shift on the result of the 'and'.
526 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
527 ConstantInt *FalseVal,
528 InstCombiner::BuilderTy *Builder) {
529 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
530 if (!IC || !IC->isEquality())
533 if (!match(IC->getOperand(1), m_Zero()))
537 Value *LHS = IC->getOperand(0);
538 if (LHS->getType() != SI.getType() ||
539 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
542 // If both select arms are non-zero see if we have a select of the form
543 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
544 // for 'x ? 2^n : 0' and fix the thing up at the end.
545 ConstantInt *Offset = 0;
546 if (!TrueVal->isZero() && !FalseVal->isZero()) {
547 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
549 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
554 // Adjust TrueVal and FalseVal to the offset.
555 TrueVal = ConstantInt::get(Builder->getContext(),
556 TrueVal->getValue() - Offset->getValue());
557 FalseVal = ConstantInt::get(Builder->getContext(),
558 FalseVal->getValue() - Offset->getValue());
561 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
562 if (!AndRHS->getValue().isPowerOf2() ||
563 (!TrueVal->getValue().isPowerOf2() &&
564 !FalseVal->getValue().isPowerOf2()))
567 // Determine which shift is needed to transform result of the 'and' into the
569 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
570 unsigned ValZeros = ValC->getValue().logBase2();
571 unsigned AndZeros = AndRHS->getValue().logBase2();
574 if (ValZeros > AndZeros)
575 V = Builder->CreateShl(V, ValZeros - AndZeros);
576 else if (ValZeros < AndZeros)
577 V = Builder->CreateLShr(V, AndZeros - ValZeros);
579 // Okay, now we know that everything is set up, we just don't know whether we
580 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
581 bool ShouldNotVal = !TrueVal->isZero();
582 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
584 V = Builder->CreateXor(V, ValC);
586 // Apply an offset if needed.
588 V = Builder->CreateAdd(V, Offset);
592 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
593 Value *CondVal = SI.getCondition();
594 Value *TrueVal = SI.getTrueValue();
595 Value *FalseVal = SI.getFalseValue();
597 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
598 return ReplaceInstUsesWith(SI, V);
600 if (SI.getType()->isIntegerTy(1)) {
601 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
602 if (C->getZExtValue()) {
603 // Change: A = select B, true, C --> A = or B, C
604 return BinaryOperator::CreateOr(CondVal, FalseVal);
606 // Change: A = select B, false, C --> A = and !B, C
607 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
608 return BinaryOperator::CreateAnd(NotCond, FalseVal);
609 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
610 if (C->getZExtValue() == false) {
611 // Change: A = select B, C, false --> A = and B, C
612 return BinaryOperator::CreateAnd(CondVal, TrueVal);
614 // Change: A = select B, C, true --> A = or !B, C
615 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
616 return BinaryOperator::CreateOr(NotCond, TrueVal);
619 // select a, b, a -> a&b
620 // select a, a, b -> a|b
621 if (CondVal == TrueVal)
622 return BinaryOperator::CreateOr(CondVal, FalseVal);
623 else if (CondVal == FalseVal)
624 return BinaryOperator::CreateAnd(CondVal, TrueVal);
627 // Selecting between two integer constants?
628 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
629 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
630 // select C, 1, 0 -> zext C to int
631 if (FalseValC->isZero() && TrueValC->getValue() == 1)
632 return new ZExtInst(CondVal, SI.getType());
634 // select C, -1, 0 -> sext C to int
635 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
636 return new SExtInst(CondVal, SI.getType());
638 // select C, 0, 1 -> zext !C to int
639 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
640 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
641 return new ZExtInst(NotCond, SI.getType());
644 // select C, 0, -1 -> sext !C to int
645 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
646 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
647 return new SExtInst(NotCond, SI.getType());
650 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
651 return ReplaceInstUsesWith(SI, V);
654 // See if we are selecting two values based on a comparison of the two values.
655 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
656 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
657 // Transform (X == Y) ? X : Y -> Y
658 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
659 // This is not safe in general for floating point:
660 // consider X== -0, Y== +0.
661 // It becomes safe if either operand is a nonzero constant.
662 ConstantFP *CFPt, *CFPf;
663 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
664 !CFPt->getValueAPF().isZero()) ||
665 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
666 !CFPf->getValueAPF().isZero()))
667 return ReplaceInstUsesWith(SI, FalseVal);
669 // Transform (X une Y) ? X : Y -> X
670 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
671 // This is not safe in general for floating point:
672 // consider X== -0, Y== +0.
673 // It becomes safe if either operand is a nonzero constant.
674 ConstantFP *CFPt, *CFPf;
675 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
676 !CFPt->getValueAPF().isZero()) ||
677 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
678 !CFPf->getValueAPF().isZero()))
679 return ReplaceInstUsesWith(SI, TrueVal);
681 // NOTE: if we wanted to, this is where to detect MIN/MAX
683 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
684 // Transform (X == Y) ? Y : X -> X
685 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
686 // This is not safe in general for floating point:
687 // consider X== -0, Y== +0.
688 // It becomes safe if either operand is a nonzero constant.
689 ConstantFP *CFPt, *CFPf;
690 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
691 !CFPt->getValueAPF().isZero()) ||
692 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
693 !CFPf->getValueAPF().isZero()))
694 return ReplaceInstUsesWith(SI, FalseVal);
696 // Transform (X une Y) ? Y : X -> Y
697 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
698 // This is not safe in general for floating point:
699 // consider X== -0, Y== +0.
700 // It becomes safe if either operand is a nonzero constant.
701 ConstantFP *CFPt, *CFPf;
702 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
703 !CFPt->getValueAPF().isZero()) ||
704 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
705 !CFPf->getValueAPF().isZero()))
706 return ReplaceInstUsesWith(SI, TrueVal);
708 // NOTE: if we wanted to, this is where to detect MIN/MAX
710 // NOTE: if we wanted to, this is where to detect ABS
713 // See if we are selecting two values based on a comparison of the two values.
714 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
715 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
718 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
719 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
720 if (TI->hasOneUse() && FI->hasOneUse()) {
721 Instruction *AddOp = 0, *SubOp = 0;
723 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
724 if (TI->getOpcode() == FI->getOpcode())
725 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
728 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
729 // even legal for FP.
730 if ((TI->getOpcode() == Instruction::Sub &&
731 FI->getOpcode() == Instruction::Add) ||
732 (TI->getOpcode() == Instruction::FSub &&
733 FI->getOpcode() == Instruction::FAdd)) {
734 AddOp = FI; SubOp = TI;
735 } else if ((FI->getOpcode() == Instruction::Sub &&
736 TI->getOpcode() == Instruction::Add) ||
737 (FI->getOpcode() == Instruction::FSub &&
738 TI->getOpcode() == Instruction::FAdd)) {
739 AddOp = TI; SubOp = FI;
743 Value *OtherAddOp = 0;
744 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
745 OtherAddOp = AddOp->getOperand(1);
746 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
747 OtherAddOp = AddOp->getOperand(0);
751 // So at this point we know we have (Y -> OtherAddOp):
752 // select C, (add X, Y), (sub X, Z)
753 Value *NegVal; // Compute -Z
754 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
755 NegVal = ConstantExpr::getNeg(C);
756 } else if (SI.getType()->isFloatingPointTy()) {
757 NegVal = InsertNewInstBefore(
758 BinaryOperator::CreateFNeg(SubOp->getOperand(1),
761 NegVal = InsertNewInstBefore(
762 BinaryOperator::CreateNeg(SubOp->getOperand(1),
766 Value *NewTrueOp = OtherAddOp;
767 Value *NewFalseOp = NegVal;
769 std::swap(NewTrueOp, NewFalseOp);
770 Instruction *NewSel =
771 SelectInst::Create(CondVal, NewTrueOp,
772 NewFalseOp, SI.getName() + ".p");
774 NewSel = InsertNewInstBefore(NewSel, SI);
775 if (SI.getType()->isFloatingPointTy())
776 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
778 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
783 // See if we can fold the select into one of our operands.
784 if (SI.getType()->isIntegerTy()) {
785 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
788 // MAX(MAX(a, b), a) -> MAX(a, b)
789 // MIN(MIN(a, b), a) -> MIN(a, b)
790 // MAX(MIN(a, b), a) -> a
791 // MIN(MAX(a, b), a) -> a
792 Value *LHS, *RHS, *LHS2, *RHS2;
793 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
794 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
795 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
798 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
799 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
806 // ABS(ABS(X)) -> ABS(X)
809 // See if we can fold the select into a phi node if the condition is a select.
810 if (isa<PHINode>(SI.getCondition()))
811 // The true/false values have to be live in the PHI predecessor's blocks.
812 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
813 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
814 if (Instruction *NV = FoldOpIntoPhi(SI))
817 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
818 if (TrueSI->getCondition() == CondVal) {
819 SI.setOperand(1, TrueSI->getTrueValue());
823 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
824 if (FalseSI->getCondition() == CondVal) {
825 SI.setOperand(2, FalseSI->getFalseValue());
830 if (BinaryOperator::isNot(CondVal)) {
831 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
832 SI.setOperand(1, FalseVal);
833 SI.setOperand(2, TrueVal);