blob: b5718c3a9e0b0bb34956217d386f59b7bb5f8311 [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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.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"
James Molloy71b91c22015-05-11 14:42:20 +000017#include "llvm/Analysis/ValueTracking.h"
Xinliang David Licad3a992016-08-25 00:26:32 +000018#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Sanjoy Das08e95b42015-04-30 04:56:04 +000025static SelectPatternFlavor
26getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
27 switch (SPF) {
28 default:
29 llvm_unreachable("unhandled!");
30
31 case SPF_SMIN:
32 return SPF_SMAX;
33 case SPF_UMIN:
34 return SPF_UMAX;
35 case SPF_SMAX:
36 return SPF_SMIN;
37 case SPF_UMAX:
38 return SPF_UMIN;
39 }
40}
41
James Molloy134bec22015-08-11 09:12:57 +000042static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
43 bool Ordered=false) {
Sanjoy Das08e95b42015-04-30 04:56:04 +000044 switch (SPF) {
45 default:
46 llvm_unreachable("unhandled!");
47
48 case SPF_SMIN:
49 return ICmpInst::ICMP_SLT;
50 case SPF_UMIN:
51 return ICmpInst::ICMP_ULT;
52 case SPF_SMAX:
53 return ICmpInst::ICMP_SGT;
54 case SPF_UMAX:
55 return ICmpInst::ICMP_UGT;
James Molloy134bec22015-08-11 09:12:57 +000056 case SPF_FMINNUM:
57 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
58 case SPF_FMAXNUM:
59 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
Sanjoy Das08e95b42015-04-30 04:56:04 +000060 }
61}
62
63static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
64 SelectPatternFlavor SPF, Value *A,
65 Value *B) {
James Molloy134bec22015-08-11 09:12:57 +000066 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
67 assert(CmpInst::isIntPredicate(Pred));
Sanjoy Das08e95b42015-04-30 04:56:04 +000068 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
69}
70
Sanjay Patel6eccf482015-09-09 15:24:36 +000071/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +000072/// %C = or %A, %B
73/// %D = select %cond, %C, %A
74/// into:
75/// %C = select %cond, %B, 0
76/// %D = or %A, %C
77///
78/// Assuming that the specified instruction is an operand to the select, return
79/// a bitmask indicating which operands of this instruction are foldable if they
80/// equal the other incoming value of the select.
81///
Sanjay Patel453ceff2016-09-29 22:18:30 +000082static unsigned getSelectFoldableOperands(Instruction *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +000083 switch (I->getOpcode()) {
84 case Instruction::Add:
85 case Instruction::Mul:
86 case Instruction::And:
87 case Instruction::Or:
88 case Instruction::Xor:
89 return 3; // Can fold through either operand.
90 case Instruction::Sub: // Can only fold on the amount subtracted.
91 case Instruction::Shl: // Can only fold on the shift amount.
92 case Instruction::LShr:
93 case Instruction::AShr:
94 return 1;
95 default:
96 return 0; // Cannot fold
97 }
98}
99
Sanjay Patel6eccf482015-09-09 15:24:36 +0000100/// For the same transformation as the previous function, return the identity
101/// constant that goes into the select.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000102static Constant *getSelectFoldableConstant(Instruction *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000103 switch (I->getOpcode()) {
104 default: llvm_unreachable("This cannot happen!");
105 case Instruction::Add:
106 case Instruction::Sub:
107 case Instruction::Or:
108 case Instruction::Xor:
109 case Instruction::Shl:
110 case Instruction::LShr:
111 case Instruction::AShr:
112 return Constant::getNullValue(I->getType());
113 case Instruction::And:
114 return Constant::getAllOnesValue(I->getType());
115 case Instruction::Mul:
116 return ConstantInt::get(I->getType(), 1);
117 }
118}
119
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000120/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000121Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000122 Instruction *FI) {
Sanjay Patel384d0f22016-06-08 20:31:52 +0000123 // If this is a cast from the same type, merge.
124 if (TI->getNumOperands() == 1 && TI->isCast()) {
125 Type *FIOpndTy = FI->getOperand(0)->getType();
126 if (TI->getOperand(0)->getType() != FIOpndTy)
127 return nullptr;
128
129 // The select condition may be a vector. We may only change the operand
130 // type if the vector width remains the same (and matches the condition).
131 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000132 if (CondTy->isVectorTy()) {
133 if (!FIOpndTy->isVectorTy())
134 return nullptr;
135 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
136 return nullptr;
137
138 // TODO: If the backend knew how to deal with casts better, we could
139 // remove this limitation. For now, there's too much potential to create
140 // worse codegen by promoting the select ahead of size-altering casts
141 // (PR28160).
142 //
143 // Note that ValueTracking's matchSelectPattern() looks through casts
144 // without checking 'hasOneUse' when it matches min/max patterns, so this
145 // transform may end up happening anyway.
146 if (TI->getOpcode() != Instruction::BitCast &&
147 (!TI->hasOneUse() || !FI->hasOneUse()))
148 return nullptr;
149
150 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
151 // TODO: The one-use restrictions for a scalar select could be eased if
152 // the fold of a select in visitLoadInst() was enhanced to match a pattern
153 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000154 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000155 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000156
157 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000158 Value *NewSI =
159 Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
160 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000161 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000162 TI->getType());
163 }
164
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000165 // Only handle binary operators with one-use here. As with the cast case
166 // above, it may be possible to relax the one-use constraint, but that needs
167 // be examined carefully since it may not reduce the total number of
168 // instructions.
Sanjay Patel84ae9432016-11-11 23:20:01 +0000169 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
170 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000171 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000172
173 // Figure out if the operations have any operands in common.
174 Value *MatchOp, *OtherOpT, *OtherOpF;
175 bool MatchIsOpZero;
176 if (TI->getOperand(0) == FI->getOperand(0)) {
177 MatchOp = TI->getOperand(0);
178 OtherOpT = TI->getOperand(1);
179 OtherOpF = FI->getOperand(1);
180 MatchIsOpZero = true;
181 } else if (TI->getOperand(1) == FI->getOperand(1)) {
182 MatchOp = TI->getOperand(1);
183 OtherOpT = TI->getOperand(0);
184 OtherOpF = FI->getOperand(0);
185 MatchIsOpZero = false;
186 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000187 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000188 } else if (TI->getOperand(0) == FI->getOperand(1)) {
189 MatchOp = TI->getOperand(0);
190 OtherOpT = TI->getOperand(1);
191 OtherOpF = FI->getOperand(0);
192 MatchIsOpZero = true;
193 } else if (TI->getOperand(1) == FI->getOperand(0)) {
194 MatchOp = TI->getOperand(1);
195 OtherOpT = TI->getOperand(0);
196 OtherOpF = FI->getOperand(1);
197 MatchIsOpZero = true;
198 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000199 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000200 }
201
202 // If we reach here, they do have operations in common.
Xinliang David Licad3a992016-08-25 00:26:32 +0000203 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
204 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000205 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
206 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
207 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000208}
209
210static bool isSelect01(Constant *C1, Constant *C2) {
211 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
212 if (!C1I)
213 return false;
214 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
215 if (!C2I)
216 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000217 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
218 return false;
219 return C1I->isOne() || C1I->isAllOnesValue() ||
220 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000221}
222
Sanjay Patel6eccf482015-09-09 15:24:36 +0000223/// Try to fold the select into one of the operands to allow further
224/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000225Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000226 Value *FalseVal) {
227 // See the comment above GetSelectFoldableOperands for a description of the
228 // transformation we are doing here.
229 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
230 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
231 !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000232 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000233 unsigned OpToFold = 0;
234 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
235 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000236 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000237 OpToFold = 2;
238 }
239
240 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000241 Constant *C = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000242 Value *OOp = TVI->getOperand(2-OpToFold);
243 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000244 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000245 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000246 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000247 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000248 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000249 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
250 FalseVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000251 BO->copyIRFlags(TVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000252 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000253 }
254 }
255 }
256 }
257 }
258
259 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
260 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
261 !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000262 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000263 unsigned OpToFold = 0;
264 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
265 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000266 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000267 OpToFold = 2;
268 }
269
270 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000271 Constant *C = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000272 Value *OOp = FVI->getOperand(2-OpToFold);
273 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000274 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000275 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000276 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000277 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000278 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
279 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
280 TrueVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000281 BO->copyIRFlags(FVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000282 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000283 }
284 }
285 }
286 }
287 }
288
Craig Topperf40110f2014-04-25 05:29:35 +0000289 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000290}
291
Sanjay Patel6eccf482015-09-09 15:24:36 +0000292/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000293/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
294/// into:
295/// (or (shl (and X, C1), C3), y)
296/// iff:
297/// C1 and C2 are both powers of 2
298/// where:
299/// C3 = Log(C2) - Log(C1)
300///
301/// This transform handles cases where:
302/// 1. The icmp predicate is inverted
303/// 2. The select operands are reversed
304/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000305static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000306 Value *FalseVal,
307 InstCombiner::BuilderTy *Builder) {
308 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000309 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000310 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000311
312 Value *CmpLHS = IC->getOperand(0);
313 Value *CmpRHS = IC->getOperand(1);
314
315 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000316 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000317
318 Value *X;
319 const APInt *C1;
320 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000321 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000322
323 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000324 bool OrOnTrueVal = false;
325 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
326 if (!OrOnFalseVal)
327 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000328
329 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000330 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000331
332 Value *V = CmpLHS;
333 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
334
335 unsigned C1Log = C1->logBase2();
336 unsigned C2Log = C2->logBase2();
337 if (C2Log > C1Log) {
338 V = Builder->CreateZExtOrTrunc(V, Y->getType());
339 V = Builder->CreateShl(V, C2Log - C1Log);
340 } else if (C1Log > C2Log) {
341 V = Builder->CreateLShr(V, C1Log - C2Log);
342 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000343 } else
344 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000345
346 ICmpInst::Predicate Pred = IC->getPredicate();
347 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
348 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
349 V = Builder->CreateXor(V, *C2);
350
351 return Builder->CreateOr(V, Y);
352}
353
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000354/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
355/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
356///
357/// For example, we can fold the following code sequence:
358/// \code
359/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
360/// %1 = icmp ne i32 %x, 0
361/// %2 = select i1 %1, i32 %0, i32 32
362/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000363///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000364/// into:
365/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
366static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Amaury Sechet5da456e2017-01-24 14:22:27 +0000367 InstCombiner::BuilderTy *Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000368 ICmpInst::Predicate Pred = ICI->getPredicate();
369 Value *CmpLHS = ICI->getOperand(0);
370 Value *CmpRHS = ICI->getOperand(1);
371
372 // Check if the condition value compares a value for equality against zero.
373 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
374 return nullptr;
375
376 Value *Count = FalseVal;
377 Value *ValueOnZero = TrueVal;
378 if (Pred == ICmpInst::ICMP_NE)
379 std::swap(Count, ValueOnZero);
380
381 // Skip zero extend/truncate.
382 Value *V = nullptr;
383 if (match(Count, m_ZExt(m_Value(V))) ||
384 match(Count, m_Trunc(m_Value(V))))
385 Count = V;
386
387 // Check if the value propagated on zero is a constant number equal to the
388 // sizeof in bits of 'Count'.
389 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
390 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
391 return nullptr;
392
393 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
394 // input to the cttz/ctlz is used as LHS for the compare instruction.
395 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
396 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
397 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000398 // Explicitly clear the 'undef_on_zero' flag.
399 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
400 Type *Ty = NewI->getArgOperand(1)->getType();
401 NewI->setArgOperand(1, Constant::getNullValue(Ty));
Amaury Sechetd90f5f62017-01-24 17:48:25 +0000402 Builder->Insert(NewI);
403 return Builder->CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000404 }
405
406 return nullptr;
407}
408
Sanjay Patel7ce65832016-11-01 17:46:08 +0000409/// Return true if we find and adjust an icmp+select pattern where the compare
410/// is with a constant that can be incremented or decremented to match the
411/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000412static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
413 ICmpInst::Predicate Pred = Cmp.getPredicate();
414 Value *CmpLHS = Cmp.getOperand(0);
415 Value *CmpRHS = Cmp.getOperand(1);
416 Value *TrueVal = Sel.getTrueValue();
417 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000418
Sanjay Patel644d7c32016-11-01 18:15:03 +0000419 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000420 const APInt *CmpC;
421 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000422 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000423
Sanjay Patel86408a82016-11-07 15:52:45 +0000424 // These transforms only work for selects of integers or vector selects of
425 // integer vectors.
426 Type *SelTy = Sel.getType();
427 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
428 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000429 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000430
Sanjay Patel644d7c32016-11-01 18:15:03 +0000431 Constant *AdjustedRHS;
432 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000433 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000434 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000435 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000436 else
437 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000438
Sanjay Patel644d7c32016-11-01 18:15:03 +0000439 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
440 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
441 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
442 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
443 ; // Nothing to do here. Values match without any sign/zero extension.
444 }
445 // Types do not match. Instead of calculating this with mixed types, promote
446 // all to the larger type. This enables scalar evolution to analyze this
447 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000448 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
449 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000450
Sanjay Patel644d7c32016-11-01 18:15:03 +0000451 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
452 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
453 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
454 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
455 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
456 CmpLHS = TrueVal;
457 AdjustedRHS = SextRHS;
458 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
459 SextRHS == TrueVal) {
460 CmpLHS = FalseVal;
461 AdjustedRHS = SextRHS;
462 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000463 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000464 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
465 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
466 // zext + signed compare cannot be changed:
467 // 0xff <s 0x00, but 0x00ff >s 0x0000
468 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
469 CmpLHS = TrueVal;
470 AdjustedRHS = ZextRHS;
471 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
472 ZextRHS == TrueVal) {
473 CmpLHS = FalseVal;
474 AdjustedRHS = ZextRHS;
475 } else {
476 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000477 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000478 } else {
479 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000480 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000481 } else {
482 return false;
483 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000484
Sanjay Patel644d7c32016-11-01 18:15:03 +0000485 Pred = ICmpInst::getSwappedPredicate(Pred);
486 CmpRHS = AdjustedRHS;
487 std::swap(FalseVal, TrueVal);
488 Cmp.setPredicate(Pred);
489 Cmp.setOperand(0, CmpLHS);
490 Cmp.setOperand(1, CmpRHS);
491 Sel.setOperand(1, TrueVal);
492 Sel.setOperand(2, FalseVal);
493 Sel.swapProfMetadata();
494
495 // Move the compare instruction right before the select instruction. Otherwise
496 // the sext/zext value may be defined after the compare instruction uses it.
497 Cmp.moveBefore(&Sel);
498
499 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000500}
501
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000502/// If this is an integer min/max where the select's 'true' operand is a
503/// constant, canonicalize that constant to the 'false' operand:
504/// select (icmp Pred X, C), C, X --> select (icmp Pred' X, C), X, C
505static Instruction *
506canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
507 InstCombiner::BuilderTy &Builder) {
508 // TODO: We should also canonicalize min/max when the select has a different
509 // constant value than the cmp constant, but we need to fix the backend first.
510 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)) ||
511 !isa<Constant>(Sel.getTrueValue()) ||
512 isa<Constant>(Sel.getFalseValue()) ||
513 Cmp.getOperand(1) != Sel.getTrueValue())
514 return nullptr;
515
516 // Canonicalize the compare predicate based on whether we have min or max.
517 Value *LHS, *RHS;
518 ICmpInst::Predicate NewPred;
519 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
520 switch (SPR.Flavor) {
521 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
522 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
523 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
524 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
525 default: return nullptr;
526 }
527
528 // Canonicalize the constant to the right side.
529 if (isa<Constant>(LHS))
530 std::swap(LHS, RHS);
531
532 Value *NewCmp = Builder.CreateICmp(NewPred, LHS, RHS);
Sanjay Patel91e73a72016-11-26 15:01:59 +0000533 SelectInst *NewSel = SelectInst::Create(NewCmp, LHS, RHS, "", nullptr, &Sel);
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000534
535 // We swapped the select operands, so swap the metadata too.
536 NewSel->swapProfMetadata();
537 return NewSel;
538}
539
Sanjay Patel7ce65832016-11-01 17:46:08 +0000540/// Visit a SelectInst that has an ICmpInst as its first operand.
541Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
542 ICmpInst *ICI) {
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000543 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *Builder))
544 return NewSel;
545
Sanjay Patel644d7c32016-11-01 18:15:03 +0000546 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000547
548 ICmpInst::Predicate Pred = ICI->getPredicate();
549 Value *CmpLHS = ICI->getOperand(0);
550 Value *CmpRHS = ICI->getOperand(1);
551 Value *TrueVal = SI.getTrueValue();
552 Value *FalseVal = SI.getFalseValue();
553
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000554 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
555 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
556 // FIXME: Type and constness constraints could be lifted, but we have to
557 // watch code size carefully. We should consider xor instead of
558 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000559 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000560 if (TrueVal->getType() == Ty) {
561 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000562 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000563 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
564 C1 = dyn_cast<ConstantInt>(TrueVal);
565 C2 = dyn_cast<ConstantInt>(FalseVal);
566 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
567 C1 = dyn_cast<ConstantInt>(FalseVal);
568 C2 = dyn_cast<ConstantInt>(TrueVal);
569 }
570 if (C1 && C2) {
571 // This shift results in either -1 or 0.
572 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
573
574 // Check if we can express the operation with a single or.
575 if (C2->isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000576 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000577
578 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000579 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000580 }
581 }
582 }
583 }
584
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000585 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
586
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000587 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000588 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
589 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
590 SI.setOperand(1, CmpRHS);
591 Changed = true;
592 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
593 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
594 SI.setOperand(2, CmpRHS);
595 Changed = true;
596 }
597 }
598
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000599 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
600 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000601 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000602 unsigned BitWidth =
603 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
David Majnemerb0362e42014-12-20 04:45:35 +0000604 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000605 Value *X;
606 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000607 bool TrueWhenUnset;
608 bool IsBitTest = false;
609 if (ICmpInst::isEquality(Pred) &&
610 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000611 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000612 IsBitTest = true;
613 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
614 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
615 X = CmpLHS;
616 Y = &MinSignedValue;
617 IsBitTest = true;
618 TrueWhenUnset = false;
619 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
620 X = CmpLHS;
621 Y = &MinSignedValue;
622 IsBitTest = true;
623 TrueWhenUnset = true;
624 }
625 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000626 Value *V = nullptr;
627 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000628 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000629 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
630 V = Builder->CreateAnd(X, ~(*Y));
631 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000632 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000633 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
634 V = Builder->CreateAnd(X, ~(*Y));
635 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000636 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000637 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
638 V = Builder->CreateOr(X, *Y);
639 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000640 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000641 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
642 V = Builder->CreateOr(X, *Y);
643
644 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000645 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000646 }
647 }
648
David Majnemer8d048d02013-04-30 08:57:58 +0000649 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000650 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000651
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000652 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000653 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000654
Craig Topperf40110f2014-04-25 05:29:35 +0000655 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000656}
657
658
Sanjay Patel6eccf482015-09-09 15:24:36 +0000659/// SI is a select whose condition is a PHI node (but the two may be in
660/// different blocks). See if the true/false values (V) are live in all of the
661/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000662///
663/// X = phi [ C1, BB1], [C2, BB2]
664/// Y = add
665/// Z = select X, Y, 0
666///
667/// because Y is not live in BB1/BB2.
668///
Sanjay Patel453ceff2016-09-29 22:18:30 +0000669static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000670 const SelectInst &SI) {
671 // If the value is a non-instruction value like a constant or argument, it
672 // can always be mapped.
673 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000674 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000675
Chris Lattner8f771cb2010-01-05 06:03:12 +0000676 // If V is a PHI node defined in the same block as the condition PHI, we can
677 // map the arguments.
678 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000679
Chris Lattner8f771cb2010-01-05 06:03:12 +0000680 if (const PHINode *VP = dyn_cast<PHINode>(I))
681 if (VP->getParent() == CondPHI->getParent())
682 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000683
Chris Lattner8f771cb2010-01-05 06:03:12 +0000684 // Otherwise, if the PHI and select are defined in the same block and if V is
685 // defined in a different block, then we can transform it.
686 if (SI.getParent() == CondPHI->getParent() &&
687 I->getParent() != CondPHI->getParent())
688 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000689
Chris Lattner8f771cb2010-01-05 06:03:12 +0000690 // Otherwise we have a 'hard' case and we can't tell without doing more
691 // detailed dominator based analysis, punt.
692 return false;
693}
694
Sanjay Patel6eccf482015-09-09 15:24:36 +0000695/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000696/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000697Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000698 SelectPatternFlavor SPF1,
699 Value *A, Value *B,
700 Instruction &Outer,
701 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000702 if (Outer.getType() != Inner->getType())
703 return nullptr;
704
Chris Lattner8f771cb2010-01-05 06:03:12 +0000705 if (C == A || C == B) {
706 // MAX(MAX(A, B), B) -> MAX(A, B)
707 // MIN(MIN(a, b), a) -> MIN(a, b)
708 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000709 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000710
Chris Lattner8f771cb2010-01-05 06:03:12 +0000711 // MAX(MIN(a, b), a) -> a
712 // MIN(MAX(a, b), a) -> a
713 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
714 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
715 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
716 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000717 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000718 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000719
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000720 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000721 const APInt *CB, *CC;
722 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
723 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
724 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
725 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
726 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
727 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
728 (SPF1 == SPF_SMAX && CB->sge(*CC)))
729 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000730
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000731 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
732 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
733 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
734 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
735 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
736 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
737 Outer.replaceUsesOfWith(Inner, A);
738 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000739 }
740 }
741 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000742
743 // ABS(ABS(X)) -> ABS(X)
744 // NABS(NABS(X)) -> NABS(X)
745 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000746 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000747 }
748
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000749 // ABS(NABS(X)) -> ABS(X)
750 // NABS(ABS(X)) -> NABS(X)
751 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
752 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
753 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000754 Value *NewSI =
755 Builder->CreateSelect(SI->getCondition(), SI->getFalseValue(),
756 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000757 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000758 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000759
760 auto IsFreeOrProfitableToInvert =
761 [&](Value *V, Value *&NotV, bool &ElidesXor) {
762 if (match(V, m_Not(m_Value(NotV)))) {
763 // If V has at most 2 uses then we can get rid of the xor operation
764 // entirely.
765 ElidesXor |= !V->hasNUsesOrMore(3);
766 return true;
767 }
768
769 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
770 NotV = nullptr;
771 return true;
772 }
773
774 return false;
775 };
776
777 Value *NotA, *NotB, *NotC;
778 bool ElidesXor = false;
779
780 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
781 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
782 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
783 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
784 //
785 // This transform is performance neutral if we can elide at least one xor from
786 // the set of three operands, since we'll be tacking on an xor at the very
787 // end.
788 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
789 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
790 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
791 if (!NotA)
792 NotA = Builder->CreateNot(A);
793 if (!NotB)
794 NotB = Builder->CreateNot(B);
795 if (!NotC)
796 NotC = Builder->CreateNot(C);
797
798 Value *NewInner = generateMinMaxSelectPattern(
799 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
800 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
801 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000802 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000803 }
804
Craig Topperf40110f2014-04-25 05:29:35 +0000805 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000806}
807
Sanjay Patel6eccf482015-09-09 15:24:36 +0000808/// If one of the constants is zero (we know they can't both be) and we have an
809/// icmp instruction with zero, and we have an 'and' with the non-constant value
810/// and a power of two we can turn the select into a shift on the result of the
811/// 'and'.
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000812static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
813 ConstantInt *FalseVal,
814 InstCombiner::BuilderTy *Builder) {
815 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000816 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000817 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000818
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000819 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000820 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000821
822 ConstantInt *AndRHS;
823 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000824 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000825 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000826
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000827 // If both select arms are non-zero see if we have a select of the form
828 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
829 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000830 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000831 if (!TrueVal->isZero() && !FalseVal->isZero()) {
832 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
833 Offset = FalseVal;
834 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
835 Offset = TrueVal;
836 else
Craig Topperf40110f2014-04-25 05:29:35 +0000837 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000838
839 // Adjust TrueVal and FalseVal to the offset.
840 TrueVal = ConstantInt::get(Builder->getContext(),
841 TrueVal->getValue() - Offset->getValue());
842 FalseVal = ConstantInt::get(Builder->getContext(),
843 FalseVal->getValue() - Offset->getValue());
844 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000845
846 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
847 if (!AndRHS->getValue().isPowerOf2() ||
848 (!TrueVal->getValue().isPowerOf2() &&
849 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000850 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000851
852 // Determine which shift is needed to transform result of the 'and' into the
853 // desired result.
854 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
855 unsigned ValZeros = ValC->getValue().logBase2();
856 unsigned AndZeros = AndRHS->getValue().logBase2();
857
Benjamin Kramer4093f292013-06-29 21:17:04 +0000858 // If types don't match we can still convert the select by introducing a zext
859 // or a trunc of the 'and'. The trunc case requires that all of the truncated
860 // bits are zero, we can figure that out by looking at the 'and' mask.
861 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000862 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000863
864 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000865 if (ValZeros > AndZeros)
866 V = Builder->CreateShl(V, ValZeros - AndZeros);
867 else if (ValZeros < AndZeros)
868 V = Builder->CreateLShr(V, AndZeros - ValZeros);
869
870 // Okay, now we know that everything is set up, we just don't know whether we
871 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
872 bool ShouldNotVal = !TrueVal->isZero();
873 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
874 if (ShouldNotVal)
875 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000876
877 // Apply an offset if needed.
878 if (Offset)
879 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000880 return V;
881}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000882
Sanjay Patel39293132016-06-08 21:10:01 +0000883/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
884/// This is even legal for FP.
885static Instruction *foldAddSubSelect(SelectInst &SI,
886 InstCombiner::BuilderTy &Builder) {
887 Value *CondVal = SI.getCondition();
888 Value *TrueVal = SI.getTrueValue();
889 Value *FalseVal = SI.getFalseValue();
890 auto *TI = dyn_cast<Instruction>(TrueVal);
891 auto *FI = dyn_cast<Instruction>(FalseVal);
892 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
893 return nullptr;
894
895 Instruction *AddOp = nullptr, *SubOp = nullptr;
896 if ((TI->getOpcode() == Instruction::Sub &&
897 FI->getOpcode() == Instruction::Add) ||
898 (TI->getOpcode() == Instruction::FSub &&
899 FI->getOpcode() == Instruction::FAdd)) {
900 AddOp = FI;
901 SubOp = TI;
902 } else if ((FI->getOpcode() == Instruction::Sub &&
903 TI->getOpcode() == Instruction::Add) ||
904 (FI->getOpcode() == Instruction::FSub &&
905 TI->getOpcode() == Instruction::FAdd)) {
906 AddOp = TI;
907 SubOp = FI;
908 }
909
910 if (AddOp) {
911 Value *OtherAddOp = nullptr;
912 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
913 OtherAddOp = AddOp->getOperand(1);
914 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
915 OtherAddOp = AddOp->getOperand(0);
916 }
917
918 if (OtherAddOp) {
919 // So at this point we know we have (Y -> OtherAddOp):
920 // select C, (add X, Y), (sub X, Z)
921 Value *NegVal; // Compute -Z
922 if (SI.getType()->isFPOrFPVectorTy()) {
923 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
924 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
925 FastMathFlags Flags = AddOp->getFastMathFlags();
926 Flags &= SubOp->getFastMathFlags();
927 NegInst->setFastMathFlags(Flags);
928 }
929 } else {
930 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
931 }
932
933 Value *NewTrueOp = OtherAddOp;
934 Value *NewFalseOp = NegVal;
935 if (AddOp != TI)
936 std::swap(NewTrueOp, NewFalseOp);
937 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +0000938 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +0000939
940 if (SI.getType()->isFPOrFPVectorTy()) {
941 Instruction *RI =
942 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
943
944 FastMathFlags Flags = AddOp->getFastMathFlags();
945 Flags &= SubOp->getFastMathFlags();
946 RI->setFastMathFlags(Flags);
947 return RI;
948 } else
949 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
950 }
951 }
952 return nullptr;
953}
954
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000955Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
956 Instruction *ExtInst;
957 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
958 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
959 return nullptr;
960
961 auto ExtOpcode = ExtInst->getOpcode();
962 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
963 return nullptr;
964
Sanjay Patel453ceff2016-09-29 22:18:30 +0000965 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000966 Value *X = ExtInst->getOperand(0);
967 Type *SmallType = X->getType();
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000968 if (!SmallType->getScalarType()->isIntegerTy(1))
969 return nullptr;
970
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000971 Constant *C;
972 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
973 !match(Sel.getFalseValue(), m_Constant(C)))
974 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000975
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000976 // If the constant is the same after truncation to the smaller type and
977 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +0000978 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000979 Type *SelType = Sel.getType();
980 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
981 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
982 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000983 Value *TruncCVal = cast<Value>(TruncC);
984 if (ExtInst == Sel.getFalseValue())
985 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000986
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000987 // select Cond, (ext X), C --> ext(select Cond, X, C')
988 // select Cond, C, (ext X) --> ext(select Cond, C', X)
989 Value *NewSel = Builder->CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
990 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +0000991 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000992
Sanjay Patel4326c4a2016-10-07 17:53:07 +0000993 // If one arm of the select is the extend of the condition, replace that arm
994 // with the extension of the appropriate known bool value.
995 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +0000996 if (ExtInst == Sel.getTrueValue()) {
997 // select X, (sext X), C --> select X, -1, C
998 // select X, (zext X), C --> select X, 1, C
999 Constant *One = ConstantInt::getTrue(SmallType);
1000 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001001 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001002 } else {
1003 // select X, C, (sext X) --> select X, C, 0
1004 // select X, C, (zext X) --> select X, C, 0
1005 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001006 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001007 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001008 }
1009
Sanjay Patel453ceff2016-09-29 22:18:30 +00001010 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001011}
1012
Sanjay Patelf26710d2016-09-16 22:16:18 +00001013/// Try to transform a vector select with a constant condition vector into a
1014/// shuffle for easier combining with other shuffles and insert/extract.
1015static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1016 Value *CondVal = SI.getCondition();
1017 Constant *CondC;
1018 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1019 return nullptr;
1020
1021 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1022 SmallVector<Constant *, 16> Mask;
1023 Mask.reserve(NumElts);
1024 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1025 for (unsigned i = 0; i != NumElts; ++i) {
1026 Constant *Elt = CondC->getAggregateElement(i);
1027 if (!Elt)
1028 return nullptr;
1029
1030 if (Elt->isOneValue()) {
1031 // If the select condition element is true, choose from the 1st vector.
1032 Mask.push_back(ConstantInt::get(Int32Ty, i));
1033 } else if (Elt->isNullValue()) {
1034 // If the select condition element is false, choose from the 2nd vector.
1035 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1036 } else if (isa<UndefValue>(Elt)) {
1037 // If the select condition element is undef, the shuffle mask is undef.
1038 Mask.push_back(UndefValue::get(Int32Ty));
1039 } else {
1040 // Bail out on a constant expression.
1041 return nullptr;
1042 }
1043 }
1044
1045 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1046 ConstantVector::get(Mask));
1047}
1048
Sanjay Patel978f8272016-10-29 15:22:04 +00001049/// Reuse bitcasted operands between a compare and select:
1050/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1051/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1052static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1053 InstCombiner::BuilderTy &Builder) {
1054 Value *Cond = Sel.getCondition();
1055 Value *TVal = Sel.getTrueValue();
1056 Value *FVal = Sel.getFalseValue();
1057
1058 CmpInst::Predicate Pred;
1059 Value *A, *B;
1060 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1061 return nullptr;
1062
1063 // The select condition is a compare instruction. If the select's true/false
1064 // values are already the same as the compare operands, there's nothing to do.
1065 if (TVal == A || TVal == B || FVal == A || FVal == B)
1066 return nullptr;
1067
1068 Value *C, *D;
1069 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1070 return nullptr;
1071
1072 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1073 Value *TSrc, *FSrc;
1074 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1075 !match(FVal, m_BitCast(m_Value(FSrc))))
1076 return nullptr;
1077
1078 // If the select true/false values are *different bitcasts* of the same source
1079 // operands, make the select operands the same as the compare operands and
1080 // cast the result. This is the canonical select form for min/max.
1081 Value *NewSel;
1082 if (TSrc == C && FSrc == D) {
1083 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1084 // bitcast (select (cmp A, B), A, B)
1085 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1086 } else if (TSrc == D && FSrc == C) {
1087 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1088 // bitcast (select (cmp A, B), B, A)
1089 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1090 } else {
1091 return nullptr;
1092 }
1093 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1094}
1095
Chris Lattner8f771cb2010-01-05 06:03:12 +00001096Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1097 Value *CondVal = SI.getCondition();
1098 Value *TrueVal = SI.getTrueValue();
1099 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001100 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001101
Chandler Carruth66b31302015-01-04 12:03:27 +00001102 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001103 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001104 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001105
Sanjay Patelf26710d2016-09-16 22:16:18 +00001106 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1107 return I;
1108
Sanjay Patel25600f32016-07-07 15:28:17 +00001109 if (SelType->getScalarType()->isIntegerTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001110 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001111 if (match(TrueVal, m_One())) {
1112 // Change: A = select B, true, C --> A = or B, C
1113 return BinaryOperator::CreateOr(CondVal, FalseVal);
1114 }
1115 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001116 // Change: A = select B, false, C --> A = and !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +00001117 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001118 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001119 }
Sanjay Patelea234362016-07-06 21:01:26 +00001120 if (match(FalseVal, m_Zero())) {
1121 // Change: A = select B, C, false --> A = and B, C
1122 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1123 }
1124 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001125 // Change: A = select B, C, true --> A = or !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +00001126 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001127 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001128 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001129
Sanjay Patela1a4e102016-07-03 14:08:19 +00001130 // select a, a, b -> a | b
1131 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001132 if (CondVal == TrueVal)
1133 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001134 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001135 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001136
Sanjay Patela1a4e102016-07-03 14:08:19 +00001137 // select a, ~a, b -> (~a) & b
1138 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001139 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1140 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001141 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001142 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001143 }
1144
Sanjay Patel65a51c22016-07-06 22:23:01 +00001145 // Selecting between two integer or vector splat integer constants?
1146 //
1147 // Note that we don't handle a scalar select of vectors:
1148 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1149 // because that may need 3 instructions to splat the condition value:
1150 // extend, insertelement, shufflevector.
Sanjay Patel25600f32016-07-07 15:28:17 +00001151 if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001152 // select C, 1, 0 -> zext C to int
1153 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001154 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001155
1156 // select C, -1, 0 -> sext C to int
1157 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001158 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001159
1160 // select C, 0, 1 -> zext !C to int
1161 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1162 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001163 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001164 }
1165
1166 // select C, 0, -1 -> sext !C to int
1167 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1168 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001169 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001170 }
1171 }
1172
Chris Lattner8f771cb2010-01-05 06:03:12 +00001173 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
Sanjay Patel65a51c22016-07-06 22:23:01 +00001174 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
Benjamin Kramerc8b035d2010-12-11 09:42:59 +00001175 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001176 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001177
1178 // See if we are selecting two values based on a comparison of the two values.
1179 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1180 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1181 // Transform (X == Y) ? X : Y -> Y
1182 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001183 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001184 // consider X== -0, Y== +0.
1185 // It becomes safe if either operand is a nonzero constant.
1186 ConstantFP *CFPt, *CFPf;
1187 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1188 !CFPt->getValueAPF().isZero()) ||
1189 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1190 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001191 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001192 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001193 // Transform (X une Y) ? X : Y -> X
1194 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001195 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001196 // consider X== -0, Y== +0.
1197 // It becomes safe if either operand is a nonzero constant.
1198 ConstantFP *CFPt, *CFPf;
1199 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1200 !CFPt->getValueAPF().isZero()) ||
1201 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1202 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001203 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001204 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001205
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001206 // Canonicalize to use ordered comparisons by swapping the select
1207 // operands.
1208 //
1209 // e.g.
1210 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1211 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1212 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001213 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001214 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001215 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1216 FCI->getName() + ".inv");
1217
1218 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1219 SI.getName() + ".p");
1220 }
1221
1222 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001223 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1224 // Transform (X == Y) ? Y : X -> X
1225 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001226 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001227 // consider X== -0, Y== +0.
1228 // It becomes safe if either operand is a nonzero constant.
1229 ConstantFP *CFPt, *CFPf;
1230 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1231 !CFPt->getValueAPF().isZero()) ||
1232 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1233 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001234 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001235 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001236 // Transform (X une Y) ? Y : X -> Y
1237 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001238 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001239 // consider X== -0, Y== +0.
1240 // It becomes safe if either operand is a nonzero constant.
1241 ConstantFP *CFPt, *CFPf;
1242 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1243 !CFPt->getValueAPF().isZero()) ||
1244 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1245 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001246 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001247 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001248
1249 // Canonicalize to use ordered comparisons by swapping the select
1250 // operands.
1251 //
1252 // e.g.
1253 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1254 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1255 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001256 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001257 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001258 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1259 FCI->getName() + ".inv");
1260
1261 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1262 SI.getName() + ".p");
1263 }
1264
Chris Lattner8f771cb2010-01-05 06:03:12 +00001265 // NOTE: if we wanted to, this is where to detect MIN/MAX
1266 }
1267 // NOTE: if we wanted to, this is where to detect ABS
1268 }
1269
1270 // See if we are selecting two values based on a comparison of the two values.
1271 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001272 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001273 return Result;
1274
Sanjay Patel39293132016-06-08 21:10:01 +00001275 if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1276 return Add;
1277
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001278 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001279 auto *TI = dyn_cast<Instruction>(TrueVal);
1280 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001281 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001282 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001283 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001284
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001285 if (Instruction *I = foldSelectExtConst(SI))
1286 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001287
Chris Lattner8f771cb2010-01-05 06:03:12 +00001288 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001289 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001290 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001291 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001292
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001293 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001294 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001295 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1296 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001297
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001298 if (SelectPatternResult::isMinOrMax(SPF)) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001299 // Canonicalize so that type casts are outside select patterns.
1300 if (LHS->getType()->getPrimitiveSizeInBits() !=
Sanjay Patel25600f32016-07-07 15:28:17 +00001301 SelType->getPrimitiveSizeInBits()) {
James Molloy134bec22015-08-11 09:12:57 +00001302 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1303
1304 Value *Cmp;
1305 if (CmpInst::isIntPredicate(Pred)) {
1306 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1307 } else {
1308 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1309 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Sanjay Patela2528152016-01-12 18:03:37 +00001310 Builder->setFastMathFlags(FMF);
James Molloy134bec22015-08-11 09:12:57 +00001311 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1312 }
1313
Xinliang David Licad3a992016-08-25 00:26:32 +00001314 Value *NewSI = Builder->CreateCast(
1315 CastOp, Builder->CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI),
1316 SelType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001317 return replaceInstUsesWith(SI, NewSI);
James Molloy2b21a7c2015-05-20 18:41:25 +00001318 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001319 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001320
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001321 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001322 // MAX(MAX(a, b), a) -> MAX(a, b)
1323 // MIN(MIN(a, b), a) -> MIN(a, b)
1324 // MAX(MIN(a, b), a) -> a
1325 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001326 // ABS(ABS(a)) -> ABS(a)
1327 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001328 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001329 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001330 SI, SPF, RHS))
1331 return R;
James Molloy134bec22015-08-11 09:12:57 +00001332 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001333 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001334 SI, SPF, LHS))
1335 return R;
1336 }
1337
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001338 // MAX(~a, ~b) -> ~MIN(a, b)
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001339 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1340 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1341 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001342 // For this transform to be profitable, we need to eliminate at least two
1343 // 'not' instructions if we're going to add one 'not' instruction.
1344 int NumberOfNots =
1345 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1346 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001347 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001348
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001349 if (NumberOfNots >= 2) {
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001350 Value *NewLHS = Builder->CreateNot(LHS);
1351 Value *NewRHS = Builder->CreateNot(RHS);
1352 Value *NewCmp = SPF == SPF_SMAX
1353 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1354 : Builder->CreateICmpULT(NewLHS, NewRHS);
1355 Value *NewSI =
1356 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1357 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001358 }
1359 }
1360
Chris Lattner8f771cb2010-01-05 06:03:12 +00001361 // TODO.
1362 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001363 }
1364
1365 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001366 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001367 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001368 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1369 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001370 if (Instruction *NV = FoldOpIntoPhi(SI))
1371 return NV;
1372
Nick Lewyckyb074e322011-01-28 03:28:10 +00001373 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001374 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1375 // select(C, select(C, a, b), c) -> select(C, a, c)
1376 if (TrueSI->getCondition() == CondVal) {
1377 if (SI.getTrueValue() == TrueSI->getTrueValue())
1378 return nullptr;
1379 SI.setOperand(1, TrueSI->getTrueValue());
1380 return &SI;
1381 }
1382 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1383 // We choose this as normal form to enable folding on the And and shortening
1384 // paths for the values (this helps GetUnderlyingObjects() for example).
1385 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1386 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1387 SI.setOperand(0, And);
1388 SI.setOperand(1, TrueSI->getTrueValue());
1389 return &SI;
1390 }
Matthias Braun2e404592015-02-06 17:49:36 +00001391 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001392 }
1393 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001394 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1395 // select(C, a, select(C, b, c)) -> select(C, a, c)
1396 if (FalseSI->getCondition() == CondVal) {
1397 if (SI.getFalseValue() == FalseSI->getFalseValue())
1398 return nullptr;
1399 SI.setOperand(2, FalseSI->getFalseValue());
1400 return &SI;
1401 }
1402 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1403 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1404 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1405 SI.setOperand(0, Or);
1406 SI.setOperand(2, FalseSI->getFalseValue());
1407 return &SI;
1408 }
Matthias Braun2e404592015-02-06 17:49:36 +00001409 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001410 }
1411
Chris Lattner8f771cb2010-01-05 06:03:12 +00001412 if (BinaryOperator::isNot(CondVal)) {
1413 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1414 SI.setOperand(1, FalseVal);
1415 SI.setOperand(2, TrueVal);
1416 return &SI;
1417 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001418
Sanjay Patel4e463b42016-09-06 18:16:31 +00001419 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001420 unsigned VWidth = VecTy->getNumElements();
1421 APInt UndefElts(VWidth, 0);
1422 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1423 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1424 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001425 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001426 return &SI;
1427 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001428
Nick Lewycky156999f2012-09-28 09:33:53 +00001429 if (isa<ConstantAggregateZero>(CondVal)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001430 return replaceInstUsesWith(SI, FalseVal);
Nick Lewycky156999f2012-09-28 09:33:53 +00001431 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001432 }
1433
Chad Rosiercd62bf52016-04-29 21:12:31 +00001434 // See if we can determine the result of this select based on a dominating
1435 // condition.
1436 BasicBlock *Parent = SI.getParent();
1437 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1438 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1439 if (PBI && PBI->isConditional() &&
1440 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1441 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1442 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1443 Optional<bool> Implication = isImpliedCondition(
1444 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1445 if (Implication) {
1446 Value *V = *Implication ? TrueVal : FalseVal;
1447 return replaceInstUsesWith(SI, V);
1448 }
1449 }
1450 }
1451
Sanjay Patel51783632017-01-13 17:02:42 +00001452 // If we can compute the condition, there's no need for a select.
1453 // Like the above fold, we are attempting to reduce compile-time cost by
1454 // putting this fold here with limitations rather than in InstSimplify.
1455 // The motivation for this call into value tracking is to take advantage of
1456 // the assumption cache, so make sure that is populated.
1457 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1458 APInt KnownOne(1, 0), KnownZero(1, 0);
1459 computeKnownBits(CondVal, KnownZero, KnownOne, 0, &SI);
1460 if (KnownOne == 1)
1461 return replaceInstUsesWith(SI, TrueVal);
1462 if (KnownZero == 1)
1463 return replaceInstUsesWith(SI, FalseVal);
1464 }
1465
Sanjay Patel978f8272016-10-29 15:22:04 +00001466 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, *Builder))
1467 return BitCastSel;
1468
Craig Topperf40110f2014-04-25 05:29:35 +00001469 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001470}