blob: 8e2a7d5ce6588e6cf7319f36938e427f382adb20 [file] [log] [blame]
Chris Lattner1e7b7b52010-01-05 06:05:07 +00001//===- InstCombineSelect.cpp ----------------------------------------------===//
Chris Lattner8f771cb2010-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 Lattner1e7b7b52010-01-05 06:05:07 +000010// This file implements the visitSelect function.
Chris Lattner8f771cb2010-01-05 06:03:12 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000018using namespace llvm;
19using namespace PatternMatch;
20
Chandler Carruth964daaa2014-04-22 02:55:47 +000021#define DEBUG_TYPE "instcombine"
22
Chris Lattner8f771cb2010-01-05 06:03:12 +000023/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
24/// returning the kind and providing the out parameter results if we
25/// successfully match.
26static SelectPatternFlavor
27MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
28 SelectInst *SI = dyn_cast<SelectInst>(V);
Craig Topperf40110f2014-04-25 05:29:35 +000029 if (!SI) return SPF_UNKNOWN;
Tobias Grosser411e6ee2011-01-07 21:33:13 +000030
Chris Lattner8f771cb2010-01-05 06:03:12 +000031 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +000032 if (!ICI) return SPF_UNKNOWN;
Tobias Grosser411e6ee2011-01-07 21:33:13 +000033
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +000034 ICmpInst::Predicate Pred = ICI->getPredicate();
35 Value *CmpLHS = ICI->getOperand(0);
36 Value *CmpRHS = ICI->getOperand(1);
37 Value *TrueVal = SI->getTrueValue();
38 Value *FalseVal = SI->getFalseValue();
39
40 LHS = CmpLHS;
41 RHS = CmpRHS;
Tobias Grosser411e6ee2011-01-07 21:33:13 +000042
43 // (icmp X, Y) ? X : Y
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +000044 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
45 switch (Pred) {
Chris Lattner8f771cb2010-01-05 06:03:12 +000046 default: return SPF_UNKNOWN; // Equality.
47 case ICmpInst::ICMP_UGT:
48 case ICmpInst::ICMP_UGE: return SPF_UMAX;
49 case ICmpInst::ICMP_SGT:
50 case ICmpInst::ICMP_SGE: return SPF_SMAX;
51 case ICmpInst::ICMP_ULT:
52 case ICmpInst::ICMP_ULE: return SPF_UMIN;
53 case ICmpInst::ICMP_SLT:
54 case ICmpInst::ICMP_SLE: return SPF_SMIN;
55 }
56 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +000057
58 // (icmp X, Y) ? Y : X
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +000059 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
60 switch (Pred) {
61 default: return SPF_UNKNOWN; // Equality.
62 case ICmpInst::ICMP_UGT:
63 case ICmpInst::ICMP_UGE: return SPF_UMIN;
64 case ICmpInst::ICMP_SGT:
65 case ICmpInst::ICMP_SGE: return SPF_SMIN;
66 case ICmpInst::ICMP_ULT:
67 case ICmpInst::ICMP_ULE: return SPF_UMAX;
68 case ICmpInst::ICMP_SLT:
69 case ICmpInst::ICMP_SLE: return SPF_SMAX;
70 }
71 }
72
73 if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
74 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
75 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
76
77 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
78 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
79 if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
80 return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
81 }
82
83 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
84 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
85 if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
86 return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
87 }
Chris Lattner8f771cb2010-01-05 06:03:12 +000088 }
89 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +000090
Chris Lattner8f771cb2010-01-05 06:03:12 +000091 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
Tobias Grosser411e6ee2011-01-07 21:33:13 +000092
Chris Lattner8f771cb2010-01-05 06:03:12 +000093 return SPF_UNKNOWN;
94}
95
96
97/// GetSelectFoldableOperands - We want to turn code that looks like this:
98/// %C = or %A, %B
99/// %D = select %cond, %C, %A
100/// into:
101/// %C = select %cond, %B, 0
102/// %D = or %A, %C
103///
104/// Assuming that the specified instruction is an operand to the select, return
105/// a bitmask indicating which operands of this instruction are foldable if they
106/// equal the other incoming value of the select.
107///
108static unsigned GetSelectFoldableOperands(Instruction *I) {
109 switch (I->getOpcode()) {
110 case Instruction::Add:
111 case Instruction::Mul:
112 case Instruction::And:
113 case Instruction::Or:
114 case Instruction::Xor:
115 return 3; // Can fold through either operand.
116 case Instruction::Sub: // Can only fold on the amount subtracted.
117 case Instruction::Shl: // Can only fold on the shift amount.
118 case Instruction::LShr:
119 case Instruction::AShr:
120 return 1;
121 default:
122 return 0; // Cannot fold
123 }
124}
125
126/// GetSelectFoldableConstant - For the same transformation as the previous
127/// function, return the identity constant that goes into the select.
128static Constant *GetSelectFoldableConstant(Instruction *I) {
129 switch (I->getOpcode()) {
130 default: llvm_unreachable("This cannot happen!");
131 case Instruction::Add:
132 case Instruction::Sub:
133 case Instruction::Or:
134 case Instruction::Xor:
135 case Instruction::Shl:
136 case Instruction::LShr:
137 case Instruction::AShr:
138 return Constant::getNullValue(I->getType());
139 case Instruction::And:
140 return Constant::getAllOnesValue(I->getType());
141 case Instruction::Mul:
142 return ConstantInt::get(I->getType(), 1);
143 }
144}
145
146/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
147/// have the same opcode and only one use each. Try to simplify this.
148Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
149 Instruction *FI) {
150 if (TI->getNumOperands() == 1) {
151 // If this is a non-volatile load or a cast from the same type,
152 // merge.
153 if (TI->isCast()) {
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000154 Type *FIOpndTy = FI->getOperand(0)->getType();
155 if (TI->getOperand(0)->getType() != FIOpndTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000156 return nullptr;
Nadav Rotem4e50efe2012-06-07 20:28:57 +0000157 // The select condition may be a vector. We may only change the operand
158 // type if the vector width remains the same (and matches the condition).
159 Type *CondTy = SI.getCondition()->getType();
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000160 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
161 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +0000162 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000163 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000164 return nullptr; // unknown unary op.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000165 }
166
167 // Fold this by inserting a select from the input values.
Eli Friedman2fd66442011-05-18 18:10:28 +0000168 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
169 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000170 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000171 TI->getType());
172 }
173
174 // Only handle binary operators here.
175 if (!isa<BinaryOperator>(TI))
Craig Topperf40110f2014-04-25 05:29:35 +0000176 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000177
178 // Figure out if the operations have any operands in common.
179 Value *MatchOp, *OtherOpT, *OtherOpF;
180 bool MatchIsOpZero;
181 if (TI->getOperand(0) == FI->getOperand(0)) {
182 MatchOp = TI->getOperand(0);
183 OtherOpT = TI->getOperand(1);
184 OtherOpF = FI->getOperand(1);
185 MatchIsOpZero = true;
186 } else if (TI->getOperand(1) == FI->getOperand(1)) {
187 MatchOp = TI->getOperand(1);
188 OtherOpT = TI->getOperand(0);
189 OtherOpF = FI->getOperand(0);
190 MatchIsOpZero = false;
191 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000192 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000193 } else if (TI->getOperand(0) == FI->getOperand(1)) {
194 MatchOp = TI->getOperand(0);
195 OtherOpT = TI->getOperand(1);
196 OtherOpF = FI->getOperand(0);
197 MatchIsOpZero = true;
198 } else if (TI->getOperand(1) == FI->getOperand(0)) {
199 MatchOp = TI->getOperand(1);
200 OtherOpT = TI->getOperand(0);
201 OtherOpF = FI->getOperand(1);
202 MatchIsOpZero = true;
203 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000204 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000205 }
206
207 // If we reach here, they do have operations in common.
Eli Friedman2fd66442011-05-18 18:10:28 +0000208 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
209 OtherOpF, SI.getName()+".v");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000210
211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
212 if (MatchIsOpZero)
213 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
214 else
215 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
216 }
217 llvm_unreachable("Shouldn't get here");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000218}
219
220static bool isSelect01(Constant *C1, Constant *C2) {
221 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
222 if (!C1I)
223 return false;
224 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
225 if (!C2I)
226 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000227 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
228 return false;
229 return C1I->isOne() || C1I->isAllOnesValue() ||
230 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000231}
232
233/// FoldSelectIntoOp - Try fold the select into one of the operands to
234/// facilitate further optimization.
235Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
236 Value *FalseVal) {
237 // See the comment above GetSelectFoldableOperands for a description of the
238 // transformation we are doing here.
239 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
240 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
241 !isa<Constant>(FalseVal)) {
242 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
243 unsigned OpToFold = 0;
244 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
245 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000246 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000247 OpToFold = 2;
248 }
249
250 if (OpToFold) {
251 Constant *C = GetSelectFoldableConstant(TVI);
252 Value *OOp = TVI->getOperand(2-OpToFold);
253 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000254 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000255 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000256 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000257 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000258 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000259 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
260 FalseVal, NewSel);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000261 if (isa<PossiblyExactOperator>(BO))
262 BO->setIsExact(TVI_BO->isExact());
263 if (isa<OverflowingBinaryOperator>(BO)) {
264 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
265 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
266 }
267 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000268 }
269 }
270 }
271 }
272 }
273
274 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
275 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
276 !isa<Constant>(TrueVal)) {
277 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
278 unsigned OpToFold = 0;
279 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
280 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000281 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000282 OpToFold = 2;
283 }
284
285 if (OpToFold) {
286 Constant *C = GetSelectFoldableConstant(FVI);
287 Value *OOp = FVI->getOperand(2-OpToFold);
288 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000289 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000290 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000291 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000292 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000293 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
294 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
295 TrueVal, NewSel);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000296 if (isa<PossiblyExactOperator>(BO))
297 BO->setIsExact(FVI_BO->isExact());
298 if (isa<OverflowingBinaryOperator>(BO)) {
299 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
300 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
301 }
302 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000303 }
304 }
305 }
306 }
307 }
308
Craig Topperf40110f2014-04-25 05:29:35 +0000309 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000310}
311
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000312/// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
313/// replaced with RepOp.
314static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000315 const DataLayout *TD,
Hal Finkel60db0582014-09-07 18:57:58 +0000316 const TargetLibraryInfo *TLI,
317 DominatorTree *DT,
318 AssumptionTracker *AT) {
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000319 // Trivial replacement.
320 if (V == Op)
321 return RepOp;
322
323 Instruction *I = dyn_cast<Instruction>(V);
324 if (!I)
Craig Topperf40110f2014-04-25 05:29:35 +0000325 return nullptr;
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000326
327 // If this is a binary operator, try to simplify it with the replaced op.
328 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
329 if (B->getOperand(0) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000330 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000331 if (B->getOperand(1) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000332 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000333 }
334
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000335 // Same for CmpInsts.
336 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
337 if (C->getOperand(0) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000338 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
Hal Finkel60db0582014-09-07 18:57:58 +0000339 TLI, DT, AT);
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000340 if (C->getOperand(1) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000341 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
Hal Finkel60db0582014-09-07 18:57:58 +0000342 TLI, DT, AT);
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000343 }
344
345 // TODO: We could hand off more cases to instsimplify here.
346
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000347 // If all operands are constant after substituting Op for RepOp then we can
348 // constant fold the instruction.
349 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
350 // Build a list of all constant operands.
351 SmallVector<Constant*, 8> ConstOps;
352 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
353 if (I->getOperand(i) == Op)
354 ConstOps.push_back(CRepOp);
355 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
356 ConstOps.push_back(COp);
357 else
358 break;
359 }
360
361 // All operands were constants, fold it.
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000362 if (ConstOps.size() == I->getNumOperands()) {
Benjamin Kramerf55b5922012-10-20 08:43:52 +0000363 if (CmpInst *C = dyn_cast<CmpInst>(I))
364 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
365 ConstOps[1], TD, TLI);
366
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000367 if (LoadInst *LI = dyn_cast<LoadInst>(I))
368 if (!LI->isVolatile())
369 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
370
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000371 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Chad Rosier43a33062011-12-02 01:26:24 +0000372 ConstOps, TD, TLI);
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000373 }
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000374 }
375
Craig Topperf40110f2014-04-25 05:29:35 +0000376 return nullptr;
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000377}
378
David Majnemer8d048d02013-04-30 08:57:58 +0000379/// foldSelectICmpAndOr - We want to turn:
380/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
381/// into:
382/// (or (shl (and X, C1), C3), y)
383/// iff:
384/// C1 and C2 are both powers of 2
385/// where:
386/// C3 = Log(C2) - Log(C1)
387///
388/// This transform handles cases where:
389/// 1. The icmp predicate is inverted
390/// 2. The select operands are reversed
391/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000392static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000393 Value *FalseVal,
394 InstCombiner::BuilderTy *Builder) {
395 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000396 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000397 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000398
399 Value *CmpLHS = IC->getOperand(0);
400 Value *CmpRHS = IC->getOperand(1);
401
402 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000403 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000404
405 Value *X;
406 const APInt *C1;
407 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000408 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000409
410 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000411 bool OrOnTrueVal = false;
412 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
413 if (!OrOnFalseVal)
414 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000415
416 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000417 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000418
419 Value *V = CmpLHS;
420 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
421
422 unsigned C1Log = C1->logBase2();
423 unsigned C2Log = C2->logBase2();
424 if (C2Log > C1Log) {
425 V = Builder->CreateZExtOrTrunc(V, Y->getType());
426 V = Builder->CreateShl(V, C2Log - C1Log);
427 } else if (C1Log > C2Log) {
428 V = Builder->CreateLShr(V, C1Log - C2Log);
429 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000430 } else
431 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000432
433 ICmpInst::Predicate Pred = IC->getPredicate();
434 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
435 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
436 V = Builder->CreateXor(V, *C2);
437
438 return Builder->CreateOr(V, Y);
439}
440
Chris Lattner8f771cb2010-01-05 06:03:12 +0000441/// visitSelectInstWithICmp - Visit a SelectInst that has an
442/// ICmpInst as its first operand.
443///
444Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
445 ICmpInst *ICI) {
446 bool Changed = false;
447 ICmpInst::Predicate Pred = ICI->getPredicate();
448 Value *CmpLHS = ICI->getOperand(0);
449 Value *CmpRHS = ICI->getOperand(1);
450 Value *TrueVal = SI.getTrueValue();
451 Value *FalseVal = SI.getFalseValue();
452
453 // Check cases where the comparison is with a constant that
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000454 // can be adjusted to fit the min/max idiom. We may move or edit ICI
455 // here, so make sure the select is the only user.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000456 if (ICI->hasOneUse())
457 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000458 // X < MIN ? T : F --> F
459 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
460 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
461 return ReplaceInstUsesWith(SI, FalseVal);
462 // X > MAX ? T : F --> F
463 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
464 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
465 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000466 switch (Pred) {
467 default: break;
468 case ICmpInst::ICMP_ULT:
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000469 case ICmpInst::ICMP_SLT:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000470 case ICmpInst::ICMP_UGT:
471 case ICmpInst::ICMP_SGT: {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000472 // These transformations only work for selects over integers.
Chris Lattner229907c2011-07-18 04:54:35 +0000473 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000474 if (!SelectTy)
475 break;
476
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000477 Constant *AdjustedRHS;
478 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
479 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
480 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
481 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
482
Chris Lattner8f771cb2010-01-05 06:03:12 +0000483 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000484 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattner8f771cb2010-01-05 06:03:12 +0000485 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000486 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
487 ; // Nothing to do here. Values match without any sign/zero extension.
488
489 // Types do not match. Instead of calculating this with mixed types
490 // promote all to the larger type. This enables scalar evolution to
491 // analyze this expression.
492 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000493 < SelectTy->getBitWidth()) {
494 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000495
496 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
497 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
498 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
499 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
500 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
501 sextRHS == FalseVal) {
502 CmpLHS = TrueVal;
503 AdjustedRHS = sextRHS;
504 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
505 sextRHS == TrueVal) {
506 CmpLHS = FalseVal;
507 AdjustedRHS = sextRHS;
508 } else if (ICI->isUnsigned()) {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000509 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000510 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
511 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
512 // zext + signed compare cannot be changed:
513 // 0xff <s 0x00, but 0x00ff >s 0x0000
514 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
515 zextRHS == FalseVal) {
516 CmpLHS = TrueVal;
517 AdjustedRHS = zextRHS;
518 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
519 zextRHS == TrueVal) {
520 CmpLHS = FalseVal;
521 AdjustedRHS = zextRHS;
522 } else
523 break;
524 } else
525 break;
526 } else
527 break;
528
529 Pred = ICmpInst::getSwappedPredicate(Pred);
530 CmpRHS = AdjustedRHS;
531 std::swap(FalseVal, TrueVal);
532 ICI->setPredicate(Pred);
533 ICI->setOperand(0, CmpLHS);
534 ICI->setOperand(1, CmpRHS);
535 SI.setOperand(1, TrueVal);
536 SI.setOperand(2, FalseVal);
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000537
538 // Move ICI instruction right before the select instruction. Otherwise
539 // the sext/zext value may be defined after the ICI instruction uses it.
540 ICI->moveBefore(&SI);
541
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000542 Changed = true;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000543 break;
544 }
545 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000546 }
547
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000548 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
549 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
550 // FIXME: Type and constness constraints could be lifted, but we have to
551 // watch code size carefully. We should consider xor instead of
552 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000553 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000554 if (TrueVal->getType() == Ty) {
555 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000556 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000557 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
558 C1 = dyn_cast<ConstantInt>(TrueVal);
559 C2 = dyn_cast<ConstantInt>(FalseVal);
560 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
561 C1 = dyn_cast<ConstantInt>(FalseVal);
562 C2 = dyn_cast<ConstantInt>(TrueVal);
563 }
564 if (C1 && C2) {
565 // This shift results in either -1 or 0.
566 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
567
568 // Check if we can express the operation with a single or.
569 if (C2->isAllOnesValue())
570 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
571
572 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
573 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
574 }
575 }
576 }
577 }
578
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000579 // If we have an equality comparison then we know the value in one of the
580 // arms of the select. See if substituting this value into the arm and
581 // simplifying the result yields the same value as the other arm.
582 if (Pred == ICmpInst::ICMP_EQ) {
Hal Finkel60db0582014-09-07 18:57:58 +0000583 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI,
584 DT, AT) == TrueVal ||
585 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI,
586 DT, AT) == TrueVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000587 return ReplaceInstUsesWith(SI, FalseVal);
Hal Finkel60db0582014-09-07 18:57:58 +0000588 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI,
589 DT, AT) == FalseVal ||
590 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI,
591 DT, AT) == FalseVal)
Nick Lewycky99fb0912011-10-02 10:37:37 +0000592 return ReplaceInstUsesWith(SI, FalseVal);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000593 } else if (Pred == ICmpInst::ICMP_NE) {
Hal Finkel60db0582014-09-07 18:57:58 +0000594 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI,
595 DT, AT) == FalseVal ||
596 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI,
597 DT, AT) == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000598 return ReplaceInstUsesWith(SI, TrueVal);
Hal Finkel60db0582014-09-07 18:57:58 +0000599 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI,
600 DT, AT) == TrueVal ||
601 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI,
602 DT, AT) == TrueVal)
Nick Lewycky99fb0912011-10-02 10:37:37 +0000603 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000604 }
Nick Lewycky83167df2011-03-27 07:30:57 +0000605
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000606 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
607
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000608 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000609 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
610 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
611 SI.setOperand(1, CmpRHS);
612 Changed = true;
613 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
614 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
615 SI.setOperand(2, CmpRHS);
616 Changed = true;
617 }
618 }
619
David Majnemer8d048d02013-04-30 08:57:58 +0000620 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
621 return ReplaceInstUsesWith(SI, V);
622
Craig Topperf40110f2014-04-25 05:29:35 +0000623 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000624}
625
626
627/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
628/// PHI node (but the two may be in different blocks). See if the true/false
629/// values (V) are live in all of the predecessor blocks of the PHI. For
630/// example, cases like this cannot be mapped:
631///
632/// X = phi [ C1, BB1], [C2, BB2]
633/// Y = add
634/// Z = select X, Y, 0
635///
636/// because Y is not live in BB1/BB2.
637///
638static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
639 const SelectInst &SI) {
640 // If the value is a non-instruction value like a constant or argument, it
641 // can always be mapped.
642 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000643 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000644
Chris Lattner8f771cb2010-01-05 06:03:12 +0000645 // If V is a PHI node defined in the same block as the condition PHI, we can
646 // map the arguments.
647 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000648
Chris Lattner8f771cb2010-01-05 06:03:12 +0000649 if (const PHINode *VP = dyn_cast<PHINode>(I))
650 if (VP->getParent() == CondPHI->getParent())
651 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000652
Chris Lattner8f771cb2010-01-05 06:03:12 +0000653 // Otherwise, if the PHI and select are defined in the same block and if V is
654 // defined in a different block, then we can transform it.
655 if (SI.getParent() == CondPHI->getParent() &&
656 I->getParent() != CondPHI->getParent())
657 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000658
Chris Lattner8f771cb2010-01-05 06:03:12 +0000659 // Otherwise we have a 'hard' case and we can't tell without doing more
660 // detailed dominator based analysis, punt.
661 return false;
662}
663
664/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000665/// SPF2(SPF1(A, B), C)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000666Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
667 SelectPatternFlavor SPF1,
668 Value *A, Value *B,
669 Instruction &Outer,
670 SelectPatternFlavor SPF2, Value *C) {
671 if (C == A || C == B) {
672 // MAX(MAX(A, B), B) -> MAX(A, B)
673 // MIN(MIN(a, b), a) -> MIN(a, b)
674 if (SPF1 == SPF2)
675 return ReplaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000676
Chris Lattner8f771cb2010-01-05 06:03:12 +0000677 // MAX(MIN(a, b), a) -> a
678 // MIN(MAX(a, b), a) -> a
679 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
680 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
681 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
682 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
683 return ReplaceInstUsesWith(Outer, C);
684 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000685
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000686 if (SPF1 == SPF2) {
687 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
688 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
689 APInt ACB = CB->getValue();
690 APInt ACC = CC->getValue();
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000691
692 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
693 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000694 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
695 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
696 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
697 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
698 return ReplaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000699
700 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
701 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
702 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
703 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
704 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
705 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
706 Outer.replaceUsesOfWith(Inner, A);
707 return &Outer;
708 }
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000709 }
710 }
711 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000712
713 // ABS(ABS(X)) -> ABS(X)
714 // NABS(NABS(X)) -> NABS(X)
715 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
716 return ReplaceInstUsesWith(Outer, Inner);
717 }
718
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000719 // ABS(NABS(X)) -> ABS(X)
720 // NABS(ABS(X)) -> NABS(X)
721 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
722 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
723 SelectInst *SI = cast<SelectInst>(Inner);
724 Value *NewSI = Builder->CreateSelect(
725 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
726 return ReplaceInstUsesWith(Outer, NewSI);
727 }
Craig Topperf40110f2014-04-25 05:29:35 +0000728 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000729}
730
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000731/// foldSelectICmpAnd - If one of the constants is zero (we know they can't
732/// both be) and we have an icmp instruction with zero, and we have an 'and'
733/// with the non-constant value and a power of two we can turn the select
734/// into a shift on the result of the 'and'.
735static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
736 ConstantInt *FalseVal,
737 InstCombiner::BuilderTy *Builder) {
738 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000739 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000740 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000741
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000742 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000743 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000744
745 ConstantInt *AndRHS;
746 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000747 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000748 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000749
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000750 // If both select arms are non-zero see if we have a select of the form
751 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
752 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000753 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000754 if (!TrueVal->isZero() && !FalseVal->isZero()) {
755 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
756 Offset = FalseVal;
757 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
758 Offset = TrueVal;
759 else
Craig Topperf40110f2014-04-25 05:29:35 +0000760 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000761
762 // Adjust TrueVal and FalseVal to the offset.
763 TrueVal = ConstantInt::get(Builder->getContext(),
764 TrueVal->getValue() - Offset->getValue());
765 FalseVal = ConstantInt::get(Builder->getContext(),
766 FalseVal->getValue() - Offset->getValue());
767 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000768
769 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
770 if (!AndRHS->getValue().isPowerOf2() ||
771 (!TrueVal->getValue().isPowerOf2() &&
772 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000773 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000774
775 // Determine which shift is needed to transform result of the 'and' into the
776 // desired result.
777 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
778 unsigned ValZeros = ValC->getValue().logBase2();
779 unsigned AndZeros = AndRHS->getValue().logBase2();
780
Benjamin Kramer4093f292013-06-29 21:17:04 +0000781 // If types don't match we can still convert the select by introducing a zext
782 // or a trunc of the 'and'. The trunc case requires that all of the truncated
783 // bits are zero, we can figure that out by looking at the 'and' mask.
784 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000786
787 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000788 if (ValZeros > AndZeros)
789 V = Builder->CreateShl(V, ValZeros - AndZeros);
790 else if (ValZeros < AndZeros)
791 V = Builder->CreateLShr(V, AndZeros - ValZeros);
792
793 // Okay, now we know that everything is set up, we just don't know whether we
794 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
795 bool ShouldNotVal = !TrueVal->isZero();
796 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
797 if (ShouldNotVal)
798 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000799
800 // Apply an offset if needed.
801 if (Offset)
802 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000803 return V;
804}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000805
806Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
807 Value *CondVal = SI.getCondition();
808 Value *TrueVal = SI.getTrueValue();
809 Value *FalseVal = SI.getFalseValue();
810
Hal Finkel60db0582014-09-07 18:57:58 +0000811 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI,
812 DT, AT))
Chris Lattnerc707fa92010-04-20 05:32:14 +0000813 return ReplaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000814
Duncan Sands9dff9be2010-02-15 16:12:20 +0000815 if (SI.getType()->isIntegerTy(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000816 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
817 if (C->getZExtValue()) {
818 // Change: A = select B, true, C --> A = or B, C
819 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000820 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000821 // Change: A = select B, false, C --> A = and !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000822 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000823 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000824 }
825 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000826 if (C->getZExtValue() == false) {
827 // Change: A = select B, C, false --> A = and B, C
828 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000829 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000830 // Change: A = select B, C, true --> A = or !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000831 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000832 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000833 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000834
Chris Lattner8f771cb2010-01-05 06:03:12 +0000835 // select a, b, a -> a&b
836 // select a, a, b -> a|b
837 if (CondVal == TrueVal)
838 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000839 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000840 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +0000841
842 // select a, ~a, b -> (~a)&b
843 // select a, b, ~a -> (~a)|b
844 if (match(TrueVal, m_Not(m_Specific(CondVal))))
845 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000846 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +0000847 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000848 }
849
850 // Selecting between two integer constants?
851 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
852 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
853 // select C, 1, 0 -> zext C to int
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000854 if (FalseValC->isZero() && TrueValC->getValue() == 1)
855 return new ZExtInst(CondVal, SI.getType());
856
857 // select C, -1, 0 -> sext C to int
858 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
859 return new SExtInst(CondVal, SI.getType());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000860
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000861 // select C, 0, 1 -> zext !C to int
862 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
863 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
864 return new ZExtInst(NotCond, SI.getType());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000865 }
866
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000867 // select C, 0, -1 -> sext !C to int
868 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
869 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
870 return new SExtInst(NotCond, SI.getType());
871 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000872
873 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
874 return ReplaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000875 }
876
877 // See if we are selecting two values based on a comparison of the two values.
878 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
879 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
880 // Transform (X == Y) ? X : Y -> Y
881 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000882 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000883 // consider X== -0, Y== +0.
884 // It becomes safe if either operand is a nonzero constant.
885 ConstantFP *CFPt, *CFPf;
886 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
887 !CFPt->getValueAPF().isZero()) ||
888 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
889 !CFPf->getValueAPF().isZero()))
890 return ReplaceInstUsesWith(SI, FalseVal);
891 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000892 // Transform (X une Y) ? X : Y -> X
893 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000894 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000895 // consider X== -0, Y== +0.
896 // It becomes safe if either operand is a nonzero constant.
897 ConstantFP *CFPt, *CFPf;
898 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
899 !CFPt->getValueAPF().isZero()) ||
900 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
901 !CFPf->getValueAPF().isZero()))
Chris Lattner8f771cb2010-01-05 06:03:12 +0000902 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000903 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000904
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000905 // Canonicalize to use ordered comparisons by swapping the select
906 // operands.
907 //
908 // e.g.
909 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
910 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
911 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
912 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
913 FCI->getName() + ".inv");
914
915 return SelectInst::Create(NewCond, FalseVal, TrueVal,
916 SI.getName() + ".p");
917 }
918
919 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +0000920 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
921 // Transform (X == Y) ? Y : X -> X
922 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000923 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000924 // consider X== -0, Y== +0.
925 // It becomes safe if either operand is a nonzero constant.
926 ConstantFP *CFPt, *CFPf;
927 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
928 !CFPt->getValueAPF().isZero()) ||
929 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
930 !CFPf->getValueAPF().isZero()))
931 return ReplaceInstUsesWith(SI, FalseVal);
932 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000933 // Transform (X une Y) ? Y : X -> Y
934 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000935 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000936 // consider X== -0, Y== +0.
937 // It becomes safe if either operand is a nonzero constant.
938 ConstantFP *CFPt, *CFPf;
939 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
940 !CFPt->getValueAPF().isZero()) ||
941 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
942 !CFPf->getValueAPF().isZero()))
943 return ReplaceInstUsesWith(SI, TrueVal);
944 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000945
946 // Canonicalize to use ordered comparisons by swapping the select
947 // operands.
948 //
949 // e.g.
950 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
951 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
952 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
953 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
954 FCI->getName() + ".inv");
955
956 return SelectInst::Create(NewCond, FalseVal, TrueVal,
957 SI.getName() + ".p");
958 }
959
Chris Lattner8f771cb2010-01-05 06:03:12 +0000960 // NOTE: if we wanted to, this is where to detect MIN/MAX
961 }
962 // NOTE: if we wanted to, this is where to detect ABS
963 }
964
965 // See if we are selecting two values based on a comparison of the two values.
966 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
967 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
968 return Result;
969
970 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
971 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
972 if (TI->hasOneUse() && FI->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000973 Instruction *AddOp = nullptr, *SubOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000974
975 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
976 if (TI->getOpcode() == FI->getOpcode())
977 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
978 return IV;
979
980 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
981 // even legal for FP.
982 if ((TI->getOpcode() == Instruction::Sub &&
983 FI->getOpcode() == Instruction::Add) ||
984 (TI->getOpcode() == Instruction::FSub &&
985 FI->getOpcode() == Instruction::FAdd)) {
986 AddOp = FI; SubOp = TI;
987 } else if ((FI->getOpcode() == Instruction::Sub &&
988 TI->getOpcode() == Instruction::Add) ||
989 (FI->getOpcode() == Instruction::FSub &&
990 TI->getOpcode() == Instruction::FAdd)) {
991 AddOp = TI; SubOp = FI;
992 }
993
994 if (AddOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000995 Value *OtherAddOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000996 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
997 OtherAddOp = AddOp->getOperand(1);
998 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
999 OtherAddOp = AddOp->getOperand(0);
1000 }
1001
1002 if (OtherAddOp) {
1003 // So at this point we know we have (Y -> OtherAddOp):
1004 // select C, (add X, Y), (sub X, Z)
1005 Value *NegVal; // Compute -Z
Eli Friedman2c980fa2011-06-23 20:40:23 +00001006 if (SI.getType()->isFPOrFPVectorTy()) {
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001007 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
Owen Anderson48b842e2014-01-18 00:48:14 +00001008 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1009 FastMathFlags Flags = AddOp->getFastMathFlags();
1010 Flags &= SubOp->getFastMathFlags();
1011 NegInst->setFastMathFlags(Flags);
1012 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001013 } else {
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001014 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
Chris Lattner8f771cb2010-01-05 06:03:12 +00001015 }
1016
1017 Value *NewTrueOp = OtherAddOp;
1018 Value *NewFalseOp = NegVal;
1019 if (AddOp != TI)
1020 std::swap(NewTrueOp, NewFalseOp);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001021 Value *NewSel =
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001022 Builder->CreateSelect(CondVal, NewTrueOp,
1023 NewFalseOp, SI.getName() + ".p");
Chris Lattner8f771cb2010-01-05 06:03:12 +00001024
Owen Anderson48b842e2014-01-18 00:48:14 +00001025 if (SI.getType()->isFPOrFPVectorTy()) {
1026 Instruction *RI =
1027 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1028
1029 FastMathFlags Flags = AddOp->getFastMathFlags();
1030 Flags &= SubOp->getFastMathFlags();
1031 RI->setFastMathFlags(Flags);
1032 return RI;
1033 } else
Dale Johannesen16bb87a2010-10-27 23:45:18 +00001034 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001035 }
1036 }
1037 }
1038
1039 // See if we can fold the select into one of our operands.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001040 if (SI.getType()->isIntegerTy()) {
Chris Lattner8f771cb2010-01-05 06:03:12 +00001041 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1042 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001043
Chris Lattner8f771cb2010-01-05 06:03:12 +00001044 // MAX(MAX(a, b), a) -> MAX(a, b)
1045 // MIN(MIN(a, b), a) -> MIN(a, b)
1046 // MAX(MIN(a, b), a) -> a
1047 // MIN(MAX(a, b), a) -> a
1048 Value *LHS, *RHS, *LHS2, *RHS2;
1049 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
1050 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001051 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001052 SI, SPF, RHS))
1053 return R;
1054 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
1055 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1056 SI, SPF, LHS))
1057 return R;
1058 }
1059
1060 // TODO.
1061 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001062 }
1063
1064 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001065 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001066 // The true/false values have to be live in the PHI predecessor's blocks.
1067 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1068 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1069 if (Instruction *NV = FoldOpIntoPhi(SI))
1070 return NV;
1071
Nick Lewyckyb074e322011-01-28 03:28:10 +00001072 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1073 if (TrueSI->getCondition() == CondVal) {
Nuno Lopes20c7eb32012-07-27 18:03:57 +00001074 if (SI.getTrueValue() == TrueSI->getTrueValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001075 return nullptr;
Nick Lewyckyb074e322011-01-28 03:28:10 +00001076 SI.setOperand(1, TrueSI->getTrueValue());
1077 return &SI;
1078 }
1079 }
1080 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1081 if (FalseSI->getCondition() == CondVal) {
Nuno Lopes20c7eb32012-07-27 18:03:57 +00001082 if (SI.getFalseValue() == FalseSI->getFalseValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001083 return nullptr;
Nick Lewyckyb074e322011-01-28 03:28:10 +00001084 SI.setOperand(2, FalseSI->getFalseValue());
1085 return &SI;
1086 }
1087 }
1088
Chris Lattner8f771cb2010-01-05 06:03:12 +00001089 if (BinaryOperator::isNot(CondVal)) {
1090 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1091 SI.setOperand(1, FalseVal);
1092 SI.setOperand(2, TrueVal);
1093 return &SI;
1094 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001095
Nadav Rotemc70ef4e2013-05-06 02:39:09 +00001096 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001097 unsigned VWidth = VecTy->getNumElements();
1098 APInt UndefElts(VWidth, 0);
1099 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1100 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1101 if (V != &SI)
1102 return ReplaceInstUsesWith(SI, V);
1103 return &SI;
1104 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001105
Nick Lewycky156999f2012-09-28 09:33:53 +00001106 if (isa<ConstantAggregateZero>(CondVal)) {
1107 return ReplaceInstUsesWith(SI, FalseVal);
1108 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001109 }
1110
Craig Topperf40110f2014-04-25 05:29:35 +00001111 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001112}