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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/Support/PatternMatch.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
22 /// returning the kind and providing the out parameter results if we
23 /// successfully match.
24 static SelectPatternFlavor
MatchSelectPattern(Value * V,Value * & LHS,Value * & RHS)25 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
26 SelectInst *SI = dyn_cast<SelectInst>(V);
27 if (SI == 0) return SPF_UNKNOWN;
28
29 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
30 if (ICI == 0) return SPF_UNKNOWN;
31
32 LHS = ICI->getOperand(0);
33 RHS = ICI->getOperand(1);
34
35 // (icmp X, Y) ? X : Y
36 if (SI->getTrueValue() == ICI->getOperand(0) &&
37 SI->getFalseValue() == ICI->getOperand(1)) {
38 switch (ICI->getPredicate()) {
39 default: return SPF_UNKNOWN; // Equality.
40 case ICmpInst::ICMP_UGT:
41 case ICmpInst::ICMP_UGE: return SPF_UMAX;
42 case ICmpInst::ICMP_SGT:
43 case ICmpInst::ICMP_SGE: return SPF_SMAX;
44 case ICmpInst::ICMP_ULT:
45 case ICmpInst::ICMP_ULE: return SPF_UMIN;
46 case ICmpInst::ICMP_SLT:
47 case ICmpInst::ICMP_SLE: return SPF_SMIN;
48 }
49 }
50
51 // (icmp X, Y) ? Y : X
52 if (SI->getTrueValue() == ICI->getOperand(1) &&
53 SI->getFalseValue() == ICI->getOperand(0)) {
54 switch (ICI->getPredicate()) {
55 default: return SPF_UNKNOWN; // Equality.
56 case ICmpInst::ICMP_UGT:
57 case ICmpInst::ICMP_UGE: return SPF_UMIN;
58 case ICmpInst::ICMP_SGT:
59 case ICmpInst::ICMP_SGE: return SPF_SMIN;
60 case ICmpInst::ICMP_ULT:
61 case ICmpInst::ICMP_ULE: return SPF_UMAX;
62 case ICmpInst::ICMP_SLT:
63 case ICmpInst::ICMP_SLE: return SPF_SMAX;
64 }
65 }
66
67 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
68
69 return SPF_UNKNOWN;
70 }
71
72
73 /// GetSelectFoldableOperands - We want to turn code that looks like this:
74 /// %C = or %A, %B
75 /// %D = select %cond, %C, %A
76 /// into:
77 /// %C = select %cond, %B, 0
78 /// %D = or %A, %C
79 ///
80 /// Assuming that the specified instruction is an operand to the select, return
81 /// a bitmask indicating which operands of this instruction are foldable if they
82 /// equal the other incoming value of the select.
83 ///
GetSelectFoldableOperands(Instruction * I)84 static unsigned GetSelectFoldableOperands(Instruction *I) {
85 switch (I->getOpcode()) {
86 case Instruction::Add:
87 case Instruction::Mul:
88 case Instruction::And:
89 case Instruction::Or:
90 case Instruction::Xor:
91 return 3; // Can fold through either operand.
92 case Instruction::Sub: // Can only fold on the amount subtracted.
93 case Instruction::Shl: // Can only fold on the shift amount.
94 case Instruction::LShr:
95 case Instruction::AShr:
96 return 1;
97 default:
98 return 0; // Cannot fold
99 }
100 }
101
102 /// GetSelectFoldableConstant - For the same transformation as the previous
103 /// function, return the identity constant that goes into the select.
GetSelectFoldableConstant(Instruction * I)104 static Constant *GetSelectFoldableConstant(Instruction *I) {
105 switch (I->getOpcode()) {
106 default: llvm_unreachable("This cannot happen!");
107 case Instruction::Add:
108 case Instruction::Sub:
109 case Instruction::Or:
110 case Instruction::Xor:
111 case Instruction::Shl:
112 case Instruction::LShr:
113 case Instruction::AShr:
114 return Constant::getNullValue(I->getType());
115 case Instruction::And:
116 return Constant::getAllOnesValue(I->getType());
117 case Instruction::Mul:
118 return ConstantInt::get(I->getType(), 1);
119 }
120 }
121
122 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
123 /// have the same opcode and only one use each. Try to simplify this.
FoldSelectOpOp(SelectInst & SI,Instruction * TI,Instruction * FI)124 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
125 Instruction *FI) {
126 if (TI->getNumOperands() == 1) {
127 // If this is a non-volatile load or a cast from the same type,
128 // merge.
129 if (TI->isCast()) {
130 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
131 return 0;
132 } else {
133 return 0; // unknown unary op.
134 }
135
136 // Fold this by inserting a select from the input values.
137 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
138 FI->getOperand(0), SI.getName()+".v");
139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
140 TI->getType());
141 }
142
143 // Only handle binary operators here.
144 if (!isa<BinaryOperator>(TI))
145 return 0;
146
147 // Figure out if the operations have any operands in common.
148 Value *MatchOp, *OtherOpT, *OtherOpF;
149 bool MatchIsOpZero;
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()) {
161 return 0;
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;
172 } else {
173 return 0;
174 }
175
176 // If we reach here, they do have operations in common.
177 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
178 OtherOpF, SI.getName()+".v");
179
180 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
181 if (MatchIsOpZero)
182 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
183 else
184 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
185 }
186 llvm_unreachable("Shouldn't get here");
187 return 0;
188 }
189
isSelect01(Constant * C1,Constant * C2)190 static bool isSelect01(Constant *C1, Constant *C2) {
191 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
192 if (!C1I)
193 return false;
194 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
195 if (!C2I)
196 return false;
197 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
198 return false;
199 return C1I->isOne() || C1I->isAllOnesValue() ||
200 C2I->isOne() || C2I->isAllOnesValue();
201 }
202
203 /// FoldSelectIntoOp - Try fold the select into one of the operands to
204 /// facilitate further optimization.
FoldSelectIntoOp(SelectInst & SI,Value * TrueVal,Value * FalseVal)205 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
206 Value *FalseVal) {
207 // See the comment above GetSelectFoldableOperands for a description of the
208 // transformation we are doing here.
209 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
210 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
211 !isa<Constant>(FalseVal)) {
212 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
213 unsigned OpToFold = 0;
214 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
215 OpToFold = 1;
216 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
217 OpToFold = 2;
218 }
219
220 if (OpToFold) {
221 Constant *C = GetSelectFoldableConstant(TVI);
222 Value *OOp = TVI->getOperand(2-OpToFold);
223 // Avoid creating select between 2 constants unless it's selecting
224 // between 0, 1 and -1.
225 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
226 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
227 NewSel->takeName(TVI);
228 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
229 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
230 FalseVal, NewSel);
231 if (isa<PossiblyExactOperator>(BO))
232 BO->setIsExact(TVI_BO->isExact());
233 if (isa<OverflowingBinaryOperator>(BO)) {
234 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
235 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
236 }
237 return BO;
238 }
239 }
240 }
241 }
242 }
243
244 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
245 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
246 !isa<Constant>(TrueVal)) {
247 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
248 unsigned OpToFold = 0;
249 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
250 OpToFold = 1;
251 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
252 OpToFold = 2;
253 }
254
255 if (OpToFold) {
256 Constant *C = GetSelectFoldableConstant(FVI);
257 Value *OOp = FVI->getOperand(2-OpToFold);
258 // Avoid creating select between 2 constants unless it's selecting
259 // between 0, 1 and -1.
260 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
261 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
262 NewSel->takeName(FVI);
263 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
264 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
265 TrueVal, NewSel);
266 if (isa<PossiblyExactOperator>(BO))
267 BO->setIsExact(FVI_BO->isExact());
268 if (isa<OverflowingBinaryOperator>(BO)) {
269 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
270 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
271 }
272 return BO;
273 }
274 }
275 }
276 }
277 }
278
279 return 0;
280 }
281
282 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
283 /// replaced with RepOp.
SimplifyWithOpReplaced(Value * V,Value * Op,Value * RepOp,const TargetData * TD)284 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
285 const TargetData *TD) {
286 // Trivial replacement.
287 if (V == Op)
288 return RepOp;
289
290 Instruction *I = dyn_cast<Instruction>(V);
291 if (!I)
292 return 0;
293
294 // If this is a binary operator, try to simplify it with the replaced op.
295 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
296 if (B->getOperand(0) == Op)
297 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD);
298 if (B->getOperand(1) == Op)
299 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD);
300 }
301
302 // Same for CmpInsts.
303 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
304 if (C->getOperand(0) == Op)
305 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD);
306 if (C->getOperand(1) == Op)
307 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD);
308 }
309
310 // TODO: We could hand off more cases to instsimplify here.
311
312 // If all operands are constant after substituting Op for RepOp then we can
313 // constant fold the instruction.
314 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
315 // Build a list of all constant operands.
316 SmallVector<Constant*, 8> ConstOps;
317 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
318 if (I->getOperand(i) == Op)
319 ConstOps.push_back(CRepOp);
320 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
321 ConstOps.push_back(COp);
322 else
323 break;
324 }
325
326 // All operands were constants, fold it.
327 if (ConstOps.size() == I->getNumOperands()) {
328 if (LoadInst *LI = dyn_cast<LoadInst>(I))
329 if (!LI->isVolatile())
330 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
331
332 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
333 ConstOps, TD);
334 }
335 }
336
337 return 0;
338 }
339
340 /// visitSelectInstWithICmp - Visit a SelectInst that has an
341 /// ICmpInst as its first operand.
342 ///
visitSelectInstWithICmp(SelectInst & SI,ICmpInst * ICI)343 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
344 ICmpInst *ICI) {
345 bool Changed = false;
346 ICmpInst::Predicate Pred = ICI->getPredicate();
347 Value *CmpLHS = ICI->getOperand(0);
348 Value *CmpRHS = ICI->getOperand(1);
349 Value *TrueVal = SI.getTrueValue();
350 Value *FalseVal = SI.getFalseValue();
351
352 // Check cases where the comparison is with a constant that
353 // can be adjusted to fit the min/max idiom. We may move or edit ICI
354 // here, so make sure the select is the only user.
355 if (ICI->hasOneUse())
356 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
357 // X < MIN ? T : F --> F
358 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
359 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
360 return ReplaceInstUsesWith(SI, FalseVal);
361 // X > MAX ? T : F --> F
362 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
363 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
364 return ReplaceInstUsesWith(SI, FalseVal);
365 switch (Pred) {
366 default: break;
367 case ICmpInst::ICMP_ULT:
368 case ICmpInst::ICMP_SLT:
369 case ICmpInst::ICMP_UGT:
370 case ICmpInst::ICMP_SGT: {
371 // These transformations only work for selects over integers.
372 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
373 if (!SelectTy)
374 break;
375
376 Constant *AdjustedRHS;
377 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
378 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
379 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
380 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
381
382 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
383 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
384 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
385 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
386 ; // Nothing to do here. Values match without any sign/zero extension.
387
388 // Types do not match. Instead of calculating this with mixed types
389 // promote all to the larger type. This enables scalar evolution to
390 // analyze this expression.
391 else if (CmpRHS->getType()->getScalarSizeInBits()
392 < SelectTy->getBitWidth()) {
393 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
394
395 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
396 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
397 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
398 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
399 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
400 sextRHS == FalseVal) {
401 CmpLHS = TrueVal;
402 AdjustedRHS = sextRHS;
403 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
404 sextRHS == TrueVal) {
405 CmpLHS = FalseVal;
406 AdjustedRHS = sextRHS;
407 } else if (ICI->isUnsigned()) {
408 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
409 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
410 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
411 // zext + signed compare cannot be changed:
412 // 0xff <s 0x00, but 0x00ff >s 0x0000
413 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
414 zextRHS == FalseVal) {
415 CmpLHS = TrueVal;
416 AdjustedRHS = zextRHS;
417 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
418 zextRHS == TrueVal) {
419 CmpLHS = FalseVal;
420 AdjustedRHS = zextRHS;
421 } else
422 break;
423 } else
424 break;
425 } else
426 break;
427
428 Pred = ICmpInst::getSwappedPredicate(Pred);
429 CmpRHS = AdjustedRHS;
430 std::swap(FalseVal, TrueVal);
431 ICI->setPredicate(Pred);
432 ICI->setOperand(0, CmpLHS);
433 ICI->setOperand(1, CmpRHS);
434 SI.setOperand(1, TrueVal);
435 SI.setOperand(2, FalseVal);
436
437 // Move ICI instruction right before the select instruction. Otherwise
438 // the sext/zext value may be defined after the ICI instruction uses it.
439 ICI->moveBefore(&SI);
440
441 Changed = true;
442 break;
443 }
444 }
445 }
446
447 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
448 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
449 // FIXME: Type and constness constraints could be lifted, but we have to
450 // watch code size carefully. We should consider xor instead of
451 // sub/add when we decide to do that.
452 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
453 if (TrueVal->getType() == Ty) {
454 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
455 ConstantInt *C1 = NULL, *C2 = NULL;
456 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
457 C1 = dyn_cast<ConstantInt>(TrueVal);
458 C2 = dyn_cast<ConstantInt>(FalseVal);
459 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
460 C1 = dyn_cast<ConstantInt>(FalseVal);
461 C2 = dyn_cast<ConstantInt>(TrueVal);
462 }
463 if (C1 && C2) {
464 // This shift results in either -1 or 0.
465 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
466
467 // Check if we can express the operation with a single or.
468 if (C2->isAllOnesValue())
469 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
470
471 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
472 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
473 }
474 }
475 }
476 }
477
478 // If we have an equality comparison then we know the value in one of the
479 // arms of the select. See if substituting this value into the arm and
480 // simplifying the result yields the same value as the other arm.
481 if (Pred == ICmpInst::ICMP_EQ) {
482 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) == TrueVal ||
483 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) == TrueVal)
484 return ReplaceInstUsesWith(SI, FalseVal);
485 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) == FalseVal ||
486 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) == FalseVal)
487 return ReplaceInstUsesWith(SI, FalseVal);
488 } else if (Pred == ICmpInst::ICMP_NE) {
489 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) == FalseVal ||
490 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) == FalseVal)
491 return ReplaceInstUsesWith(SI, TrueVal);
492 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) == TrueVal ||
493 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) == TrueVal)
494 return ReplaceInstUsesWith(SI, TrueVal);
495 }
496
497 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
498
499 if (isa<Constant>(CmpRHS)) {
500 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
501 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
502 SI.setOperand(1, CmpRHS);
503 Changed = true;
504 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
505 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
506 SI.setOperand(2, CmpRHS);
507 Changed = true;
508 }
509 }
510
511 return Changed ? &SI : 0;
512 }
513
514
515 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
516 /// PHI node (but the two may be in different blocks). See if the true/false
517 /// values (V) are live in all of the predecessor blocks of the PHI. For
518 /// example, cases like this cannot be mapped:
519 ///
520 /// X = phi [ C1, BB1], [C2, BB2]
521 /// Y = add
522 /// Z = select X, Y, 0
523 ///
524 /// because Y is not live in BB1/BB2.
525 ///
CanSelectOperandBeMappingIntoPredBlock(const Value * V,const SelectInst & SI)526 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
527 const SelectInst &SI) {
528 // If the value is a non-instruction value like a constant or argument, it
529 // can always be mapped.
530 const Instruction *I = dyn_cast<Instruction>(V);
531 if (I == 0) return true;
532
533 // If V is a PHI node defined in the same block as the condition PHI, we can
534 // map the arguments.
535 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
536
537 if (const PHINode *VP = dyn_cast<PHINode>(I))
538 if (VP->getParent() == CondPHI->getParent())
539 return true;
540
541 // Otherwise, if the PHI and select are defined in the same block and if V is
542 // defined in a different block, then we can transform it.
543 if (SI.getParent() == CondPHI->getParent() &&
544 I->getParent() != CondPHI->getParent())
545 return true;
546
547 // Otherwise we have a 'hard' case and we can't tell without doing more
548 // detailed dominator based analysis, punt.
549 return false;
550 }
551
552 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
553 /// SPF2(SPF1(A, B), C)
FoldSPFofSPF(Instruction * Inner,SelectPatternFlavor SPF1,Value * A,Value * B,Instruction & Outer,SelectPatternFlavor SPF2,Value * C)554 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
555 SelectPatternFlavor SPF1,
556 Value *A, Value *B,
557 Instruction &Outer,
558 SelectPatternFlavor SPF2, Value *C) {
559 if (C == A || C == B) {
560 // MAX(MAX(A, B), B) -> MAX(A, B)
561 // MIN(MIN(a, b), a) -> MIN(a, b)
562 if (SPF1 == SPF2)
563 return ReplaceInstUsesWith(Outer, Inner);
564
565 // MAX(MIN(a, b), a) -> a
566 // MIN(MAX(a, b), a) -> a
567 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
568 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
569 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
570 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
571 return ReplaceInstUsesWith(Outer, C);
572 }
573
574 // TODO: MIN(MIN(A, 23), 97)
575 return 0;
576 }
577
578
579 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
580 /// both be) and we have an icmp instruction with zero, and we have an 'and'
581 /// with the non-constant value and a power of two we can turn the select
582 /// into a shift on the result of the 'and'.
foldSelectICmpAnd(const SelectInst & SI,ConstantInt * TrueVal,ConstantInt * FalseVal,InstCombiner::BuilderTy * Builder)583 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
584 ConstantInt *FalseVal,
585 InstCombiner::BuilderTy *Builder) {
586 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
587 if (!IC || !IC->isEquality())
588 return 0;
589
590 if (!match(IC->getOperand(1), m_Zero()))
591 return 0;
592
593 ConstantInt *AndRHS;
594 Value *LHS = IC->getOperand(0);
595 if (LHS->getType() != SI.getType() ||
596 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
597 return 0;
598
599 // If both select arms are non-zero see if we have a select of the form
600 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
601 // for 'x ? 2^n : 0' and fix the thing up at the end.
602 ConstantInt *Offset = 0;
603 if (!TrueVal->isZero() && !FalseVal->isZero()) {
604 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
605 Offset = FalseVal;
606 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
607 Offset = TrueVal;
608 else
609 return 0;
610
611 // Adjust TrueVal and FalseVal to the offset.
612 TrueVal = ConstantInt::get(Builder->getContext(),
613 TrueVal->getValue() - Offset->getValue());
614 FalseVal = ConstantInt::get(Builder->getContext(),
615 FalseVal->getValue() - Offset->getValue());
616 }
617
618 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
619 if (!AndRHS->getValue().isPowerOf2() ||
620 (!TrueVal->getValue().isPowerOf2() &&
621 !FalseVal->getValue().isPowerOf2()))
622 return 0;
623
624 // Determine which shift is needed to transform result of the 'and' into the
625 // desired result.
626 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
627 unsigned ValZeros = ValC->getValue().logBase2();
628 unsigned AndZeros = AndRHS->getValue().logBase2();
629
630 Value *V = LHS;
631 if (ValZeros > AndZeros)
632 V = Builder->CreateShl(V, ValZeros - AndZeros);
633 else if (ValZeros < AndZeros)
634 V = Builder->CreateLShr(V, AndZeros - ValZeros);
635
636 // Okay, now we know that everything is set up, we just don't know whether we
637 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
638 bool ShouldNotVal = !TrueVal->isZero();
639 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
640 if (ShouldNotVal)
641 V = Builder->CreateXor(V, ValC);
642
643 // Apply an offset if needed.
644 if (Offset)
645 V = Builder->CreateAdd(V, Offset);
646 return V;
647 }
648
visitSelectInst(SelectInst & SI)649 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
650 Value *CondVal = SI.getCondition();
651 Value *TrueVal = SI.getTrueValue();
652 Value *FalseVal = SI.getFalseValue();
653
654 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
655 return ReplaceInstUsesWith(SI, V);
656
657 if (SI.getType()->isIntegerTy(1)) {
658 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
659 if (C->getZExtValue()) {
660 // Change: A = select B, true, C --> A = or B, C
661 return BinaryOperator::CreateOr(CondVal, FalseVal);
662 }
663 // Change: A = select B, false, C --> A = and !B, C
664 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
665 return BinaryOperator::CreateAnd(NotCond, FalseVal);
666 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
667 if (C->getZExtValue() == false) {
668 // Change: A = select B, C, false --> A = and B, C
669 return BinaryOperator::CreateAnd(CondVal, TrueVal);
670 }
671 // Change: A = select B, C, true --> A = or !B, C
672 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
673 return BinaryOperator::CreateOr(NotCond, TrueVal);
674 }
675
676 // select a, b, a -> a&b
677 // select a, a, b -> a|b
678 if (CondVal == TrueVal)
679 return BinaryOperator::CreateOr(CondVal, FalseVal);
680 else if (CondVal == FalseVal)
681 return BinaryOperator::CreateAnd(CondVal, TrueVal);
682 }
683
684 // Selecting between two integer constants?
685 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
686 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
687 // select C, 1, 0 -> zext C to int
688 if (FalseValC->isZero() && TrueValC->getValue() == 1)
689 return new ZExtInst(CondVal, SI.getType());
690
691 // select C, -1, 0 -> sext C to int
692 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
693 return new SExtInst(CondVal, SI.getType());
694
695 // select C, 0, 1 -> zext !C to int
696 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
697 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
698 return new ZExtInst(NotCond, SI.getType());
699 }
700
701 // select C, 0, -1 -> sext !C to int
702 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
703 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
704 return new SExtInst(NotCond, SI.getType());
705 }
706
707 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
708 return ReplaceInstUsesWith(SI, V);
709 }
710
711 // See if we are selecting two values based on a comparison of the two values.
712 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
713 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
714 // Transform (X == Y) ? X : Y -> Y
715 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
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, FalseVal);
725 }
726 // Transform (X une Y) ? X : Y -> X
727 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
728 // This is not safe in general for floating point:
729 // consider X== -0, Y== +0.
730 // It becomes safe if either operand is a nonzero constant.
731 ConstantFP *CFPt, *CFPf;
732 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
733 !CFPt->getValueAPF().isZero()) ||
734 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
735 !CFPf->getValueAPF().isZero()))
736 return ReplaceInstUsesWith(SI, TrueVal);
737 }
738 // NOTE: if we wanted to, this is where to detect MIN/MAX
739
740 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
741 // Transform (X == Y) ? Y : X -> X
742 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
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, FalseVal);
752 }
753 // Transform (X une Y) ? Y : X -> Y
754 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
755 // This is not safe in general for floating point:
756 // consider X== -0, Y== +0.
757 // It becomes safe if either operand is a nonzero constant.
758 ConstantFP *CFPt, *CFPf;
759 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
760 !CFPt->getValueAPF().isZero()) ||
761 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
762 !CFPf->getValueAPF().isZero()))
763 return ReplaceInstUsesWith(SI, TrueVal);
764 }
765 // NOTE: if we wanted to, this is where to detect MIN/MAX
766 }
767 // NOTE: if we wanted to, this is where to detect ABS
768 }
769
770 // See if we are selecting two values based on a comparison of the two values.
771 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
772 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
773 return Result;
774
775 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
776 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
777 if (TI->hasOneUse() && FI->hasOneUse()) {
778 Instruction *AddOp = 0, *SubOp = 0;
779
780 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
781 if (TI->getOpcode() == FI->getOpcode())
782 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
783 return IV;
784
785 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
786 // even legal for FP.
787 if ((TI->getOpcode() == Instruction::Sub &&
788 FI->getOpcode() == Instruction::Add) ||
789 (TI->getOpcode() == Instruction::FSub &&
790 FI->getOpcode() == Instruction::FAdd)) {
791 AddOp = FI; SubOp = TI;
792 } else if ((FI->getOpcode() == Instruction::Sub &&
793 TI->getOpcode() == Instruction::Add) ||
794 (FI->getOpcode() == Instruction::FSub &&
795 TI->getOpcode() == Instruction::FAdd)) {
796 AddOp = TI; SubOp = FI;
797 }
798
799 if (AddOp) {
800 Value *OtherAddOp = 0;
801 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
802 OtherAddOp = AddOp->getOperand(1);
803 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
804 OtherAddOp = AddOp->getOperand(0);
805 }
806
807 if (OtherAddOp) {
808 // So at this point we know we have (Y -> OtherAddOp):
809 // select C, (add X, Y), (sub X, Z)
810 Value *NegVal; // Compute -Z
811 if (SI.getType()->isFPOrFPVectorTy()) {
812 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
813 } else {
814 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
815 }
816
817 Value *NewTrueOp = OtherAddOp;
818 Value *NewFalseOp = NegVal;
819 if (AddOp != TI)
820 std::swap(NewTrueOp, NewFalseOp);
821 Value *NewSel =
822 Builder->CreateSelect(CondVal, NewTrueOp,
823 NewFalseOp, SI.getName() + ".p");
824
825 if (SI.getType()->isFPOrFPVectorTy())
826 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
827 else
828 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
829 }
830 }
831 }
832
833 // See if we can fold the select into one of our operands.
834 if (SI.getType()->isIntegerTy()) {
835 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
836 return FoldI;
837
838 // MAX(MAX(a, b), a) -> MAX(a, b)
839 // MIN(MIN(a, b), a) -> MIN(a, b)
840 // MAX(MIN(a, b), a) -> a
841 // MIN(MAX(a, b), a) -> a
842 Value *LHS, *RHS, *LHS2, *RHS2;
843 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
844 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
845 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
846 SI, SPF, RHS))
847 return R;
848 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
849 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
850 SI, SPF, LHS))
851 return R;
852 }
853
854 // TODO.
855 // ABS(-X) -> ABS(X)
856 // ABS(ABS(X)) -> ABS(X)
857 }
858
859 // See if we can fold the select into a phi node if the condition is a select.
860 if (isa<PHINode>(SI.getCondition()))
861 // The true/false values have to be live in the PHI predecessor's blocks.
862 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
863 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
864 if (Instruction *NV = FoldOpIntoPhi(SI))
865 return NV;
866
867 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
868 if (TrueSI->getCondition() == CondVal) {
869 SI.setOperand(1, TrueSI->getTrueValue());
870 return &SI;
871 }
872 }
873 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
874 if (FalseSI->getCondition() == CondVal) {
875 SI.setOperand(2, FalseSI->getFalseValue());
876 return &SI;
877 }
878 }
879
880 if (BinaryOperator::isNot(CondVal)) {
881 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
882 SI.setOperand(1, FalseVal);
883 SI.setOperand(2, TrueVal);
884 return &SI;
885 }
886
887 return 0;
888 }
889