Silence -Wunused-variable in release builds.
[llvm/stm8.git] / lib / Transforms / InstCombine / InstCombineSelect.cpp
blob5733c20828c67c4e3c83607792c3c33345d63ce4
1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitSelect function.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Support/PatternMatch.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 using namespace llvm;
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)
68 return SPF_UNKNOWN;
72 /// GetSelectFoldableOperands - We want to turn code that looks like this:
73 /// %C = or %A, %B
74 /// %D = select %cond, %C, %A
75 /// into:
76 /// %C = select %cond, %B, 0
77 /// %D = or %A, %C
78 ///
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.
82 ///
83 static unsigned GetSelectFoldableOperands(Instruction *I) {
84 switch (I->getOpcode()) {
85 case Instruction::Add:
86 case Instruction::Mul:
87 case Instruction::And:
88 case Instruction::Or:
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:
95 return 1;
96 default:
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,
124 Instruction *FI) {
125 if (TI->getNumOperands() == 1) {
126 // If this is a non-volatile load or a cast from the same type,
127 // merge.
128 if (TI->isCast()) {
129 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
130 return 0;
131 } else {
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,
139 TI->getType());
142 // Only handle binary operators here.
143 if (!isa<BinaryOperator>(TI))
144 return 0;
146 // Figure out if the operations have any operands in common.
147 Value *MatchOp, *OtherOpT, *OtherOpF;
148 bool MatchIsOpZero;
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()) {
160 return 0;
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;
171 } else {
172 return 0;
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)) {
180 if (MatchIsOpZero)
181 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
182 else
183 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
185 llvm_unreachable("Shouldn't get here");
186 return 0;
189 static bool isSelect01(Constant *C1, Constant *C2) {
190 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
191 if (!C1I)
192 return false;
193 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
194 if (!C2I)
195 return false;
196 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
197 return false;
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,
205 Value *FalseVal) {
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)) {
214 OpToFold = 1;
215 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
216 OpToFold = 2;
219 if (OpToFold) {
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(),
229 FalseVal, NewSel);
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());
236 return BO;
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)) {
249 OpToFold = 1;
250 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
251 OpToFold = 2;
254 if (OpToFold) {
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(),
264 TrueVal, NewSel);
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());
271 return BO;
278 return 0;
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.
286 if (V == Op)
287 return RepOp;
289 Instruction *I = dyn_cast<Instruction>(V);
290 if (!I)
291 return 0;
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 // 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), TD);
305 if (C->getOperand(1) == Op)
306 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD);
309 // TODO: We could hand off more cases to instsimplify here.
311 // If all operands are constant after substituting Op for RepOp then we can
312 // constant fold the instruction.
313 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
314 // Build a list of all constant operands.
315 SmallVector<Constant*, 8> ConstOps;
316 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
317 if (I->getOperand(i) == Op)
318 ConstOps.push_back(CRepOp);
319 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
320 ConstOps.push_back(COp);
321 else
322 break;
325 // All operands were constants, fold it.
326 if (ConstOps.size() == I->getNumOperands())
327 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
328 ConstOps.data(), ConstOps.size(), TD);
331 return 0;
334 /// visitSelectInstWithICmp - Visit a SelectInst that has an
335 /// ICmpInst as its first operand.
337 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
338 ICmpInst *ICI) {
339 bool Changed = false;
340 ICmpInst::Predicate Pred = ICI->getPredicate();
341 Value *CmpLHS = ICI->getOperand(0);
342 Value *CmpRHS = ICI->getOperand(1);
343 Value *TrueVal = SI.getTrueValue();
344 Value *FalseVal = SI.getFalseValue();
346 // Check cases where the comparison is with a constant that
347 // can be adjusted to fit the min/max idiom. We may move or edit ICI
348 // here, so make sure the select is the only user.
349 if (ICI->hasOneUse())
350 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
351 // X < MIN ? T : F --> F
352 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
353 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
354 return ReplaceInstUsesWith(SI, FalseVal);
355 // X > MAX ? T : F --> F
356 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
357 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
358 return ReplaceInstUsesWith(SI, FalseVal);
359 switch (Pred) {
360 default: break;
361 case ICmpInst::ICMP_ULT:
362 case ICmpInst::ICMP_SLT:
363 case ICmpInst::ICMP_UGT:
364 case ICmpInst::ICMP_SGT: {
365 // These transformations only work for selects over integers.
366 const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
367 if (!SelectTy)
368 break;
370 Constant *AdjustedRHS;
371 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
372 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
373 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
374 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
376 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
377 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
378 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
379 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
380 ; // Nothing to do here. Values match without any sign/zero extension.
382 // Types do not match. Instead of calculating this with mixed types
383 // promote all to the larger type. This enables scalar evolution to
384 // analyze this expression.
385 else if (CmpRHS->getType()->getScalarSizeInBits()
386 < SelectTy->getBitWidth()) {
387 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
389 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
390 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
391 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
392 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
393 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
394 sextRHS == FalseVal) {
395 CmpLHS = TrueVal;
396 AdjustedRHS = sextRHS;
397 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
398 sextRHS == TrueVal) {
399 CmpLHS = FalseVal;
400 AdjustedRHS = sextRHS;
401 } else if (ICI->isUnsigned()) {
402 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
403 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
404 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
405 // zext + signed compare cannot be changed:
406 // 0xff <s 0x00, but 0x00ff >s 0x0000
407 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
408 zextRHS == FalseVal) {
409 CmpLHS = TrueVal;
410 AdjustedRHS = zextRHS;
411 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
412 zextRHS == TrueVal) {
413 CmpLHS = FalseVal;
414 AdjustedRHS = zextRHS;
415 } else
416 break;
417 } else
418 break;
419 } else
420 break;
422 Pred = ICmpInst::getSwappedPredicate(Pred);
423 CmpRHS = AdjustedRHS;
424 std::swap(FalseVal, TrueVal);
425 ICI->setPredicate(Pred);
426 ICI->setOperand(0, CmpLHS);
427 ICI->setOperand(1, CmpRHS);
428 SI.setOperand(1, TrueVal);
429 SI.setOperand(2, FalseVal);
431 // Move ICI instruction right before the select instruction. Otherwise
432 // the sext/zext value may be defined after the ICI instruction uses it.
433 ICI->moveBefore(&SI);
435 Changed = true;
436 break;
441 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
442 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
443 // FIXME: Type and constness constraints could be lifted, but we have to
444 // watch code size carefully. We should consider xor instead of
445 // sub/add when we decide to do that.
446 if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
447 if (TrueVal->getType() == Ty) {
448 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
449 ConstantInt *C1 = NULL, *C2 = NULL;
450 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
451 C1 = dyn_cast<ConstantInt>(TrueVal);
452 C2 = dyn_cast<ConstantInt>(FalseVal);
453 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
454 C1 = dyn_cast<ConstantInt>(FalseVal);
455 C2 = dyn_cast<ConstantInt>(TrueVal);
457 if (C1 && C2) {
458 // This shift results in either -1 or 0.
459 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
461 // Check if we can express the operation with a single or.
462 if (C2->isAllOnesValue())
463 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
465 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
466 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
472 // If we have an equality comparison then we know the value in one of the
473 // arms of the select. See if substituting this value into the arm and
474 // simplifying the result yields the same value as the other arm.
475 if (Pred == ICmpInst::ICMP_EQ) {
476 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) == TrueVal ||
477 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) == TrueVal)
478 return ReplaceInstUsesWith(SI, FalseVal);
479 } else if (Pred == ICmpInst::ICMP_NE) {
480 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) == FalseVal ||
481 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) == FalseVal)
482 return ReplaceInstUsesWith(SI, TrueVal);
485 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
487 if (isa<Constant>(CmpRHS)) {
488 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
489 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
490 SI.setOperand(1, CmpRHS);
491 Changed = true;
492 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
493 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
494 SI.setOperand(2, CmpRHS);
495 Changed = true;
499 return Changed ? &SI : 0;
503 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
504 /// PHI node (but the two may be in different blocks). See if the true/false
505 /// values (V) are live in all of the predecessor blocks of the PHI. For
506 /// example, cases like this cannot be mapped:
508 /// X = phi [ C1, BB1], [C2, BB2]
509 /// Y = add
510 /// Z = select X, Y, 0
512 /// because Y is not live in BB1/BB2.
514 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
515 const SelectInst &SI) {
516 // If the value is a non-instruction value like a constant or argument, it
517 // can always be mapped.
518 const Instruction *I = dyn_cast<Instruction>(V);
519 if (I == 0) return true;
521 // If V is a PHI node defined in the same block as the condition PHI, we can
522 // map the arguments.
523 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
525 if (const PHINode *VP = dyn_cast<PHINode>(I))
526 if (VP->getParent() == CondPHI->getParent())
527 return true;
529 // Otherwise, if the PHI and select are defined in the same block and if V is
530 // defined in a different block, then we can transform it.
531 if (SI.getParent() == CondPHI->getParent() &&
532 I->getParent() != CondPHI->getParent())
533 return true;
535 // Otherwise we have a 'hard' case and we can't tell without doing more
536 // detailed dominator based analysis, punt.
537 return false;
540 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
541 /// SPF2(SPF1(A, B), C)
542 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
543 SelectPatternFlavor SPF1,
544 Value *A, Value *B,
545 Instruction &Outer,
546 SelectPatternFlavor SPF2, Value *C) {
547 if (C == A || C == B) {
548 // MAX(MAX(A, B), B) -> MAX(A, B)
549 // MIN(MIN(a, b), a) -> MIN(a, b)
550 if (SPF1 == SPF2)
551 return ReplaceInstUsesWith(Outer, Inner);
553 // MAX(MIN(a, b), a) -> a
554 // MIN(MAX(a, b), a) -> a
555 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
556 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
557 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
558 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
559 return ReplaceInstUsesWith(Outer, C);
562 // TODO: MIN(MIN(A, 23), 97)
563 return 0;
567 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
568 /// both be) and we have an icmp instruction with zero, and we have an 'and'
569 /// with the non-constant value and a power of two we can turn the select
570 /// into a shift on the result of the 'and'.
571 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
572 ConstantInt *FalseVal,
573 InstCombiner::BuilderTy *Builder) {
574 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
575 if (!IC || !IC->isEquality())
576 return 0;
578 if (!match(IC->getOperand(1), m_Zero()))
579 return 0;
581 ConstantInt *AndRHS;
582 Value *LHS = IC->getOperand(0);
583 if (LHS->getType() != SI.getType() ||
584 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
585 return 0;
587 // If both select arms are non-zero see if we have a select of the form
588 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
589 // for 'x ? 2^n : 0' and fix the thing up at the end.
590 ConstantInt *Offset = 0;
591 if (!TrueVal->isZero() && !FalseVal->isZero()) {
592 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
593 Offset = FalseVal;
594 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
595 Offset = TrueVal;
596 else
597 return 0;
599 // Adjust TrueVal and FalseVal to the offset.
600 TrueVal = ConstantInt::get(Builder->getContext(),
601 TrueVal->getValue() - Offset->getValue());
602 FalseVal = ConstantInt::get(Builder->getContext(),
603 FalseVal->getValue() - Offset->getValue());
606 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
607 if (!AndRHS->getValue().isPowerOf2() ||
608 (!TrueVal->getValue().isPowerOf2() &&
609 !FalseVal->getValue().isPowerOf2()))
610 return 0;
612 // Determine which shift is needed to transform result of the 'and' into the
613 // desired result.
614 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
615 unsigned ValZeros = ValC->getValue().logBase2();
616 unsigned AndZeros = AndRHS->getValue().logBase2();
618 Value *V = LHS;
619 if (ValZeros > AndZeros)
620 V = Builder->CreateShl(V, ValZeros - AndZeros);
621 else if (ValZeros < AndZeros)
622 V = Builder->CreateLShr(V, AndZeros - ValZeros);
624 // Okay, now we know that everything is set up, we just don't know whether we
625 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
626 bool ShouldNotVal = !TrueVal->isZero();
627 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
628 if (ShouldNotVal)
629 V = Builder->CreateXor(V, ValC);
631 // Apply an offset if needed.
632 if (Offset)
633 V = Builder->CreateAdd(V, Offset);
634 return V;
637 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
638 Value *CondVal = SI.getCondition();
639 Value *TrueVal = SI.getTrueValue();
640 Value *FalseVal = SI.getFalseValue();
642 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
643 return ReplaceInstUsesWith(SI, V);
645 if (SI.getType()->isIntegerTy(1)) {
646 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
647 if (C->getZExtValue()) {
648 // Change: A = select B, true, C --> A = or B, C
649 return BinaryOperator::CreateOr(CondVal, FalseVal);
651 // Change: A = select B, false, C --> A = and !B, C
652 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
653 return BinaryOperator::CreateAnd(NotCond, FalseVal);
654 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
655 if (C->getZExtValue() == false) {
656 // Change: A = select B, C, false --> A = and B, C
657 return BinaryOperator::CreateAnd(CondVal, TrueVal);
659 // Change: A = select B, C, true --> A = or !B, C
660 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
661 return BinaryOperator::CreateOr(NotCond, TrueVal);
664 // select a, b, a -> a&b
665 // select a, a, b -> a|b
666 if (CondVal == TrueVal)
667 return BinaryOperator::CreateOr(CondVal, FalseVal);
668 else if (CondVal == FalseVal)
669 return BinaryOperator::CreateAnd(CondVal, TrueVal);
672 // Selecting between two integer constants?
673 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
674 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
675 // select C, 1, 0 -> zext C to int
676 if (FalseValC->isZero() && TrueValC->getValue() == 1)
677 return new ZExtInst(CondVal, SI.getType());
679 // select C, -1, 0 -> sext C to int
680 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
681 return new SExtInst(CondVal, SI.getType());
683 // select C, 0, 1 -> zext !C to int
684 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
685 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
686 return new ZExtInst(NotCond, SI.getType());
689 // select C, 0, -1 -> sext !C to int
690 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
691 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
692 return new SExtInst(NotCond, SI.getType());
695 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
696 return ReplaceInstUsesWith(SI, V);
699 // See if we are selecting two values based on a comparison of the two values.
700 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
701 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
702 // Transform (X == Y) ? X : Y -> Y
703 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
704 // This is not safe in general for floating point:
705 // consider X== -0, Y== +0.
706 // It becomes safe if either operand is a nonzero constant.
707 ConstantFP *CFPt, *CFPf;
708 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
709 !CFPt->getValueAPF().isZero()) ||
710 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
711 !CFPf->getValueAPF().isZero()))
712 return ReplaceInstUsesWith(SI, FalseVal);
714 // Transform (X une Y) ? X : Y -> X
715 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
716 // This is not safe in general for floating point:
717 // consider X== -0, Y== +0.
718 // It becomes safe if either operand is a nonzero constant.
719 ConstantFP *CFPt, *CFPf;
720 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
721 !CFPt->getValueAPF().isZero()) ||
722 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
723 !CFPf->getValueAPF().isZero()))
724 return ReplaceInstUsesWith(SI, TrueVal);
726 // NOTE: if we wanted to, this is where to detect MIN/MAX
728 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
729 // Transform (X == Y) ? Y : X -> X
730 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
731 // This is not safe in general for floating point:
732 // consider X== -0, Y== +0.
733 // It becomes safe if either operand is a nonzero constant.
734 ConstantFP *CFPt, *CFPf;
735 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
736 !CFPt->getValueAPF().isZero()) ||
737 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
738 !CFPf->getValueAPF().isZero()))
739 return ReplaceInstUsesWith(SI, FalseVal);
741 // Transform (X une Y) ? Y : X -> Y
742 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
743 // This is not safe in general for floating point:
744 // consider X== -0, Y== +0.
745 // It becomes safe if either operand is a nonzero constant.
746 ConstantFP *CFPt, *CFPf;
747 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
748 !CFPt->getValueAPF().isZero()) ||
749 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
750 !CFPf->getValueAPF().isZero()))
751 return ReplaceInstUsesWith(SI, TrueVal);
753 // NOTE: if we wanted to, this is where to detect MIN/MAX
755 // NOTE: if we wanted to, this is where to detect ABS
758 // See if we are selecting two values based on a comparison of the two values.
759 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
760 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
761 return Result;
763 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
764 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
765 if (TI->hasOneUse() && FI->hasOneUse()) {
766 Instruction *AddOp = 0, *SubOp = 0;
768 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
769 if (TI->getOpcode() == FI->getOpcode())
770 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
771 return IV;
773 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
774 // even legal for FP.
775 if ((TI->getOpcode() == Instruction::Sub &&
776 FI->getOpcode() == Instruction::Add) ||
777 (TI->getOpcode() == Instruction::FSub &&
778 FI->getOpcode() == Instruction::FAdd)) {
779 AddOp = FI; SubOp = TI;
780 } else if ((FI->getOpcode() == Instruction::Sub &&
781 TI->getOpcode() == Instruction::Add) ||
782 (FI->getOpcode() == Instruction::FSub &&
783 TI->getOpcode() == Instruction::FAdd)) {
784 AddOp = TI; SubOp = FI;
787 if (AddOp) {
788 Value *OtherAddOp = 0;
789 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
790 OtherAddOp = AddOp->getOperand(1);
791 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
792 OtherAddOp = AddOp->getOperand(0);
795 if (OtherAddOp) {
796 // So at this point we know we have (Y -> OtherAddOp):
797 // select C, (add X, Y), (sub X, Z)
798 Value *NegVal; // Compute -Z
799 if (SI.getType()->isFPOrFPVectorTy()) {
800 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
801 } else {
802 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
805 Value *NewTrueOp = OtherAddOp;
806 Value *NewFalseOp = NegVal;
807 if (AddOp != TI)
808 std::swap(NewTrueOp, NewFalseOp);
809 Value *NewSel =
810 Builder->CreateSelect(CondVal, NewTrueOp,
811 NewFalseOp, SI.getName() + ".p");
813 if (SI.getType()->isFPOrFPVectorTy())
814 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
815 else
816 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
821 // See if we can fold the select into one of our operands.
822 if (SI.getType()->isIntegerTy()) {
823 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
824 return FoldI;
826 // MAX(MAX(a, b), a) -> MAX(a, b)
827 // MIN(MIN(a, b), a) -> MIN(a, b)
828 // MAX(MIN(a, b), a) -> a
829 // MIN(MAX(a, b), a) -> a
830 Value *LHS, *RHS, *LHS2, *RHS2;
831 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
832 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
833 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
834 SI, SPF, RHS))
835 return R;
836 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
837 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
838 SI, SPF, LHS))
839 return R;
842 // TODO.
843 // ABS(-X) -> ABS(X)
844 // ABS(ABS(X)) -> ABS(X)
847 // See if we can fold the select into a phi node if the condition is a select.
848 if (isa<PHINode>(SI.getCondition()))
849 // The true/false values have to be live in the PHI predecessor's blocks.
850 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
851 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
852 if (Instruction *NV = FoldOpIntoPhi(SI))
853 return NV;
855 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
856 if (TrueSI->getCondition() == CondVal) {
857 SI.setOperand(1, TrueSI->getTrueValue());
858 return &SI;
861 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
862 if (FalseSI->getCondition() == CondVal) {
863 SI.setOperand(2, FalseSI->getFalseValue());
864 return &SI;
868 if (BinaryOperator::isNot(CondVal)) {
869 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
870 SI.setOperand(1, FalseVal);
871 SI.setOperand(2, TrueVal);
872 return &SI;
875 return 0;