blob: e727b2c592db31da7f0f42703d2d990d202ed040 [file] [log] [blame]
Chris Lattner1c22c802010-01-05 06:05:07 +00001//===- InstCombineSelect.cpp ----------------------------------------------===//
Chris Lattnerc6334b92010-01-05 06:03:12 +00002//
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//
Chris Lattner1c22c802010-01-05 06:05:07 +000010// This file implements the visitSelect function.
Chris Lattnerc6334b92010-01-05 06:03:12 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Chris Lattnerc6334b92010-01-05 06:03:12 +000015#include "llvm/Support/PatternMatch.h"
Eli Friedman74703252011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner04754262010-04-20 05:32:14 +000017#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerc6334b92010-01-05 06:03:12 +000018using namespace llvm;
19using 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.
24static SelectPatternFlavor
25MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
26 SelectInst *SI = dyn_cast<SelectInst>(V);
27 if (SI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000028
Chris Lattnerc6334b92010-01-05 06:03:12 +000029 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
30 if (ICI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000031
Chris Lattnerc6334b92010-01-05 06:03:12 +000032 LHS = ICI->getOperand(0);
33 RHS = ICI->getOperand(1);
Tobias Grosser8d088bd2011-01-07 21:33:13 +000034
35 // (icmp X, Y) ? X : Y
Chris Lattnerc6334b92010-01-05 06:03:12 +000036 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 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000050
51 // (icmp X, Y) ? Y : X
Chris Lattnerc6334b92010-01-05 06:03:12 +000052 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 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000066
Chris Lattnerc6334b92010-01-05 06:03:12 +000067 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
Tobias Grosser8d088bd2011-01-07 21:33:13 +000068
Chris Lattnerc6334b92010-01-05 06:03:12 +000069 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///
84static 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.
104static 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.
124Instruction *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.
Eli Friedman976e7e12011-05-18 18:10:28 +0000137 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
138 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattnerc6334b92010-01-05 06:03:12 +0000140 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.
Eli Friedman976e7e12011-05-18 18:10:28 +0000177 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
178 OtherOpF, SI.getName()+".v");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000179
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");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000187}
188
189static 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;
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000196 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
197 return false;
198 return C1I->isOne() || C1I->isAllOnesValue() ||
199 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattnerc6334b92010-01-05 06:03:12 +0000200}
201
202/// FoldSelectIntoOp - Try fold the select into one of the operands to
203/// facilitate further optimization.
204Instruction *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;
Nick Lewycky675619c2011-03-27 19:51:23 +0000215 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000216 OpToFold = 2;
217 }
218
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
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000223 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000224 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman976e7e12011-05-18 18:10:28 +0000225 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000226 NewSel->takeName(TVI);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000227 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky675619c2011-03-27 19:51:23 +0000228 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
229 FalseVal, NewSel);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000230 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());
235 }
236 return BO;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000237 }
238 }
239 }
240 }
241 }
242
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;
Nick Lewycky675619c2011-03-27 19:51:23 +0000250 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000251 OpToFold = 2;
252 }
253
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
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000258 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000259 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman976e7e12011-05-18 18:10:28 +0000260 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000261 NewSel->takeName(FVI);
Nick Lewycky675619c2011-03-27 19:51:23 +0000262 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
263 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
264 TrueVal, NewSel);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000265 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());
270 }
271 return BO;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000272 }
273 }
274 }
275 }
276 }
277
278 return 0;
279}
280
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000281/// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
282/// replaced with RepOp.
283static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Chad Rosieraab8e282011-12-02 01:26:24 +0000284 const TargetData *TD,
285 const TargetLibraryInfo *TLI) {
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000286 // 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)
Chad Rosieraab8e282011-12-02 01:26:24 +0000297 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000298 if (B->getOperand(1) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000299 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000300 }
301
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000302 // Same for CmpInsts.
303 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
304 if (C->getOperand(0) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000305 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
306 TLI);
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000307 if (C->getOperand(1) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000308 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
309 TLI);
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000310 }
311
312 // TODO: We could hand off more cases to instsimplify here.
313
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000314 // If all operands are constant after substituting Op for RepOp then we can
315 // constant fold the instruction.
316 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
317 // Build a list of all constant operands.
318 SmallVector<Constant*, 8> ConstOps;
319 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
320 if (I->getOperand(i) == Op)
321 ConstOps.push_back(CRepOp);
322 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
323 ConstOps.push_back(COp);
324 else
325 break;
326 }
327
328 // All operands were constants, fold it.
Nick Lewycky267236a2011-10-02 09:12:55 +0000329 if (ConstOps.size() == I->getNumOperands()) {
330 if (LoadInst *LI = dyn_cast<LoadInst>(I))
331 if (!LI->isVolatile())
332 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
333
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000334 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Chad Rosieraab8e282011-12-02 01:26:24 +0000335 ConstOps, TD, TLI);
Nick Lewycky267236a2011-10-02 09:12:55 +0000336 }
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000337 }
338
339 return 0;
340}
341
Chris Lattnerc6334b92010-01-05 06:03:12 +0000342/// visitSelectInstWithICmp - Visit a SelectInst that has an
343/// ICmpInst as its first operand.
344///
345Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
346 ICmpInst *ICI) {
347 bool Changed = false;
348 ICmpInst::Predicate Pred = ICI->getPredicate();
349 Value *CmpLHS = ICI->getOperand(0);
350 Value *CmpRHS = ICI->getOperand(1);
351 Value *TrueVal = SI.getTrueValue();
352 Value *FalseVal = SI.getFalseValue();
353
354 // Check cases where the comparison is with a constant that
Tobias Grosseraa2be842011-01-09 16:00:11 +0000355 // can be adjusted to fit the min/max idiom. We may move or edit ICI
356 // here, so make sure the select is the only user.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000357 if (ICI->hasOneUse())
358 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Tobias Grosser46431d72011-01-07 21:33:14 +0000359 // X < MIN ? T : F --> F
360 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
361 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
362 return ReplaceInstUsesWith(SI, FalseVal);
363 // X > MAX ? T : F --> F
364 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
365 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
366 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000367 switch (Pred) {
368 default: break;
369 case ICmpInst::ICMP_ULT:
Tobias Grosser46431d72011-01-07 21:33:14 +0000370 case ICmpInst::ICMP_SLT:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000371 case ICmpInst::ICMP_UGT:
372 case ICmpInst::ICMP_SGT: {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000373 // These transformations only work for selects over integers.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000374 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommelb686eb92011-01-08 10:51:36 +0000375 if (!SelectTy)
376 break;
377
Tobias Grosser46431d72011-01-07 21:33:14 +0000378 Constant *AdjustedRHS;
379 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
380 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
381 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
382 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
383
Chris Lattnerc6334b92010-01-05 06:03:12 +0000384 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosser46431d72011-01-07 21:33:14 +0000385 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattnerc6334b92010-01-05 06:03:12 +0000386 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosser46431d72011-01-07 21:33:14 +0000387 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
388 ; // Nothing to do here. Values match without any sign/zero extension.
389
390 // Types do not match. Instead of calculating this with mixed types
391 // promote all to the larger type. This enables scalar evolution to
392 // analyze this expression.
393 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommelb686eb92011-01-08 10:51:36 +0000394 < SelectTy->getBitWidth()) {
395 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000396
397 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
398 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
399 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
400 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
401 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
402 sextRHS == FalseVal) {
403 CmpLHS = TrueVal;
404 AdjustedRHS = sextRHS;
405 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
406 sextRHS == TrueVal) {
407 CmpLHS = FalseVal;
408 AdjustedRHS = sextRHS;
409 } else if (ICI->isUnsigned()) {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000410 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000411 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
412 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
413 // zext + signed compare cannot be changed:
414 // 0xff <s 0x00, but 0x00ff >s 0x0000
415 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
416 zextRHS == FalseVal) {
417 CmpLHS = TrueVal;
418 AdjustedRHS = zextRHS;
419 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
420 zextRHS == TrueVal) {
421 CmpLHS = FalseVal;
422 AdjustedRHS = zextRHS;
423 } else
424 break;
425 } else
426 break;
427 } else
428 break;
429
430 Pred = ICmpInst::getSwappedPredicate(Pred);
431 CmpRHS = AdjustedRHS;
432 std::swap(FalseVal, TrueVal);
433 ICI->setPredicate(Pred);
434 ICI->setOperand(0, CmpLHS);
435 ICI->setOperand(1, CmpRHS);
436 SI.setOperand(1, TrueVal);
437 SI.setOperand(2, FalseVal);
Tobias Grosseraa2be842011-01-09 16:00:11 +0000438
439 // Move ICI instruction right before the select instruction. Otherwise
440 // the sext/zext value may be defined after the ICI instruction uses it.
441 ICI->moveBefore(&SI);
442
Tobias Grosser46431d72011-01-07 21:33:14 +0000443 Changed = true;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000444 break;
445 }
446 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000447 }
448
Benjamin Kramer1db071f2010-07-08 11:39:10 +0000449 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
450 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
451 // FIXME: Type and constness constraints could be lifted, but we have to
452 // watch code size carefully. We should consider xor instead of
453 // sub/add when we decide to do that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000454 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer1db071f2010-07-08 11:39:10 +0000455 if (TrueVal->getType() == Ty) {
456 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
457 ConstantInt *C1 = NULL, *C2 = NULL;
458 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
459 C1 = dyn_cast<ConstantInt>(TrueVal);
460 C2 = dyn_cast<ConstantInt>(FalseVal);
461 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
462 C1 = dyn_cast<ConstantInt>(FalseVal);
463 C2 = dyn_cast<ConstantInt>(TrueVal);
464 }
465 if (C1 && C2) {
466 // This shift results in either -1 or 0.
467 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
468
469 // Check if we can express the operation with a single or.
470 if (C2->isAllOnesValue())
471 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
472
473 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
474 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
475 }
476 }
477 }
478 }
479
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000480 // If we have an equality comparison then we know the value in one of the
481 // arms of the select. See if substituting this value into the arm and
482 // simplifying the result yields the same value as the other arm.
483 if (Pred == ICmpInst::ICMP_EQ) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000484 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
485 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000486 return ReplaceInstUsesWith(SI, FalseVal);
Chad Rosieraab8e282011-12-02 01:26:24 +0000487 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
488 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
Nick Lewycky11357d42011-10-02 10:37:37 +0000489 return ReplaceInstUsesWith(SI, FalseVal);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000490 } else if (Pred == ICmpInst::ICMP_NE) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000491 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
492 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000493 return ReplaceInstUsesWith(SI, TrueVal);
Chad Rosieraab8e282011-12-02 01:26:24 +0000494 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
495 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
Nick Lewycky11357d42011-10-02 10:37:37 +0000496 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000497 }
Nick Lewycky98cd7502011-03-27 07:30:57 +0000498
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000499 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
500
Nick Lewycky98cd7502011-03-27 07:30:57 +0000501 if (isa<Constant>(CmpRHS)) {
502 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
503 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
504 SI.setOperand(1, CmpRHS);
505 Changed = true;
506 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
507 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
508 SI.setOperand(2, CmpRHS);
509 Changed = true;
510 }
511 }
512
Chris Lattnerc6334b92010-01-05 06:03:12 +0000513 return Changed ? &SI : 0;
514}
515
516
517/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
518/// PHI node (but the two may be in different blocks). See if the true/false
519/// values (V) are live in all of the predecessor blocks of the PHI. For
520/// example, cases like this cannot be mapped:
521///
522/// X = phi [ C1, BB1], [C2, BB2]
523/// Y = add
524/// Z = select X, Y, 0
525///
526/// because Y is not live in BB1/BB2.
527///
528static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
529 const SelectInst &SI) {
530 // If the value is a non-instruction value like a constant or argument, it
531 // can always be mapped.
532 const Instruction *I = dyn_cast<Instruction>(V);
533 if (I == 0) return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000534
Chris Lattnerc6334b92010-01-05 06:03:12 +0000535 // If V is a PHI node defined in the same block as the condition PHI, we can
536 // map the arguments.
537 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000538
Chris Lattnerc6334b92010-01-05 06:03:12 +0000539 if (const PHINode *VP = dyn_cast<PHINode>(I))
540 if (VP->getParent() == CondPHI->getParent())
541 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000542
Chris Lattnerc6334b92010-01-05 06:03:12 +0000543 // Otherwise, if the PHI and select are defined in the same block and if V is
544 // defined in a different block, then we can transform it.
545 if (SI.getParent() == CondPHI->getParent() &&
546 I->getParent() != CondPHI->getParent())
547 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000548
Chris Lattnerc6334b92010-01-05 06:03:12 +0000549 // Otherwise we have a 'hard' case and we can't tell without doing more
550 // detailed dominator based analysis, punt.
551 return false;
552}
553
554/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000555/// SPF2(SPF1(A, B), C)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000556Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
557 SelectPatternFlavor SPF1,
558 Value *A, Value *B,
559 Instruction &Outer,
560 SelectPatternFlavor SPF2, Value *C) {
561 if (C == A || C == B) {
562 // MAX(MAX(A, B), B) -> MAX(A, B)
563 // MIN(MIN(a, b), a) -> MIN(a, b)
564 if (SPF1 == SPF2)
565 return ReplaceInstUsesWith(Outer, Inner);
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000566
Chris Lattnerc6334b92010-01-05 06:03:12 +0000567 // MAX(MIN(a, b), a) -> a
568 // MIN(MAX(a, b), a) -> a
569 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
570 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
571 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
572 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
573 return ReplaceInstUsesWith(Outer, C);
574 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000575
Chris Lattnerc6334b92010-01-05 06:03:12 +0000576 // TODO: MIN(MIN(A, 23), 97)
577 return 0;
578}
579
580
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000581/// foldSelectICmpAnd - If one of the constants is zero (we know they can't
582/// both be) and we have an icmp instruction with zero, and we have an 'and'
583/// with the non-constant value and a power of two we can turn the select
584/// into a shift on the result of the 'and'.
585static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
586 ConstantInt *FalseVal,
587 InstCombiner::BuilderTy *Builder) {
588 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
589 if (!IC || !IC->isEquality())
590 return 0;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000591
Benjamin Kramer6b497252011-03-11 11:37:40 +0000592 if (!match(IC->getOperand(1), m_Zero()))
593 return 0;
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000594
595 ConstantInt *AndRHS;
596 Value *LHS = IC->getOperand(0);
597 if (LHS->getType() != SI.getType() ||
598 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
599 return 0;
600
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000601 // If both select arms are non-zero see if we have a select of the form
602 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
603 // for 'x ? 2^n : 0' and fix the thing up at the end.
604 ConstantInt *Offset = 0;
605 if (!TrueVal->isZero() && !FalseVal->isZero()) {
606 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
607 Offset = FalseVal;
608 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
609 Offset = TrueVal;
610 else
611 return 0;
612
613 // Adjust TrueVal and FalseVal to the offset.
614 TrueVal = ConstantInt::get(Builder->getContext(),
615 TrueVal->getValue() - Offset->getValue());
616 FalseVal = ConstantInt::get(Builder->getContext(),
617 FalseVal->getValue() - Offset->getValue());
618 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000619
620 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
621 if (!AndRHS->getValue().isPowerOf2() ||
622 (!TrueVal->getValue().isPowerOf2() &&
623 !FalseVal->getValue().isPowerOf2()))
624 return 0;
625
626 // Determine which shift is needed to transform result of the 'and' into the
627 // desired result.
628 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
629 unsigned ValZeros = ValC->getValue().logBase2();
630 unsigned AndZeros = AndRHS->getValue().logBase2();
631
632 Value *V = LHS;
633 if (ValZeros > AndZeros)
634 V = Builder->CreateShl(V, ValZeros - AndZeros);
635 else if (ValZeros < AndZeros)
636 V = Builder->CreateLShr(V, AndZeros - ValZeros);
637
638 // Okay, now we know that everything is set up, we just don't know whether we
639 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
640 bool ShouldNotVal = !TrueVal->isZero();
641 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
642 if (ShouldNotVal)
643 V = Builder->CreateXor(V, ValC);
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000644
645 // Apply an offset if needed.
646 if (Offset)
647 V = Builder->CreateAdd(V, Offset);
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000648 return V;
649}
Chris Lattnerc6334b92010-01-05 06:03:12 +0000650
651Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
652 Value *CondVal = SI.getCondition();
653 Value *TrueVal = SI.getTrueValue();
654 Value *FalseVal = SI.getFalseValue();
655
Chris Lattner04754262010-04-20 05:32:14 +0000656 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
657 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000658
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000659 if (SI.getType()->isIntegerTy(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000660 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
661 if (C->getZExtValue()) {
662 // Change: A = select B, true, C --> A = or B, C
663 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000664 }
Chris Lattner04754262010-04-20 05:32:14 +0000665 // Change: A = select B, false, C --> A = and !B, C
Eli Friedmane87ca452011-05-18 17:31:55 +0000666 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattner04754262010-04-20 05:32:14 +0000667 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000668 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
669 if (C->getZExtValue() == false) {
670 // Change: A = select B, C, false --> A = and B, C
671 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000672 }
Chris Lattner04754262010-04-20 05:32:14 +0000673 // Change: A = select B, C, true --> A = or !B, C
Eli Friedmane87ca452011-05-18 17:31:55 +0000674 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattner04754262010-04-20 05:32:14 +0000675 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000676 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000677
Chris Lattnerc6334b92010-01-05 06:03:12 +0000678 // select a, b, a -> a&b
679 // select a, a, b -> a|b
680 if (CondVal == TrueVal)
681 return BinaryOperator::CreateOr(CondVal, FalseVal);
682 else if (CondVal == FalseVal)
683 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooper4e5a1ab2011-12-15 00:56:45 +0000684
685 // select a, ~a, b -> (~a)&b
686 // select a, b, ~a -> (~a)|b
687 if (match(TrueVal, m_Not(m_Specific(CondVal))))
688 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
689 else if (match(FalseVal, m_Not(m_Specific(CondVal))))
690 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000691 }
692
693 // Selecting between two integer constants?
694 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
695 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
696 // select C, 1, 0 -> zext C to int
Chris Lattnerabb992d2010-01-24 00:09:49 +0000697 if (FalseValC->isZero() && TrueValC->getValue() == 1)
698 return new ZExtInst(CondVal, SI.getType());
699
700 // select C, -1, 0 -> sext C to int
701 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
702 return new SExtInst(CondVal, SI.getType());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000703
Chris Lattnerabb992d2010-01-24 00:09:49 +0000704 // select C, 0, 1 -> zext !C to int
705 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
706 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
707 return new ZExtInst(NotCond, SI.getType());
Chris Lattnerc6334b92010-01-05 06:03:12 +0000708 }
709
Chris Lattnerabb992d2010-01-24 00:09:49 +0000710 // select C, 0, -1 -> sext !C to int
711 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
712 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
713 return new SExtInst(NotCond, SI.getType());
714 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000715
716 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
717 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000718 }
719
720 // See if we are selecting two values based on a comparison of the two values.
721 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
722 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
723 // Transform (X == Y) ? X : Y -> Y
724 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000725 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000726 // consider X== -0, Y== +0.
727 // It becomes safe if either operand is a nonzero constant.
728 ConstantFP *CFPt, *CFPf;
729 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
730 !CFPt->getValueAPF().isZero()) ||
731 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
732 !CFPf->getValueAPF().isZero()))
733 return ReplaceInstUsesWith(SI, FalseVal);
734 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000735 // Transform (X une Y) ? X : Y -> X
736 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000737 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000738 // consider X== -0, Y== +0.
739 // It becomes safe if either operand is a nonzero constant.
740 ConstantFP *CFPt, *CFPf;
741 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
742 !CFPt->getValueAPF().isZero()) ||
743 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
744 !CFPf->getValueAPF().isZero()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000745 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman21dc20c2010-02-23 17:17:57 +0000746 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000747 // NOTE: if we wanted to, this is where to detect MIN/MAX
748
749 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
750 // Transform (X == Y) ? Y : X -> X
751 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000752 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000753 // consider X== -0, Y== +0.
754 // It becomes safe if either operand is a nonzero constant.
755 ConstantFP *CFPt, *CFPf;
756 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
757 !CFPt->getValueAPF().isZero()) ||
758 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
759 !CFPf->getValueAPF().isZero()))
760 return ReplaceInstUsesWith(SI, FalseVal);
761 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000762 // Transform (X une Y) ? Y : X -> Y
763 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000764 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000765 // consider X== -0, Y== +0.
766 // It becomes safe if either operand is a nonzero constant.
767 ConstantFP *CFPt, *CFPf;
768 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
769 !CFPt->getValueAPF().isZero()) ||
770 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
771 !CFPf->getValueAPF().isZero()))
772 return ReplaceInstUsesWith(SI, TrueVal);
773 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000774 // NOTE: if we wanted to, this is where to detect MIN/MAX
775 }
776 // NOTE: if we wanted to, this is where to detect ABS
777 }
778
779 // See if we are selecting two values based on a comparison of the two values.
780 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
781 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
782 return Result;
783
784 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
785 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
786 if (TI->hasOneUse() && FI->hasOneUse()) {
787 Instruction *AddOp = 0, *SubOp = 0;
788
789 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
790 if (TI->getOpcode() == FI->getOpcode())
791 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
792 return IV;
793
794 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
795 // even legal for FP.
796 if ((TI->getOpcode() == Instruction::Sub &&
797 FI->getOpcode() == Instruction::Add) ||
798 (TI->getOpcode() == Instruction::FSub &&
799 FI->getOpcode() == Instruction::FAdd)) {
800 AddOp = FI; SubOp = TI;
801 } else if ((FI->getOpcode() == Instruction::Sub &&
802 TI->getOpcode() == Instruction::Add) ||
803 (FI->getOpcode() == Instruction::FSub &&
804 TI->getOpcode() == Instruction::FAdd)) {
805 AddOp = TI; SubOp = FI;
806 }
807
808 if (AddOp) {
809 Value *OtherAddOp = 0;
810 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
811 OtherAddOp = AddOp->getOperand(1);
812 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
813 OtherAddOp = AddOp->getOperand(0);
814 }
815
816 if (OtherAddOp) {
817 // So at this point we know we have (Y -> OtherAddOp):
818 // select C, (add X, Y), (sub X, Z)
819 Value *NegVal; // Compute -Z
Eli Friedman00805fa2011-06-23 20:40:23 +0000820 if (SI.getType()->isFPOrFPVectorTy()) {
Eli Friedman1eca76a2011-05-18 17:58:37 +0000821 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
Chris Lattnerc6334b92010-01-05 06:03:12 +0000822 } else {
Eli Friedman1eca76a2011-05-18 17:58:37 +0000823 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
Chris Lattnerc6334b92010-01-05 06:03:12 +0000824 }
825
826 Value *NewTrueOp = OtherAddOp;
827 Value *NewFalseOp = NegVal;
828 if (AddOp != TI)
829 std::swap(NewTrueOp, NewFalseOp);
Eli Friedman1eca76a2011-05-18 17:58:37 +0000830 Value *NewSel =
831 Builder->CreateSelect(CondVal, NewTrueOp,
832 NewFalseOp, SI.getName() + ".p");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000833
Eli Friedman00805fa2011-06-23 20:40:23 +0000834 if (SI.getType()->isFPOrFPVectorTy())
Dale Johannesenf514f522010-10-27 23:45:18 +0000835 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
836 else
837 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000838 }
839 }
840 }
841
842 // See if we can fold the select into one of our operands.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000843 if (SI.getType()->isIntegerTy()) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000844 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
845 return FoldI;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000846
Chris Lattnerc6334b92010-01-05 06:03:12 +0000847 // MAX(MAX(a, b), a) -> MAX(a, b)
848 // MIN(MIN(a, b), a) -> MIN(a, b)
849 // MAX(MIN(a, b), a) -> a
850 // MIN(MAX(a, b), a) -> a
851 Value *LHS, *RHS, *LHS2, *RHS2;
852 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
853 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
854 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
855 SI, SPF, RHS))
856 return R;
857 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
858 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
859 SI, SPF, LHS))
860 return R;
861 }
862
863 // TODO.
864 // ABS(-X) -> ABS(X)
865 // ABS(ABS(X)) -> ABS(X)
866 }
867
868 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000869 if (isa<PHINode>(SI.getCondition()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000870 // The true/false values have to be live in the PHI predecessor's blocks.
871 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
872 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
873 if (Instruction *NV = FoldOpIntoPhi(SI))
874 return NV;
875
Nick Lewyckydf3bfae2011-01-28 03:28:10 +0000876 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
877 if (TrueSI->getCondition() == CondVal) {
878 SI.setOperand(1, TrueSI->getTrueValue());
879 return &SI;
880 }
881 }
882 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
883 if (FalseSI->getCondition() == CondVal) {
884 SI.setOperand(2, FalseSI->getFalseValue());
885 return &SI;
886 }
887 }
888
Chris Lattnerc6334b92010-01-05 06:03:12 +0000889 if (BinaryOperator::isNot(CondVal)) {
890 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
891 SI.setOperand(1, FalseVal);
892 SI.setOperand(2, TrueVal);
893 return &SI;
894 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000895
896 return 0;
897}