blob: 165b54bcdeed4755b73e9d35b175b2d6f73dfdb5 [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 // TODO: This function ends awkwardly in unreachable - fix to be more normal.
166
167 // Only handle binary operators with one-use here. As with the cast case
168 // above, it may be possible to relax the one-use constraint, but that needs
169 // be examined carefully since it may not reduce the total number of
170 // instructions.
171 if (!isa<BinaryOperator>(TI) || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000172 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000173
174 // Figure out if the operations have any operands in common.
175 Value *MatchOp, *OtherOpT, *OtherOpF;
176 bool MatchIsOpZero;
177 if (TI->getOperand(0) == FI->getOperand(0)) {
178 MatchOp = TI->getOperand(0);
179 OtherOpT = TI->getOperand(1);
180 OtherOpF = FI->getOperand(1);
181 MatchIsOpZero = true;
182 } else if (TI->getOperand(1) == FI->getOperand(1)) {
183 MatchOp = TI->getOperand(1);
184 OtherOpT = TI->getOperand(0);
185 OtherOpF = FI->getOperand(0);
186 MatchIsOpZero = false;
187 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000188 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000189 } else if (TI->getOperand(0) == FI->getOperand(1)) {
190 MatchOp = TI->getOperand(0);
191 OtherOpT = TI->getOperand(1);
192 OtherOpF = FI->getOperand(0);
193 MatchIsOpZero = true;
194 } else if (TI->getOperand(1) == FI->getOperand(0)) {
195 MatchOp = TI->getOperand(1);
196 OtherOpT = TI->getOperand(0);
197 OtherOpF = FI->getOperand(1);
198 MatchIsOpZero = true;
199 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000200 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000201 }
202
203 // If we reach here, they do have operations in common.
Xinliang David Licad3a992016-08-25 00:26:32 +0000204 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
205 SI.getName() + ".v", &SI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000206
207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
208 if (MatchIsOpZero)
209 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
210 else
211 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
212 }
213 llvm_unreachable("Shouldn't get here");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000214}
215
216static bool isSelect01(Constant *C1, Constant *C2) {
217 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
218 if (!C1I)
219 return false;
220 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
221 if (!C2I)
222 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000223 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
224 return false;
225 return C1I->isOne() || C1I->isAllOnesValue() ||
226 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000227}
228
Sanjay Patel6eccf482015-09-09 15:24:36 +0000229/// Try to fold the select into one of the operands to allow further
230/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000231Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000232 Value *FalseVal) {
233 // See the comment above GetSelectFoldableOperands for a description of the
234 // transformation we are doing here.
235 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
236 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
237 !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000238 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000239 unsigned OpToFold = 0;
240 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
241 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000242 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000243 OpToFold = 2;
244 }
245
246 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000247 Constant *C = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000248 Value *OOp = TVI->getOperand(2-OpToFold);
249 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000250 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000251 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000252 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000253 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000254 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000255 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
256 FalseVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000257 BO->copyIRFlags(TVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000258 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000259 }
260 }
261 }
262 }
263 }
264
265 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
266 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
267 !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000268 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000269 unsigned OpToFold = 0;
270 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
271 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000272 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000273 OpToFold = 2;
274 }
275
276 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000277 Constant *C = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000278 Value *OOp = FVI->getOperand(2-OpToFold);
279 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000280 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000281 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000282 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000283 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000284 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
285 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
286 TrueVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000287 BO->copyIRFlags(FVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000288 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000289 }
290 }
291 }
292 }
293 }
294
Craig Topperf40110f2014-04-25 05:29:35 +0000295 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000296}
297
Sanjay Patel6eccf482015-09-09 15:24:36 +0000298/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000299/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
300/// into:
301/// (or (shl (and X, C1), C3), y)
302/// iff:
303/// C1 and C2 are both powers of 2
304/// where:
305/// C3 = Log(C2) - Log(C1)
306///
307/// This transform handles cases where:
308/// 1. The icmp predicate is inverted
309/// 2. The select operands are reversed
310/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000311static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000312 Value *FalseVal,
313 InstCombiner::BuilderTy *Builder) {
314 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000315 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000316 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000317
318 Value *CmpLHS = IC->getOperand(0);
319 Value *CmpRHS = IC->getOperand(1);
320
321 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000322 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000323
324 Value *X;
325 const APInt *C1;
326 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000327 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000328
329 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000330 bool OrOnTrueVal = false;
331 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
332 if (!OrOnFalseVal)
333 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000334
335 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000336 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000337
338 Value *V = CmpLHS;
339 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
340
341 unsigned C1Log = C1->logBase2();
342 unsigned C2Log = C2->logBase2();
343 if (C2Log > C1Log) {
344 V = Builder->CreateZExtOrTrunc(V, Y->getType());
345 V = Builder->CreateShl(V, C2Log - C1Log);
346 } else if (C1Log > C2Log) {
347 V = Builder->CreateLShr(V, C1Log - C2Log);
348 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000349 } else
350 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000351
352 ICmpInst::Predicate Pred = IC->getPredicate();
353 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
354 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
355 V = Builder->CreateXor(V, *C2);
356
357 return Builder->CreateOr(V, Y);
358}
359
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000360/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
361/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
362///
363/// For example, we can fold the following code sequence:
364/// \code
365/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
366/// %1 = icmp ne i32 %x, 0
367/// %2 = select i1 %1, i32 %0, i32 32
368/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000369///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000370/// into:
371/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
372static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
373 InstCombiner::BuilderTy *Builder) {
374 ICmpInst::Predicate Pred = ICI->getPredicate();
375 Value *CmpLHS = ICI->getOperand(0);
376 Value *CmpRHS = ICI->getOperand(1);
377
378 // Check if the condition value compares a value for equality against zero.
379 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
380 return nullptr;
381
382 Value *Count = FalseVal;
383 Value *ValueOnZero = TrueVal;
384 if (Pred == ICmpInst::ICMP_NE)
385 std::swap(Count, ValueOnZero);
386
387 // Skip zero extend/truncate.
388 Value *V = nullptr;
389 if (match(Count, m_ZExt(m_Value(V))) ||
390 match(Count, m_Trunc(m_Value(V))))
391 Count = V;
392
393 // Check if the value propagated on zero is a constant number equal to the
394 // sizeof in bits of 'Count'.
395 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
396 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
397 return nullptr;
398
399 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
400 // input to the cttz/ctlz is used as LHS for the compare instruction.
401 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
402 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
403 IntrinsicInst *II = cast<IntrinsicInst>(Count);
404 IRBuilder<> Builder(II);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000405 // Explicitly clear the 'undef_on_zero' flag.
406 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
407 Type *Ty = NewI->getArgOperand(1)->getType();
408 NewI->setArgOperand(1, Constant::getNullValue(Ty));
409 Builder.Insert(NewI);
410 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000411 }
412
413 return nullptr;
414}
415
Sanjay Patel6eccf482015-09-09 15:24:36 +0000416/// Visit a SelectInst that has an ICmpInst as its first operand.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000417Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
Sanjay Patele3de1522016-10-25 16:12:31 +0000418 ICmpInst *ICI) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000419 bool Changed = false;
420 ICmpInst::Predicate Pred = ICI->getPredicate();
421 Value *CmpLHS = ICI->getOperand(0);
422 Value *CmpRHS = ICI->getOperand(1);
423 Value *TrueVal = SI.getTrueValue();
424 Value *FalseVal = SI.getFalseValue();
425
426 // Check cases where the comparison is with a constant that
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000427 // can be adjusted to fit the min/max idiom. We may move or edit ICI
428 // here, so make sure the select is the only user.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000429 if (ICI->hasOneUse())
430 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
431 switch (Pred) {
432 default: break;
433 case ICmpInst::ICMP_ULT:
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000434 case ICmpInst::ICMP_SLT:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000435 case ICmpInst::ICMP_UGT:
436 case ICmpInst::ICMP_SGT: {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000437 // These transformations only work for selects over integers.
Chris Lattner229907c2011-07-18 04:54:35 +0000438 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000439 if (!SelectTy)
440 break;
441
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000442 Constant *AdjustedRHS;
443 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
444 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
445 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
446 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
447
Chris Lattner8f771cb2010-01-05 06:03:12 +0000448 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000449 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattner8f771cb2010-01-05 06:03:12 +0000450 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000451 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
452 ; // Nothing to do here. Values match without any sign/zero extension.
453
454 // Types do not match. Instead of calculating this with mixed types
455 // promote all to the larger type. This enables scalar evolution to
456 // analyze this expression.
Sanjay Patele3de1522016-10-25 16:12:31 +0000457 else if (CmpRHS->getType()->getScalarSizeInBits() <
458 SelectTy->getBitWidth()) {
459 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000460
461 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
462 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
463 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
464 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
465 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
Sanjay Patele3de1522016-10-25 16:12:31 +0000466 SextRHS == FalseVal) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000467 CmpLHS = TrueVal;
Sanjay Patele3de1522016-10-25 16:12:31 +0000468 AdjustedRHS = SextRHS;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000469 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
Sanjay Patele3de1522016-10-25 16:12:31 +0000470 SextRHS == TrueVal) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000471 CmpLHS = FalseVal;
Sanjay Patele3de1522016-10-25 16:12:31 +0000472 AdjustedRHS = SextRHS;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000473 } else if (ICI->isUnsigned()) {
Sanjay Patele3de1522016-10-25 16:12:31 +0000474 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000475 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
476 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
477 // zext + signed compare cannot be changed:
478 // 0xff <s 0x00, but 0x00ff >s 0x0000
479 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
Sanjay Patele3de1522016-10-25 16:12:31 +0000480 ZextRHS == FalseVal) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000481 CmpLHS = TrueVal;
Sanjay Patele3de1522016-10-25 16:12:31 +0000482 AdjustedRHS = ZextRHS;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000483 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
Sanjay Patele3de1522016-10-25 16:12:31 +0000484 ZextRHS == TrueVal) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000485 CmpLHS = FalseVal;
Sanjay Patele3de1522016-10-25 16:12:31 +0000486 AdjustedRHS = ZextRHS;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000487 } else
488 break;
489 } else
490 break;
491 } else
492 break;
493
494 Pred = ICmpInst::getSwappedPredicate(Pred);
495 CmpRHS = AdjustedRHS;
496 std::swap(FalseVal, TrueVal);
497 ICI->setPredicate(Pred);
498 ICI->setOperand(0, CmpLHS);
499 ICI->setOperand(1, CmpRHS);
500 SI.setOperand(1, TrueVal);
501 SI.setOperand(2, FalseVal);
Xinliang David Licad3a992016-08-25 00:26:32 +0000502 SI.swapProfMetadata();
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000503
504 // Move ICI instruction right before the select instruction. Otherwise
505 // the sext/zext value may be defined after the ICI instruction uses it.
506 ICI->moveBefore(&SI);
507
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000508 Changed = true;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000509 break;
510 }
511 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000512 }
513
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000514 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
515 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
516 // FIXME: Type and constness constraints could be lifted, but we have to
517 // watch code size carefully. We should consider xor instead of
518 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000519 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000520 if (TrueVal->getType() == Ty) {
521 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000522 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000523 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
524 C1 = dyn_cast<ConstantInt>(TrueVal);
525 C2 = dyn_cast<ConstantInt>(FalseVal);
526 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
527 C1 = dyn_cast<ConstantInt>(FalseVal);
528 C2 = dyn_cast<ConstantInt>(TrueVal);
529 }
530 if (C1 && C2) {
531 // This shift results in either -1 or 0.
532 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
533
534 // Check if we can express the operation with a single or.
535 if (C2->isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000536 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000537
538 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000539 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000540 }
541 }
542 }
543 }
544
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000545 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
546
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000547 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000548 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
549 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
550 SI.setOperand(1, CmpRHS);
551 Changed = true;
552 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
553 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
554 SI.setOperand(2, CmpRHS);
555 Changed = true;
556 }
557 }
558
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000559 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
560 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000561 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000562 unsigned BitWidth =
563 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
David Majnemerb0362e42014-12-20 04:45:35 +0000564 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000565 Value *X;
566 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000567 bool TrueWhenUnset;
568 bool IsBitTest = false;
569 if (ICmpInst::isEquality(Pred) &&
570 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000571 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000572 IsBitTest = true;
573 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
574 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
575 X = CmpLHS;
576 Y = &MinSignedValue;
577 IsBitTest = true;
578 TrueWhenUnset = false;
579 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
580 X = CmpLHS;
581 Y = &MinSignedValue;
582 IsBitTest = true;
583 TrueWhenUnset = true;
584 }
585 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000586 Value *V = nullptr;
587 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000588 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000589 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
590 V = Builder->CreateAnd(X, ~(*Y));
591 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000592 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000593 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
594 V = Builder->CreateAnd(X, ~(*Y));
595 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000596 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000597 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
598 V = Builder->CreateOr(X, *Y);
599 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000600 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000601 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
602 V = Builder->CreateOr(X, *Y);
603
604 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000605 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000606 }
607 }
608
David Majnemer8d048d02013-04-30 08:57:58 +0000609 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000610 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000611
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000612 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000613 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000614
Craig Topperf40110f2014-04-25 05:29:35 +0000615 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000616}
617
618
Sanjay Patel6eccf482015-09-09 15:24:36 +0000619/// SI is a select whose condition is a PHI node (but the two may be in
620/// different blocks). See if the true/false values (V) are live in all of the
621/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000622///
623/// X = phi [ C1, BB1], [C2, BB2]
624/// Y = add
625/// Z = select X, Y, 0
626///
627/// because Y is not live in BB1/BB2.
628///
Sanjay Patel453ceff2016-09-29 22:18:30 +0000629static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000630 const SelectInst &SI) {
631 // If the value is a non-instruction value like a constant or argument, it
632 // can always be mapped.
633 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000634 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000635
Chris Lattner8f771cb2010-01-05 06:03:12 +0000636 // If V is a PHI node defined in the same block as the condition PHI, we can
637 // map the arguments.
638 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000639
Chris Lattner8f771cb2010-01-05 06:03:12 +0000640 if (const PHINode *VP = dyn_cast<PHINode>(I))
641 if (VP->getParent() == CondPHI->getParent())
642 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000643
Chris Lattner8f771cb2010-01-05 06:03:12 +0000644 // Otherwise, if the PHI and select are defined in the same block and if V is
645 // defined in a different block, then we can transform it.
646 if (SI.getParent() == CondPHI->getParent() &&
647 I->getParent() != CondPHI->getParent())
648 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000649
Chris Lattner8f771cb2010-01-05 06:03:12 +0000650 // Otherwise we have a 'hard' case and we can't tell without doing more
651 // detailed dominator based analysis, punt.
652 return false;
653}
654
Sanjay Patel6eccf482015-09-09 15:24:36 +0000655/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000656/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000657Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000658 SelectPatternFlavor SPF1,
659 Value *A, Value *B,
660 Instruction &Outer,
661 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000662 if (Outer.getType() != Inner->getType())
663 return nullptr;
664
Chris Lattner8f771cb2010-01-05 06:03:12 +0000665 if (C == A || C == B) {
666 // MAX(MAX(A, B), B) -> MAX(A, B)
667 // MIN(MIN(a, b), a) -> MIN(a, b)
668 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000669 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000670
Chris Lattner8f771cb2010-01-05 06:03:12 +0000671 // MAX(MIN(a, b), a) -> a
672 // MIN(MAX(a, b), a) -> a
673 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
674 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
675 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
676 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000677 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000678 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000679
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000680 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000681 const APInt *CB, *CC;
682 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
683 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
684 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
685 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
686 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
687 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
688 (SPF1 == SPF_SMAX && CB->sge(*CC)))
689 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000690
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000691 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
692 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
693 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
694 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
695 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
696 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
697 Outer.replaceUsesOfWith(Inner, A);
698 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000699 }
700 }
701 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000702
703 // ABS(ABS(X)) -> ABS(X)
704 // NABS(NABS(X)) -> NABS(X)
705 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000706 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000707 }
708
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000709 // ABS(NABS(X)) -> ABS(X)
710 // NABS(ABS(X)) -> NABS(X)
711 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
712 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
713 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000714 Value *NewSI =
715 Builder->CreateSelect(SI->getCondition(), SI->getFalseValue(),
716 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000717 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000718 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000719
720 auto IsFreeOrProfitableToInvert =
721 [&](Value *V, Value *&NotV, bool &ElidesXor) {
722 if (match(V, m_Not(m_Value(NotV)))) {
723 // If V has at most 2 uses then we can get rid of the xor operation
724 // entirely.
725 ElidesXor |= !V->hasNUsesOrMore(3);
726 return true;
727 }
728
729 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
730 NotV = nullptr;
731 return true;
732 }
733
734 return false;
735 };
736
737 Value *NotA, *NotB, *NotC;
738 bool ElidesXor = false;
739
740 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
741 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
742 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
743 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
744 //
745 // This transform is performance neutral if we can elide at least one xor from
746 // the set of three operands, since we'll be tacking on an xor at the very
747 // end.
748 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
749 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
750 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
751 if (!NotA)
752 NotA = Builder->CreateNot(A);
753 if (!NotB)
754 NotB = Builder->CreateNot(B);
755 if (!NotC)
756 NotC = Builder->CreateNot(C);
757
758 Value *NewInner = generateMinMaxSelectPattern(
759 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
760 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
761 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000762 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000763 }
764
Craig Topperf40110f2014-04-25 05:29:35 +0000765 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000766}
767
Sanjay Patel6eccf482015-09-09 15:24:36 +0000768/// If one of the constants is zero (we know they can't both be) and we have an
769/// icmp instruction with zero, and we have an 'and' with the non-constant value
770/// and a power of two we can turn the select into a shift on the result of the
771/// 'and'.
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000772static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
773 ConstantInt *FalseVal,
774 InstCombiner::BuilderTy *Builder) {
775 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000776 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000777 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000778
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000779 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000780 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000781
782 ConstantInt *AndRHS;
783 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000784 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000786
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000787 // If both select arms are non-zero see if we have a select of the form
788 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
789 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000790 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000791 if (!TrueVal->isZero() && !FalseVal->isZero()) {
792 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
793 Offset = FalseVal;
794 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
795 Offset = TrueVal;
796 else
Craig Topperf40110f2014-04-25 05:29:35 +0000797 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000798
799 // Adjust TrueVal and FalseVal to the offset.
800 TrueVal = ConstantInt::get(Builder->getContext(),
801 TrueVal->getValue() - Offset->getValue());
802 FalseVal = ConstantInt::get(Builder->getContext(),
803 FalseVal->getValue() - Offset->getValue());
804 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000805
806 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
807 if (!AndRHS->getValue().isPowerOf2() ||
808 (!TrueVal->getValue().isPowerOf2() &&
809 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000810 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000811
812 // Determine which shift is needed to transform result of the 'and' into the
813 // desired result.
814 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
815 unsigned ValZeros = ValC->getValue().logBase2();
816 unsigned AndZeros = AndRHS->getValue().logBase2();
817
Benjamin Kramer4093f292013-06-29 21:17:04 +0000818 // If types don't match we can still convert the select by introducing a zext
819 // or a trunc of the 'and'. The trunc case requires that all of the truncated
820 // bits are zero, we can figure that out by looking at the 'and' mask.
821 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000823
824 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000825 if (ValZeros > AndZeros)
826 V = Builder->CreateShl(V, ValZeros - AndZeros);
827 else if (ValZeros < AndZeros)
828 V = Builder->CreateLShr(V, AndZeros - ValZeros);
829
830 // Okay, now we know that everything is set up, we just don't know whether we
831 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
832 bool ShouldNotVal = !TrueVal->isZero();
833 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
834 if (ShouldNotVal)
835 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000836
837 // Apply an offset if needed.
838 if (Offset)
839 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000840 return V;
841}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000842
Sanjay Patel39293132016-06-08 21:10:01 +0000843/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
844/// This is even legal for FP.
845static Instruction *foldAddSubSelect(SelectInst &SI,
846 InstCombiner::BuilderTy &Builder) {
847 Value *CondVal = SI.getCondition();
848 Value *TrueVal = SI.getTrueValue();
849 Value *FalseVal = SI.getFalseValue();
850 auto *TI = dyn_cast<Instruction>(TrueVal);
851 auto *FI = dyn_cast<Instruction>(FalseVal);
852 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
853 return nullptr;
854
855 Instruction *AddOp = nullptr, *SubOp = nullptr;
856 if ((TI->getOpcode() == Instruction::Sub &&
857 FI->getOpcode() == Instruction::Add) ||
858 (TI->getOpcode() == Instruction::FSub &&
859 FI->getOpcode() == Instruction::FAdd)) {
860 AddOp = FI;
861 SubOp = TI;
862 } else if ((FI->getOpcode() == Instruction::Sub &&
863 TI->getOpcode() == Instruction::Add) ||
864 (FI->getOpcode() == Instruction::FSub &&
865 TI->getOpcode() == Instruction::FAdd)) {
866 AddOp = TI;
867 SubOp = FI;
868 }
869
870 if (AddOp) {
871 Value *OtherAddOp = nullptr;
872 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
873 OtherAddOp = AddOp->getOperand(1);
874 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
875 OtherAddOp = AddOp->getOperand(0);
876 }
877
878 if (OtherAddOp) {
879 // So at this point we know we have (Y -> OtherAddOp):
880 // select C, (add X, Y), (sub X, Z)
881 Value *NegVal; // Compute -Z
882 if (SI.getType()->isFPOrFPVectorTy()) {
883 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
884 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
885 FastMathFlags Flags = AddOp->getFastMathFlags();
886 Flags &= SubOp->getFastMathFlags();
887 NegInst->setFastMathFlags(Flags);
888 }
889 } else {
890 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
891 }
892
893 Value *NewTrueOp = OtherAddOp;
894 Value *NewFalseOp = NegVal;
895 if (AddOp != TI)
896 std::swap(NewTrueOp, NewFalseOp);
897 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +0000898 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +0000899
900 if (SI.getType()->isFPOrFPVectorTy()) {
901 Instruction *RI =
902 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
903
904 FastMathFlags Flags = AddOp->getFastMathFlags();
905 Flags &= SubOp->getFastMathFlags();
906 RI->setFastMathFlags(Flags);
907 return RI;
908 } else
909 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
910 }
911 }
912 return nullptr;
913}
914
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000915Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
916 Instruction *ExtInst;
917 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
918 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
919 return nullptr;
920
921 auto ExtOpcode = ExtInst->getOpcode();
922 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
923 return nullptr;
924
Sanjay Patel453ceff2016-09-29 22:18:30 +0000925 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000926 Value *X = ExtInst->getOperand(0);
927 Type *SmallType = X->getType();
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000928 if (!SmallType->getScalarType()->isIntegerTy(1))
929 return nullptr;
930
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000931 Constant *C;
932 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
933 !match(Sel.getFalseValue(), m_Constant(C)))
934 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000935
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000936 // If the constant is the same after truncation to the smaller type and
937 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +0000938 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000939 Type *SelType = Sel.getType();
940 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
941 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
942 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000943 Value *TruncCVal = cast<Value>(TruncC);
944 if (ExtInst == Sel.getFalseValue())
945 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000946
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000947 // select Cond, (ext X), C --> ext(select Cond, X, C')
948 // select Cond, C, (ext X) --> ext(select Cond, C', X)
949 Value *NewSel = Builder->CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
950 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +0000951 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000952
Sanjay Patel4326c4a2016-10-07 17:53:07 +0000953 // If one arm of the select is the extend of the condition, replace that arm
954 // with the extension of the appropriate known bool value.
955 if (Cond == X) {
956 SelectInst *NewSel;
957 if (ExtInst == Sel.getTrueValue()) {
958 // select X, (sext X), C --> select X, -1, C
959 // select X, (zext X), C --> select X, 1, C
960 Constant *One = ConstantInt::getTrue(SmallType);
961 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
962 NewSel = SelectInst::Create(Cond, AllOnesOrOne, C);
963 } else {
964 // select X, C, (sext X) --> select X, C, 0
965 // select X, C, (zext X) --> select X, C, 0
966 Constant *Zero = ConstantInt::getNullValue(SelType);
967 NewSel = SelectInst::Create(Cond, C, Zero);
968 }
969 NewSel->copyMetadata(Sel);
970 return NewSel;
971 }
972
Sanjay Patel453ceff2016-09-29 22:18:30 +0000973 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +0000974}
975
Sanjay Patelf26710d2016-09-16 22:16:18 +0000976/// Try to transform a vector select with a constant condition vector into a
977/// shuffle for easier combining with other shuffles and insert/extract.
978static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
979 Value *CondVal = SI.getCondition();
980 Constant *CondC;
981 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
982 return nullptr;
983
984 unsigned NumElts = CondVal->getType()->getVectorNumElements();
985 SmallVector<Constant *, 16> Mask;
986 Mask.reserve(NumElts);
987 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
988 for (unsigned i = 0; i != NumElts; ++i) {
989 Constant *Elt = CondC->getAggregateElement(i);
990 if (!Elt)
991 return nullptr;
992
993 if (Elt->isOneValue()) {
994 // If the select condition element is true, choose from the 1st vector.
995 Mask.push_back(ConstantInt::get(Int32Ty, i));
996 } else if (Elt->isNullValue()) {
997 // If the select condition element is false, choose from the 2nd vector.
998 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
999 } else if (isa<UndefValue>(Elt)) {
1000 // If the select condition element is undef, the shuffle mask is undef.
1001 Mask.push_back(UndefValue::get(Int32Ty));
1002 } else {
1003 // Bail out on a constant expression.
1004 return nullptr;
1005 }
1006 }
1007
1008 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1009 ConstantVector::get(Mask));
1010}
1011
Chris Lattner8f771cb2010-01-05 06:03:12 +00001012Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1013 Value *CondVal = SI.getCondition();
1014 Value *TrueVal = SI.getTrueValue();
1015 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001016 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001017
Chandler Carruth66b31302015-01-04 12:03:27 +00001018 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00001019 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001020 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001021
Sanjay Patelf26710d2016-09-16 22:16:18 +00001022 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1023 return I;
1024
Sanjay Patel25600f32016-07-07 15:28:17 +00001025 if (SelType->getScalarType()->isIntegerTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001026 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001027 if (match(TrueVal, m_One())) {
1028 // Change: A = select B, true, C --> A = or B, C
1029 return BinaryOperator::CreateOr(CondVal, FalseVal);
1030 }
1031 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001032 // Change: A = select B, false, C --> A = and !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +00001033 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001034 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001035 }
Sanjay Patelea234362016-07-06 21:01:26 +00001036 if (match(FalseVal, m_Zero())) {
1037 // Change: A = select B, C, false --> A = and B, C
1038 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1039 }
1040 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001041 // Change: A = select B, C, true --> A = or !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +00001042 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001043 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001044 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001045
Sanjay Patela1a4e102016-07-03 14:08:19 +00001046 // select a, a, b -> a | b
1047 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001048 if (CondVal == TrueVal)
1049 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001050 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001051 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001052
Sanjay Patela1a4e102016-07-03 14:08:19 +00001053 // select a, ~a, b -> (~a) & b
1054 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001055 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1056 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001057 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001058 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001059 }
1060
Sanjay Patel65a51c22016-07-06 22:23:01 +00001061 // Selecting between two integer or vector splat integer constants?
1062 //
1063 // Note that we don't handle a scalar select of vectors:
1064 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1065 // because that may need 3 instructions to splat the condition value:
1066 // extend, insertelement, shufflevector.
Sanjay Patel25600f32016-07-07 15:28:17 +00001067 if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001068 // select C, 1, 0 -> zext C to int
1069 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001070 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001071
1072 // select C, -1, 0 -> sext C to int
1073 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001074 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001075
1076 // select C, 0, 1 -> zext !C to int
1077 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1078 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001079 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001080 }
1081
1082 // select C, 0, -1 -> sext !C to int
1083 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1084 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001085 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001086 }
1087 }
1088
Chris Lattner8f771cb2010-01-05 06:03:12 +00001089 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
Sanjay Patel65a51c22016-07-06 22:23:01 +00001090 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
Benjamin Kramerc8b035d2010-12-11 09:42:59 +00001091 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001092 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001093
1094 // See if we are selecting two values based on a comparison of the two values.
1095 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1096 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1097 // Transform (X == Y) ? X : Y -> Y
1098 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001099 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001100 // consider X== -0, Y== +0.
1101 // It becomes safe if either operand is a nonzero constant.
1102 ConstantFP *CFPt, *CFPf;
1103 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1104 !CFPt->getValueAPF().isZero()) ||
1105 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1106 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001107 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001108 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001109 // Transform (X une Y) ? X : Y -> X
1110 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001111 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001112 // consider X== -0, Y== +0.
1113 // It becomes safe if either operand is a nonzero constant.
1114 ConstantFP *CFPt, *CFPf;
1115 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1116 !CFPt->getValueAPF().isZero()) ||
1117 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1118 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001119 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001120 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001121
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001122 // Canonicalize to use ordered comparisons by swapping the select
1123 // operands.
1124 //
1125 // e.g.
1126 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1127 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1128 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001129 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001130 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001131 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1132 FCI->getName() + ".inv");
1133
1134 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1135 SI.getName() + ".p");
1136 }
1137
1138 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001139 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1140 // Transform (X == Y) ? Y : X -> X
1141 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001142 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001143 // consider X== -0, Y== +0.
1144 // It becomes safe if either operand is a nonzero constant.
1145 ConstantFP *CFPt, *CFPf;
1146 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1147 !CFPt->getValueAPF().isZero()) ||
1148 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1149 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001150 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001151 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001152 // Transform (X une Y) ? Y : X -> Y
1153 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001154 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001155 // consider X== -0, Y== +0.
1156 // It becomes safe if either operand is a nonzero constant.
1157 ConstantFP *CFPt, *CFPf;
1158 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1159 !CFPt->getValueAPF().isZero()) ||
1160 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1161 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001162 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001163 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001164
1165 // Canonicalize to use ordered comparisons by swapping the select
1166 // operands.
1167 //
1168 // e.g.
1169 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1170 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1171 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001172 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001173 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001174 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1175 FCI->getName() + ".inv");
1176
1177 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1178 SI.getName() + ".p");
1179 }
1180
Chris Lattner8f771cb2010-01-05 06:03:12 +00001181 // NOTE: if we wanted to, this is where to detect MIN/MAX
1182 }
1183 // NOTE: if we wanted to, this is where to detect ABS
1184 }
1185
1186 // See if we are selecting two values based on a comparison of the two values.
1187 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001188 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001189 return Result;
1190
Sanjay Patel39293132016-06-08 21:10:01 +00001191 if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1192 return Add;
1193
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001194 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001195 auto *TI = dyn_cast<Instruction>(TrueVal);
1196 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001197 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001198 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001199 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001200
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001201 if (Instruction *I = foldSelectExtConst(SI))
1202 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001203
Chris Lattner8f771cb2010-01-05 06:03:12 +00001204 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001205 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001206 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001207 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001208
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001209 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001210 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001211 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1212 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001213
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001214 if (SelectPatternResult::isMinOrMax(SPF)) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001215 // Canonicalize so that type casts are outside select patterns.
1216 if (LHS->getType()->getPrimitiveSizeInBits() !=
Sanjay Patel25600f32016-07-07 15:28:17 +00001217 SelType->getPrimitiveSizeInBits()) {
James Molloy134bec22015-08-11 09:12:57 +00001218 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1219
1220 Value *Cmp;
1221 if (CmpInst::isIntPredicate(Pred)) {
1222 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1223 } else {
1224 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1225 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Sanjay Patela2528152016-01-12 18:03:37 +00001226 Builder->setFastMathFlags(FMF);
James Molloy134bec22015-08-11 09:12:57 +00001227 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1228 }
1229
Xinliang David Licad3a992016-08-25 00:26:32 +00001230 Value *NewSI = Builder->CreateCast(
1231 CastOp, Builder->CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI),
1232 SelType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001233 return replaceInstUsesWith(SI, NewSI);
James Molloy2b21a7c2015-05-20 18:41:25 +00001234 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001235 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001236
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001237 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001238 // MAX(MAX(a, b), a) -> MAX(a, b)
1239 // MIN(MIN(a, b), a) -> MIN(a, b)
1240 // MAX(MIN(a, b), a) -> a
1241 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001242 // ABS(ABS(a)) -> ABS(a)
1243 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001244 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001245 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001246 SI, SPF, RHS))
1247 return R;
James Molloy134bec22015-08-11 09:12:57 +00001248 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001249 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001250 SI, SPF, LHS))
1251 return R;
1252 }
1253
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001254 // MAX(~a, ~b) -> ~MIN(a, b)
1255 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1256 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1257 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1258
1259 // This transform adds a xor operation and that extra cost needs to be
1260 // justified. We look for simplifications that will result from
1261 // applying this rule:
1262
1263 bool Profitable =
1264 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1265 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1266 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1267
1268 if (Profitable) {
1269 Value *NewLHS = Builder->CreateNot(LHS);
1270 Value *NewRHS = Builder->CreateNot(RHS);
1271 Value *NewCmp = SPF == SPF_SMAX
1272 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1273 : Builder->CreateICmpULT(NewLHS, NewRHS);
1274 Value *NewSI =
1275 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel4b198802016-02-01 22:23:39 +00001276 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001277 }
1278 }
1279 }
1280
Chris Lattner8f771cb2010-01-05 06:03:12 +00001281 // TODO.
1282 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001283 }
1284
1285 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001286 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001287 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001288 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1289 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001290 if (Instruction *NV = FoldOpIntoPhi(SI))
1291 return NV;
1292
Nick Lewyckyb074e322011-01-28 03:28:10 +00001293 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001294 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1295 // select(C, select(C, a, b), c) -> select(C, a, c)
1296 if (TrueSI->getCondition() == CondVal) {
1297 if (SI.getTrueValue() == TrueSI->getTrueValue())
1298 return nullptr;
1299 SI.setOperand(1, TrueSI->getTrueValue());
1300 return &SI;
1301 }
1302 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1303 // We choose this as normal form to enable folding on the And and shortening
1304 // paths for the values (this helps GetUnderlyingObjects() for example).
1305 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1306 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1307 SI.setOperand(0, And);
1308 SI.setOperand(1, TrueSI->getTrueValue());
1309 return &SI;
1310 }
Matthias Braun2e404592015-02-06 17:49:36 +00001311 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001312 }
1313 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001314 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1315 // select(C, a, select(C, b, c)) -> select(C, a, c)
1316 if (FalseSI->getCondition() == CondVal) {
1317 if (SI.getFalseValue() == FalseSI->getFalseValue())
1318 return nullptr;
1319 SI.setOperand(2, FalseSI->getFalseValue());
1320 return &SI;
1321 }
1322 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1323 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1324 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1325 SI.setOperand(0, Or);
1326 SI.setOperand(2, FalseSI->getFalseValue());
1327 return &SI;
1328 }
Matthias Braun2e404592015-02-06 17:49:36 +00001329 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001330 }
1331
Chris Lattner8f771cb2010-01-05 06:03:12 +00001332 if (BinaryOperator::isNot(CondVal)) {
1333 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1334 SI.setOperand(1, FalseVal);
1335 SI.setOperand(2, TrueVal);
1336 return &SI;
1337 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001338
Sanjay Patel4e463b42016-09-06 18:16:31 +00001339 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001340 unsigned VWidth = VecTy->getNumElements();
1341 APInt UndefElts(VWidth, 0);
1342 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1343 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1344 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001345 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001346 return &SI;
1347 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001348
Nick Lewycky156999f2012-09-28 09:33:53 +00001349 if (isa<ConstantAggregateZero>(CondVal)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001350 return replaceInstUsesWith(SI, FalseVal);
Nick Lewycky156999f2012-09-28 09:33:53 +00001351 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001352 }
1353
Chad Rosiercd62bf52016-04-29 21:12:31 +00001354 // See if we can determine the result of this select based on a dominating
1355 // condition.
1356 BasicBlock *Parent = SI.getParent();
1357 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1358 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1359 if (PBI && PBI->isConditional() &&
1360 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1361 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1362 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1363 Optional<bool> Implication = isImpliedCondition(
1364 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1365 if (Implication) {
1366 Value *V = *Implication ? TrueVal : FalseVal;
1367 return replaceInstUsesWith(SI, V);
1368 }
1369 }
1370 }
1371
Craig Topperf40110f2014-04-25 05:29:35 +00001372 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001373}