blob: 1f89ca635a94633fe873bdd7dd740bba4f96ed74 [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"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/AssumptionCache.h"
Craig Topper882f2962017-08-16 21:52:07 +000020#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000021#include "llvm/Analysis/InstructionSimplify.h"
James Molloy71b91c22015-05-11 14:42:20 +000022#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000034#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000035#include "llvm/IR/Type.h"
36#include "llvm/IR/User.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/Casting.h"
39#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000040#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000041#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42#include <cassert>
43#include <utility>
44
Chris Lattner8f771cb2010-01-05 06:03:12 +000045using namespace llvm;
46using namespace PatternMatch;
47
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "instcombine"
49
Sanjay Patel7ed0bc22018-03-06 16:57:55 +000050static Value *createMinMax(InstCombiner::BuilderTy &Builder,
51 SelectPatternFlavor SPF, Value *A, Value *B) {
52 CmpInst::Predicate Pred = getMinMaxPred(SPF);
53 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
Craig Topperbb4069e2017-07-07 23:16:26 +000054 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
Sanjoy Das08e95b42015-04-30 04:56:04 +000055}
56
Craig Topper28d6d962017-09-05 05:26:37 +000057/// If one of the constants is zero (we know they can't both be) and we have an
58/// icmp instruction with zero, and we have an 'and' with the non-constant value
59/// and a power of two we can turn the select into a shift on the result of the
60/// 'and'.
61/// This folds:
62/// select (icmp eq (and X, C1)), C2, C3
63/// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
64/// To something like:
65/// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
66/// Or:
67/// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
68/// With some variations depending if C3 is larger than C2, or the shift
69/// isn't needed, or the bit widths don't match.
70static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
71 APInt TrueVal, APInt FalseVal,
72 InstCombiner::BuilderTy &Builder) {
73 assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
74
75 // If this is a vector select, we need a vector compare.
76 if (SelType->isVectorTy() != IC->getType()->isVectorTy())
77 return nullptr;
78
79 Value *V;
80 APInt AndMask;
81 bool CreateAnd = false;
82 ICmpInst::Predicate Pred = IC->getPredicate();
83 if (ICmpInst::isEquality(Pred)) {
84 if (!match(IC->getOperand(1), m_Zero()))
85 return nullptr;
86
87 V = IC->getOperand(0);
88
89 const APInt *AndRHS;
90 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
91 return nullptr;
92
93 AndMask = *AndRHS;
94 } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
95 Pred, V, AndMask)) {
96 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
97
98 if (!AndMask.isPowerOf2())
99 return nullptr;
100
101 CreateAnd = true;
102 } else {
103 return nullptr;
104 }
105
106 // If both select arms are non-zero see if we have a select of the form
107 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
108 // for 'x ? 2^n : 0' and fix the thing up at the end.
109 APInt Offset(TrueVal.getBitWidth(), 0);
110 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
111 if ((TrueVal - FalseVal).isPowerOf2())
112 Offset = FalseVal;
113 else if ((FalseVal - TrueVal).isPowerOf2())
114 Offset = TrueVal;
115 else
116 return nullptr;
117
118 // Adjust TrueVal and FalseVal to the offset.
119 TrueVal -= Offset;
120 FalseVal -= Offset;
121 }
122
123 // Make sure one of the select arms is a power of 2.
124 if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
125 return nullptr;
126
127 // Determine which shift is needed to transform result of the 'and' into the
128 // desired result.
129 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
130 unsigned ValZeros = ValC.logBase2();
131 unsigned AndZeros = AndMask.logBase2();
132
133 if (CreateAnd) {
134 // Insert the AND instruction on the input to the truncate.
135 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
136 }
137
138 // If types don't match we can still convert the select by introducing a zext
139 // or a trunc of the 'and'.
140 if (ValZeros > AndZeros) {
141 V = Builder.CreateZExtOrTrunc(V, SelType);
142 V = Builder.CreateShl(V, ValZeros - AndZeros);
143 } else if (ValZeros < AndZeros) {
144 V = Builder.CreateLShr(V, AndZeros - ValZeros);
145 V = Builder.CreateZExtOrTrunc(V, SelType);
146 } else
147 V = Builder.CreateZExtOrTrunc(V, SelType);
148
149 // Okay, now we know that everything is set up, we just don't know whether we
150 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
151 bool ShouldNotVal = !TrueVal.isNullValue();
152 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
153 if (ShouldNotVal)
154 V = Builder.CreateXor(V, ValC);
155
156 // Apply an offset if needed.
157 if (!Offset.isNullValue())
158 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
159 return V;
160}
161
Sanjay Patel6eccf482015-09-09 15:24:36 +0000162/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000163/// %C = or %A, %B
164/// %D = select %cond, %C, %A
165/// into:
166/// %C = select %cond, %B, 0
167/// %D = or %A, %C
168///
169/// Assuming that the specified instruction is an operand to the select, return
170/// a bitmask indicating which operands of this instruction are foldable if they
171/// equal the other incoming value of the select.
Craig Topper8e351e92017-08-08 06:19:24 +0000172static unsigned getSelectFoldableOperands(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000173 switch (I->getOpcode()) {
174 case Instruction::Add:
175 case Instruction::Mul:
176 case Instruction::And:
177 case Instruction::Or:
178 case Instruction::Xor:
179 return 3; // Can fold through either operand.
180 case Instruction::Sub: // Can only fold on the amount subtracted.
181 case Instruction::Shl: // Can only fold on the shift amount.
182 case Instruction::LShr:
183 case Instruction::AShr:
184 return 1;
185 default:
186 return 0; // Cannot fold
187 }
188}
189
Sanjay Patel6eccf482015-09-09 15:24:36 +0000190/// For the same transformation as the previous function, return the identity
191/// constant that goes into the select.
Craig Topper4c766a02017-09-05 05:26:36 +0000192static APInt getSelectFoldableConstant(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000193 switch (I->getOpcode()) {
194 default: llvm_unreachable("This cannot happen!");
195 case Instruction::Add:
196 case Instruction::Sub:
197 case Instruction::Or:
198 case Instruction::Xor:
199 case Instruction::Shl:
200 case Instruction::LShr:
201 case Instruction::AShr:
Craig Topper4c766a02017-09-05 05:26:36 +0000202 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000203 case Instruction::And:
Craig Topper4c766a02017-09-05 05:26:36 +0000204 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000205 case Instruction::Mul:
Craig Topper4c766a02017-09-05 05:26:36 +0000206 return APInt(I->getType()->getScalarSizeInBits(), 1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000207 }
208}
209
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000210/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000211Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000212 Instruction *FI) {
Sanjay Patel6105bb52017-03-16 20:42:45 +0000213 // Don't break up min/max patterns. The hasOneUse checks below prevent that
214 // for most cases, but vector min/max with bitcasts can be transformed. If the
215 // one-use restrictions are eased for other patterns, we still don't want to
216 // obfuscate min/max.
217 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
218 match(&SI, m_SMax(m_Value(), m_Value())) ||
219 match(&SI, m_UMin(m_Value(), m_Value())) ||
220 match(&SI, m_UMax(m_Value(), m_Value()))))
221 return nullptr;
222
Sanjay Patel384d0f22016-06-08 20:31:52 +0000223 // If this is a cast from the same type, merge.
224 if (TI->getNumOperands() == 1 && TI->isCast()) {
225 Type *FIOpndTy = FI->getOperand(0)->getType();
226 if (TI->getOperand(0)->getType() != FIOpndTy)
227 return nullptr;
228
229 // The select condition may be a vector. We may only change the operand
230 // type if the vector width remains the same (and matches the condition).
231 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000232 if (CondTy->isVectorTy()) {
233 if (!FIOpndTy->isVectorTy())
234 return nullptr;
235 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
236 return nullptr;
237
238 // TODO: If the backend knew how to deal with casts better, we could
239 // remove this limitation. For now, there's too much potential to create
240 // worse codegen by promoting the select ahead of size-altering casts
241 // (PR28160).
242 //
243 // Note that ValueTracking's matchSelectPattern() looks through casts
244 // without checking 'hasOneUse' when it matches min/max patterns, so this
245 // transform may end up happening anyway.
246 if (TI->getOpcode() != Instruction::BitCast &&
247 (!TI->hasOneUse() || !FI->hasOneUse()))
248 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000249 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
250 // TODO: The one-use restrictions for a scalar select could be eased if
251 // the fold of a select in visitLoadInst() was enhanced to match a pattern
252 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000253 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000254 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000255
256 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000257 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000258 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
259 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000260 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000261 TI->getType());
262 }
263
John Brawn2867bd72018-01-19 10:05:15 +0000264 // Only handle binary operators (including two-operand getelementptr) with
265 // one-use here. As with the cast case above, it may be possible to relax the
266 // one-use constraint, but that needs be examined carefully since it may not
267 // reduce the total number of instructions.
268 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
269 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
270 !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000271 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000272
273 // Figure out if the operations have any operands in common.
274 Value *MatchOp, *OtherOpT, *OtherOpF;
275 bool MatchIsOpZero;
276 if (TI->getOperand(0) == FI->getOperand(0)) {
277 MatchOp = TI->getOperand(0);
278 OtherOpT = TI->getOperand(1);
279 OtherOpF = FI->getOperand(1);
280 MatchIsOpZero = true;
281 } else if (TI->getOperand(1) == FI->getOperand(1)) {
282 MatchOp = TI->getOperand(1);
283 OtherOpT = TI->getOperand(0);
284 OtherOpF = FI->getOperand(0);
285 MatchIsOpZero = false;
286 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000287 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000288 } else if (TI->getOperand(0) == FI->getOperand(1)) {
289 MatchOp = TI->getOperand(0);
290 OtherOpT = TI->getOperand(1);
291 OtherOpF = FI->getOperand(0);
292 MatchIsOpZero = true;
293 } else if (TI->getOperand(1) == FI->getOperand(0)) {
294 MatchOp = TI->getOperand(1);
295 OtherOpT = TI->getOperand(0);
296 OtherOpF = FI->getOperand(1);
297 MatchIsOpZero = true;
298 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000299 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000300 }
301
302 // If we reach here, they do have operations in common.
Craig Topperbb4069e2017-07-07 23:16:26 +0000303 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
304 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000305 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
306 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
John Brawn2867bd72018-01-19 10:05:15 +0000307 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
308 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
309 }
310 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
311 auto *FGEP = cast<GetElementPtrInst>(FI);
312 Type *ElementType = TGEP->getResultElementType();
313 return TGEP->isInBounds() && FGEP->isInBounds()
314 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
315 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
316 }
317 llvm_unreachable("Expected BinaryOperator or GEP");
318 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000319}
320
Craig Topper4c766a02017-09-05 05:26:36 +0000321static bool isSelect01(const APInt &C1I, const APInt &C2I) {
322 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000323 return false;
Craig Topper4c766a02017-09-05 05:26:36 +0000324 return C1I.isOneValue() || C1I.isAllOnesValue() ||
325 C2I.isOneValue() || C2I.isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000326}
327
Sanjay Patel6eccf482015-09-09 15:24:36 +0000328/// Try to fold the select into one of the operands to allow further
329/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000330Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000331 Value *FalseVal) {
332 // See the comment above GetSelectFoldableOperands for a description of the
333 // transformation we are doing here.
Craig Topper8e351e92017-08-08 06:19:24 +0000334 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
335 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000336 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000337 unsigned OpToFold = 0;
338 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
339 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000340 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000341 OpToFold = 2;
342 }
343
344 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000345 APInt CI = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000346 Value *OOp = TVI->getOperand(2-OpToFold);
347 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000348 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000349 const APInt *OOpC;
350 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
351 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
352 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000353 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000354 NewSel->takeName(TVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000355 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000356 FalseVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000357 BO->copyIRFlags(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000358 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000359 }
360 }
361 }
362 }
363 }
364
Craig Topper8e351e92017-08-08 06:19:24 +0000365 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
366 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000367 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000368 unsigned OpToFold = 0;
369 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
370 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000371 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000372 OpToFold = 2;
373 }
374
375 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000376 APInt CI = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000377 Value *OOp = FVI->getOperand(2-OpToFold);
378 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000379 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000380 const APInt *OOpC;
381 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
382 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
383 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000384 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000385 NewSel->takeName(FVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000386 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000387 TrueVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000388 BO->copyIRFlags(FVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000389 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000390 }
391 }
392 }
393 }
394 }
395
Craig Topperf40110f2014-04-25 05:29:35 +0000396 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000397}
398
Sanjay Patel6eccf482015-09-09 15:24:36 +0000399/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000400/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
401/// into:
Craig Topperae86cc72017-06-21 16:07:13 +0000402/// (or (shl (and X, C1), C3), Y)
David Majnemer8d048d02013-04-30 08:57:58 +0000403/// iff:
404/// C1 and C2 are both powers of 2
405/// where:
406/// C3 = Log(C2) - Log(C1)
407///
408/// This transform handles cases where:
409/// 1. The icmp predicate is inverted
410/// 2. The select operands are reversed
411/// 3. The magnitude of C2 and C1 are flipped
Craig Topper5d6ddda2017-08-29 00:13:49 +0000412static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000413 Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000414 InstCombiner::BuilderTy &Builder) {
Craig Topper5d6ddda2017-08-29 00:13:49 +0000415 // Only handle integer compares. Also, if this is a vector select, we need a
416 // vector compare.
417 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
418 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000419 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000420
421 Value *CmpLHS = IC->getOperand(0);
422 Value *CmpRHS = IC->getOperand(1);
423
Craig Topperdffbbcb2017-06-22 16:23:30 +0000424 Value *V;
425 unsigned C1Log;
426 bool IsEqualZero;
427 bool NeedAnd = false;
428 if (IC->isEquality()) {
429 if (!match(CmpRHS, m_Zero()))
430 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000431
Craig Topperdffbbcb2017-06-22 16:23:30 +0000432 const APInt *C1;
433 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
434 return nullptr;
435
436 V = CmpLHS;
437 C1Log = C1->logBase2();
438 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
439 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
440 IC->getPredicate() == ICmpInst::ICMP_SGT) {
441 // We also need to recognize (icmp slt (trunc (X)), 0) and
442 // (icmp sgt (trunc (X)), -1).
443 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
444 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
445 (!IsEqualZero && !match(CmpRHS, m_Zero())))
446 return nullptr;
447
448 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
449 return nullptr;
450
451 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
452 NeedAnd = true;
453 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000454 return nullptr;
Craig Topperdffbbcb2017-06-22 16:23:30 +0000455 }
David Majnemer8d048d02013-04-30 08:57:58 +0000456
457 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000458 bool OrOnTrueVal = false;
459 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
460 if (!OrOnFalseVal)
461 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000462
463 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000464 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000465
David Majnemer8d048d02013-04-30 08:57:58 +0000466 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
467
David Majnemer8d048d02013-04-30 08:57:58 +0000468 unsigned C2Log = C2->logBase2();
Craig Topperae86cc72017-06-21 16:07:13 +0000469
Craig Topperdffbbcb2017-06-22 16:23:30 +0000470 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
Craig Topperae86cc72017-06-21 16:07:13 +0000471 bool NeedShift = C1Log != C2Log;
Craig Topper5d6ddda2017-08-29 00:13:49 +0000472 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
473 V->getType()->getScalarSizeInBits();
Craig Topperae86cc72017-06-21 16:07:13 +0000474
475 // Make sure we don't create more instructions than we save.
476 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
477 if ((NeedShift + NeedXor + NeedZExtTrunc) >
478 (IC->hasOneUse() + Or->hasOneUse()))
479 return nullptr;
480
Craig Topperdffbbcb2017-06-22 16:23:30 +0000481 if (NeedAnd) {
482 // Insert the AND instruction on the input to the truncate.
483 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
Craig Topperbb4069e2017-07-07 23:16:26 +0000484 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
Craig Topperdffbbcb2017-06-22 16:23:30 +0000485 }
486
David Majnemer8d048d02013-04-30 08:57:58 +0000487 if (C2Log > C1Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000488 V = Builder.CreateZExtOrTrunc(V, Y->getType());
489 V = Builder.CreateShl(V, C2Log - C1Log);
David Majnemer8d048d02013-04-30 08:57:58 +0000490 } else if (C1Log > C2Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000491 V = Builder.CreateLShr(V, C1Log - C2Log);
492 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000493 } else
Craig Topperbb4069e2017-07-07 23:16:26 +0000494 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000495
Craig Topperae86cc72017-06-21 16:07:13 +0000496 if (NeedXor)
Craig Topperbb4069e2017-07-07 23:16:26 +0000497 V = Builder.CreateXor(V, *C2);
David Majnemer8d048d02013-04-30 08:57:58 +0000498
Craig Topperbb4069e2017-07-07 23:16:26 +0000499 return Builder.CreateOr(V, Y);
David Majnemer8d048d02013-04-30 08:57:58 +0000500}
501
Sanjay Patele9a153f2018-02-05 17:53:29 +0000502/// Transform patterns such as: (a > b) ? a - b : 0
503/// into: ((a > b) ? a : b) - b)
504/// This produces a canonical max pattern that is more easily recognized by the
505/// backend and converted into saturated subtraction instructions if those
506/// exist.
507/// There are 8 commuted/swapped variants of this pattern.
508/// TODO: Also support a - UMIN(a,b) patterns.
509static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
510 const Value *TrueVal,
511 const Value *FalseVal,
512 InstCombiner::BuilderTy &Builder) {
513 ICmpInst::Predicate Pred = ICI->getPredicate();
514 if (!ICmpInst::isUnsigned(Pred))
515 return nullptr;
516
517 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
518 if (match(TrueVal, m_Zero())) {
519 Pred = ICmpInst::getInversePredicate(Pred);
520 std::swap(TrueVal, FalseVal);
521 }
522 if (!match(FalseVal, m_Zero()))
523 return nullptr;
524
525 Value *A = ICI->getOperand(0);
526 Value *B = ICI->getOperand(1);
527 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
528 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
529 std::swap(A, B);
530 Pred = ICmpInst::getSwappedPredicate(Pred);
531 }
532
533 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
534 "Unexpected isUnsigned predicate!");
535
536 // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
537 bool IsNegative = false;
538 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
539 IsNegative = true;
540 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
541 return nullptr;
542
543 // If sub is used anywhere else, we wouldn't be able to eliminate it
544 // afterwards.
545 if (!TrueVal->hasOneUse())
546 return nullptr;
547
548 // All checks passed, convert to canonical unsigned saturated subtraction
549 // form: sub(max()).
550 // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
551 Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
552 return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
553}
554
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000555/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
556/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
557///
558/// For example, we can fold the following code sequence:
559/// \code
560/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
561/// %1 = icmp ne i32 %x, 0
562/// %2 = select i1 %1, i32 %0, i32 32
563/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000564///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000565/// into:
566/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
567static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000568 InstCombiner::BuilderTy &Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000569 ICmpInst::Predicate Pred = ICI->getPredicate();
570 Value *CmpLHS = ICI->getOperand(0);
571 Value *CmpRHS = ICI->getOperand(1);
572
573 // Check if the condition value compares a value for equality against zero.
574 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
575 return nullptr;
576
577 Value *Count = FalseVal;
578 Value *ValueOnZero = TrueVal;
579 if (Pred == ICmpInst::ICMP_NE)
580 std::swap(Count, ValueOnZero);
581
582 // Skip zero extend/truncate.
583 Value *V = nullptr;
584 if (match(Count, m_ZExt(m_Value(V))) ||
585 match(Count, m_Trunc(m_Value(V))))
586 Count = V;
587
588 // Check if the value propagated on zero is a constant number equal to the
589 // sizeof in bits of 'Count'.
590 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
591 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
592 return nullptr;
593
594 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
595 // input to the cttz/ctlz is used as LHS for the compare instruction.
596 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
597 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
598 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000599 // Explicitly clear the 'undef_on_zero' flag.
600 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Craig Topper3b74a682017-08-04 16:07:18 +0000601 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
Craig Topperbb4069e2017-07-07 23:16:26 +0000602 Builder.Insert(NewI);
603 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000604 }
605
606 return nullptr;
607}
608
Sanjay Patel7ce65832016-11-01 17:46:08 +0000609/// Return true if we find and adjust an icmp+select pattern where the compare
610/// is with a constant that can be incremented or decremented to match the
611/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000612static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
613 ICmpInst::Predicate Pred = Cmp.getPredicate();
614 Value *CmpLHS = Cmp.getOperand(0);
615 Value *CmpRHS = Cmp.getOperand(1);
616 Value *TrueVal = Sel.getTrueValue();
617 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000618
Sanjay Patel644d7c32016-11-01 18:15:03 +0000619 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000620 const APInt *CmpC;
621 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000622 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000623
Sanjay Patel86408a82016-11-07 15:52:45 +0000624 // These transforms only work for selects of integers or vector selects of
625 // integer vectors.
626 Type *SelTy = Sel.getType();
627 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
628 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000629 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000630
Sanjay Patel644d7c32016-11-01 18:15:03 +0000631 Constant *AdjustedRHS;
632 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000633 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000634 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000635 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000636 else
637 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000638
Sanjay Patel644d7c32016-11-01 18:15:03 +0000639 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
640 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
641 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
642 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
643 ; // Nothing to do here. Values match without any sign/zero extension.
644 }
645 // Types do not match. Instead of calculating this with mixed types, promote
646 // all to the larger type. This enables scalar evolution to analyze this
647 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000648 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
649 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000650
Sanjay Patel644d7c32016-11-01 18:15:03 +0000651 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
652 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
653 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
654 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
655 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
656 CmpLHS = TrueVal;
657 AdjustedRHS = SextRHS;
658 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
659 SextRHS == TrueVal) {
660 CmpLHS = FalseVal;
661 AdjustedRHS = SextRHS;
662 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000663 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000664 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
665 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
666 // zext + signed compare cannot be changed:
667 // 0xff <s 0x00, but 0x00ff >s 0x0000
668 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
669 CmpLHS = TrueVal;
670 AdjustedRHS = ZextRHS;
671 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
672 ZextRHS == TrueVal) {
673 CmpLHS = FalseVal;
674 AdjustedRHS = ZextRHS;
675 } else {
676 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000677 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000678 } else {
679 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000680 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000681 } else {
682 return false;
683 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000684
Sanjay Patel644d7c32016-11-01 18:15:03 +0000685 Pred = ICmpInst::getSwappedPredicate(Pred);
686 CmpRHS = AdjustedRHS;
687 std::swap(FalseVal, TrueVal);
688 Cmp.setPredicate(Pred);
689 Cmp.setOperand(0, CmpLHS);
690 Cmp.setOperand(1, CmpRHS);
691 Sel.setOperand(1, TrueVal);
692 Sel.setOperand(2, FalseVal);
693 Sel.swapProfMetadata();
694
695 // Move the compare instruction right before the select instruction. Otherwise
696 // the sext/zext value may be defined after the compare instruction uses it.
697 Cmp.moveBefore(&Sel);
698
699 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000700}
701
Sanjay Patelcb731f12017-02-21 19:33:53 +0000702/// If this is an integer min/max (icmp + select) with a constant operand,
703/// create the canonical icmp for the min/max operation and canonicalize the
704/// constant to the 'false' operand of the select:
705/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
706/// Note: if C1 != C2, this will change the icmp constant to the existing
707/// constant operand of the select.
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000708static Instruction *
709canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
710 InstCombiner::BuilderTy &Builder) {
Sanjay Patelcb731f12017-02-21 19:33:53 +0000711 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000712 return nullptr;
713
714 // Canonicalize the compare predicate based on whether we have min or max.
715 Value *LHS, *RHS;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000716 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000717 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
718 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000719
Sanjay Patelcb731f12017-02-21 19:33:53 +0000720 // Is this already canonical?
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000721 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
Sanjay Patelcb731f12017-02-21 19:33:53 +0000722 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000723 Cmp.getPredicate() == CanonicalPred)
Sanjay Patelcb731f12017-02-21 19:33:53 +0000724 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000725
Sanjay Patelcb731f12017-02-21 19:33:53 +0000726 // Create the canonical compare and plug it into the select.
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000727 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000728
Sanjay Patelcb731f12017-02-21 19:33:53 +0000729 // If the select operands did not change, we're done.
730 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
731 return &Sel;
732
733 // If we are swapping the select operands, swap the metadata too.
734 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
735 "Unexpected results from matchSelectPattern");
736 Sel.setTrueValue(LHS);
737 Sel.setFalseValue(RHS);
738 Sel.swapProfMetadata();
739 return &Sel;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000740}
741
Sanjay Patel7ce65832016-11-01 17:46:08 +0000742/// Visit a SelectInst that has an ICmpInst as its first operand.
743Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
744 ICmpInst *ICI) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000745 Value *TrueVal = SI.getTrueValue();
746 Value *FalseVal = SI.getFalseValue();
747
Craig Topperbb4069e2017-07-07 23:16:26 +0000748 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000749 return NewSel;
750
Sanjay Patel644d7c32016-11-01 18:15:03 +0000751 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000752
753 ICmpInst::Predicate Pred = ICI->getPredicate();
754 Value *CmpLHS = ICI->getOperand(0);
755 Value *CmpRHS = ICI->getOperand(1);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000756
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000757 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
758 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
759 // FIXME: Type and constness constraints could be lifted, but we have to
760 // watch code size carefully. We should consider xor instead of
761 // sub/add when we decide to do that.
Craig Topper74177e12017-08-21 19:02:06 +0000762 // TODO: Merge this with foldSelectICmpAnd somehow.
Craig Topper882f2962017-08-16 21:52:07 +0000763 if (CmpLHS->getType()->isIntOrIntVectorTy() &&
764 CmpLHS->getType() == TrueVal->getType()) {
765 const APInt *C1, *C2;
766 if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
767 ICmpInst::Predicate Pred = ICI->getPredicate();
768 Value *X;
769 APInt Mask;
Craig Topper924f2022017-09-01 21:27:34 +0000770 if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
Craig Topper882f2962017-08-16 21:52:07 +0000771 if (Mask.isSignMask()) {
772 assert(X == CmpLHS && "Expected to use the compare input directly");
773 assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
774
775 if (Pred == ICmpInst::ICMP_NE)
776 std::swap(C1, C2);
777
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000778 // This shift results in either -1 or 0.
Craig Topper882f2962017-08-16 21:52:07 +0000779 Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000780
781 // Check if we can express the operation with a single or.
Craig Topper882f2962017-08-16 21:52:07 +0000782 if (C2->isAllOnesValue())
783 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000784
Craig Topper882f2962017-08-16 21:52:07 +0000785 Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
786 return replaceInstUsesWith(SI, Builder.CreateAdd(And,
787 ConstantInt::get(And->getType(), *C1)));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000788 }
789 }
790 }
791 }
792
Craig Topper74177e12017-08-21 19:02:06 +0000793 {
794 const APInt *TrueValC, *FalseValC;
795 if (match(TrueVal, m_APInt(TrueValC)) &&
796 match(FalseVal, m_APInt(FalseValC)))
797 if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
798 *FalseValC, Builder))
799 return replaceInstUsesWith(SI, V);
800 }
801
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000802 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
803
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000804 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000805 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
806 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
807 SI.setOperand(1, CmpRHS);
808 Changed = true;
809 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
810 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
811 SI.setOperand(2, CmpRHS);
812 Changed = true;
813 }
814 }
815
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000816 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
817 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000818 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000819 unsigned BitWidth =
820 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
Craig Topperbcfd2d12017-04-20 16:56:25 +0000821 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000822 Value *X;
823 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000824 bool TrueWhenUnset;
825 bool IsBitTest = false;
826 if (ICmpInst::isEquality(Pred) &&
827 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000828 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000829 IsBitTest = true;
830 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
831 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
832 X = CmpLHS;
833 Y = &MinSignedValue;
834 IsBitTest = true;
835 TrueWhenUnset = false;
836 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
837 X = CmpLHS;
838 Y = &MinSignedValue;
839 IsBitTest = true;
840 TrueWhenUnset = true;
841 }
842 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000843 Value *V = nullptr;
844 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000845 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000846 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000847 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000848 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000849 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000850 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000851 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000852 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000853 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000854 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000855 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000856 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000857 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000858 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000859 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000860
861 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000862 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000863 }
864 }
865
Craig Topper5d6ddda2017-08-29 00:13:49 +0000866 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000867 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000868
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000869 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000870 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000871
Sanjay Patele9a153f2018-02-05 17:53:29 +0000872 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
873 return replaceInstUsesWith(SI, V);
874
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000876}
877
Sanjay Patel6eccf482015-09-09 15:24:36 +0000878/// SI is a select whose condition is a PHI node (but the two may be in
879/// different blocks). See if the true/false values (V) are live in all of the
880/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000881///
882/// X = phi [ C1, BB1], [C2, BB2]
883/// Y = add
884/// Z = select X, Y, 0
885///
886/// because Y is not live in BB1/BB2.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000887static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000888 const SelectInst &SI) {
889 // If the value is a non-instruction value like a constant or argument, it
890 // can always be mapped.
891 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000892 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000893
Chris Lattner8f771cb2010-01-05 06:03:12 +0000894 // If V is a PHI node defined in the same block as the condition PHI, we can
895 // map the arguments.
896 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000897
Chris Lattner8f771cb2010-01-05 06:03:12 +0000898 if (const PHINode *VP = dyn_cast<PHINode>(I))
899 if (VP->getParent() == CondPHI->getParent())
900 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000901
Chris Lattner8f771cb2010-01-05 06:03:12 +0000902 // Otherwise, if the PHI and select are defined in the same block and if V is
903 // defined in a different block, then we can transform it.
904 if (SI.getParent() == CondPHI->getParent() &&
905 I->getParent() != CondPHI->getParent())
906 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000907
Chris Lattner8f771cb2010-01-05 06:03:12 +0000908 // Otherwise we have a 'hard' case and we can't tell without doing more
909 // detailed dominator based analysis, punt.
910 return false;
911}
912
Sanjay Patel6eccf482015-09-09 15:24:36 +0000913/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000914/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000915Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000916 SelectPatternFlavor SPF1,
917 Value *A, Value *B,
918 Instruction &Outer,
919 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000920 if (Outer.getType() != Inner->getType())
921 return nullptr;
922
Chris Lattner8f771cb2010-01-05 06:03:12 +0000923 if (C == A || C == B) {
924 // MAX(MAX(A, B), B) -> MAX(A, B)
925 // MIN(MIN(a, b), a) -> MIN(a, b)
926 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000927 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000928
Chris Lattner8f771cb2010-01-05 06:03:12 +0000929 // MAX(MIN(a, b), a) -> a
930 // MIN(MAX(a, b), a) -> a
931 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
932 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
933 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
934 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000935 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000936 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000937
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000938 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000939 const APInt *CB, *CC;
940 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
941 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
942 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
943 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
944 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
945 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
946 (SPF1 == SPF_SMAX && CB->sge(*CC)))
947 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000948
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000949 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
950 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
951 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
952 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
953 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
954 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
955 Outer.replaceUsesOfWith(Inner, A);
956 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000957 }
958 }
959 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000960
961 // ABS(ABS(X)) -> ABS(X)
962 // NABS(NABS(X)) -> NABS(X)
963 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000964 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000965 }
966
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000967 // ABS(NABS(X)) -> ABS(X)
968 // NABS(ABS(X)) -> NABS(X)
969 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
970 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
971 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000972 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000973 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
974 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000975 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000976 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000977
978 auto IsFreeOrProfitableToInvert =
979 [&](Value *V, Value *&NotV, bool &ElidesXor) {
980 if (match(V, m_Not(m_Value(NotV)))) {
981 // If V has at most 2 uses then we can get rid of the xor operation
982 // entirely.
983 ElidesXor |= !V->hasNUsesOrMore(3);
984 return true;
985 }
986
987 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
988 NotV = nullptr;
989 return true;
990 }
991
992 return false;
993 };
994
995 Value *NotA, *NotB, *NotC;
996 bool ElidesXor = false;
997
998 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
999 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1000 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1001 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1002 //
1003 // This transform is performance neutral if we can elide at least one xor from
1004 // the set of three operands, since we'll be tacking on an xor at the very
1005 // end.
Anna Thomasec36f3b2017-02-21 14:40:28 +00001006 if (SelectPatternResult::isMinOrMax(SPF1) &&
1007 SelectPatternResult::isMinOrMax(SPF2) &&
1008 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
Sanjoy Das08e95b42015-04-30 04:56:04 +00001009 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1010 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1011 if (!NotA)
Craig Topperbb4069e2017-07-07 23:16:26 +00001012 NotA = Builder.CreateNot(A);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001013 if (!NotB)
Craig Topperbb4069e2017-07-07 23:16:26 +00001014 NotB = Builder.CreateNot(B);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001015 if (!NotC)
Craig Topperbb4069e2017-07-07 23:16:26 +00001016 NotC = Builder.CreateNot(C);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001017
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001018 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1019 NotB);
1020 Value *NewOuter = Builder.CreateNot(
1021 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +00001022 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001023 }
1024
Craig Topperf40110f2014-04-25 05:29:35 +00001025 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001026}
1027
Sanjay Patel39293132016-06-08 21:10:01 +00001028/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1029/// This is even legal for FP.
1030static Instruction *foldAddSubSelect(SelectInst &SI,
1031 InstCombiner::BuilderTy &Builder) {
1032 Value *CondVal = SI.getCondition();
1033 Value *TrueVal = SI.getTrueValue();
1034 Value *FalseVal = SI.getFalseValue();
1035 auto *TI = dyn_cast<Instruction>(TrueVal);
1036 auto *FI = dyn_cast<Instruction>(FalseVal);
1037 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1038 return nullptr;
1039
1040 Instruction *AddOp = nullptr, *SubOp = nullptr;
1041 if ((TI->getOpcode() == Instruction::Sub &&
1042 FI->getOpcode() == Instruction::Add) ||
1043 (TI->getOpcode() == Instruction::FSub &&
1044 FI->getOpcode() == Instruction::FAdd)) {
1045 AddOp = FI;
1046 SubOp = TI;
1047 } else if ((FI->getOpcode() == Instruction::Sub &&
1048 TI->getOpcode() == Instruction::Add) ||
1049 (FI->getOpcode() == Instruction::FSub &&
1050 TI->getOpcode() == Instruction::FAdd)) {
1051 AddOp = TI;
1052 SubOp = FI;
1053 }
1054
1055 if (AddOp) {
1056 Value *OtherAddOp = nullptr;
1057 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1058 OtherAddOp = AddOp->getOperand(1);
1059 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1060 OtherAddOp = AddOp->getOperand(0);
1061 }
1062
1063 if (OtherAddOp) {
1064 // So at this point we know we have (Y -> OtherAddOp):
1065 // select C, (add X, Y), (sub X, Z)
1066 Value *NegVal; // Compute -Z
1067 if (SI.getType()->isFPOrFPVectorTy()) {
1068 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1069 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1070 FastMathFlags Flags = AddOp->getFastMathFlags();
1071 Flags &= SubOp->getFastMathFlags();
1072 NegInst->setFastMathFlags(Flags);
1073 }
1074 } else {
1075 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1076 }
1077
1078 Value *NewTrueOp = OtherAddOp;
1079 Value *NewFalseOp = NegVal;
1080 if (AddOp != TI)
1081 std::swap(NewTrueOp, NewFalseOp);
1082 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +00001083 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +00001084
1085 if (SI.getType()->isFPOrFPVectorTy()) {
1086 Instruction *RI =
1087 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1088
1089 FastMathFlags Flags = AddOp->getFastMathFlags();
1090 Flags &= SubOp->getFastMathFlags();
1091 RI->setFastMathFlags(Flags);
1092 return RI;
1093 } else
1094 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1095 }
1096 }
1097 return nullptr;
1098}
1099
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001100Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1101 Instruction *ExtInst;
1102 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1103 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1104 return nullptr;
1105
1106 auto ExtOpcode = ExtInst->getOpcode();
1107 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1108 return nullptr;
1109
Sanjay Patel453ceff2016-09-29 22:18:30 +00001110 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001111 Value *X = ExtInst->getOperand(0);
1112 Type *SmallType = X->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001113 if (!SmallType->isIntOrIntVectorTy(1))
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001114 return nullptr;
1115
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001116 Constant *C;
1117 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1118 !match(Sel.getFalseValue(), m_Constant(C)))
1119 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001120
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001121 // If the constant is the same after truncation to the smaller type and
1122 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001123 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001124 Type *SelType = Sel.getType();
1125 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1126 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1127 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001128 Value *TruncCVal = cast<Value>(TruncC);
1129 if (ExtInst == Sel.getFalseValue())
1130 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001131
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001132 // select Cond, (ext X), C --> ext(select Cond, X, C')
1133 // select Cond, C, (ext X) --> ext(select Cond, C', X)
Craig Topperbb4069e2017-07-07 23:16:26 +00001134 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001135 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +00001136 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001137
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001138 // If one arm of the select is the extend of the condition, replace that arm
1139 // with the extension of the appropriate known bool value.
1140 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001141 if (ExtInst == Sel.getTrueValue()) {
1142 // select X, (sext X), C --> select X, -1, C
1143 // select X, (zext X), C --> select X, 1, C
1144 Constant *One = ConstantInt::getTrue(SmallType);
1145 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001146 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001147 } else {
1148 // select X, C, (sext X) --> select X, C, 0
1149 // select X, C, (zext X) --> select X, C, 0
1150 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001151 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001152 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001153 }
1154
Sanjay Patel453ceff2016-09-29 22:18:30 +00001155 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001156}
1157
Sanjay Patelf26710d2016-09-16 22:16:18 +00001158/// Try to transform a vector select with a constant condition vector into a
1159/// shuffle for easier combining with other shuffles and insert/extract.
1160static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1161 Value *CondVal = SI.getCondition();
1162 Constant *CondC;
1163 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1164 return nullptr;
1165
1166 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1167 SmallVector<Constant *, 16> Mask;
1168 Mask.reserve(NumElts);
1169 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1170 for (unsigned i = 0; i != NumElts; ++i) {
1171 Constant *Elt = CondC->getAggregateElement(i);
1172 if (!Elt)
1173 return nullptr;
1174
1175 if (Elt->isOneValue()) {
1176 // If the select condition element is true, choose from the 1st vector.
1177 Mask.push_back(ConstantInt::get(Int32Ty, i));
1178 } else if (Elt->isNullValue()) {
1179 // If the select condition element is false, choose from the 2nd vector.
1180 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1181 } else if (isa<UndefValue>(Elt)) {
Sanjay Patel6e410182017-04-12 18:39:53 +00001182 // Undef in a select condition (choose one of the operands) does not mean
1183 // the same thing as undef in a shuffle mask (any value is acceptable), so
1184 // give up.
1185 return nullptr;
Sanjay Patelf26710d2016-09-16 22:16:18 +00001186 } else {
1187 // Bail out on a constant expression.
1188 return nullptr;
1189 }
1190 }
1191
1192 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1193 ConstantVector::get(Mask));
1194}
1195
Sanjay Patel978f8272016-10-29 15:22:04 +00001196/// Reuse bitcasted operands between a compare and select:
1197/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1198/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1199static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1200 InstCombiner::BuilderTy &Builder) {
1201 Value *Cond = Sel.getCondition();
1202 Value *TVal = Sel.getTrueValue();
1203 Value *FVal = Sel.getFalseValue();
1204
1205 CmpInst::Predicate Pred;
1206 Value *A, *B;
1207 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1208 return nullptr;
1209
1210 // The select condition is a compare instruction. If the select's true/false
1211 // values are already the same as the compare operands, there's nothing to do.
1212 if (TVal == A || TVal == B || FVal == A || FVal == B)
1213 return nullptr;
1214
1215 Value *C, *D;
1216 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1217 return nullptr;
1218
1219 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1220 Value *TSrc, *FSrc;
1221 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1222 !match(FVal, m_BitCast(m_Value(FSrc))))
1223 return nullptr;
1224
1225 // If the select true/false values are *different bitcasts* of the same source
1226 // operands, make the select operands the same as the compare operands and
1227 // cast the result. This is the canonical select form for min/max.
1228 Value *NewSel;
1229 if (TSrc == C && FSrc == D) {
1230 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1231 // bitcast (select (cmp A, B), A, B)
1232 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1233 } else if (TSrc == D && FSrc == C) {
1234 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1235 // bitcast (select (cmp A, B), B, A)
1236 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1237 } else {
1238 return nullptr;
1239 }
1240 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1241}
1242
Matthew Simpsonb6915fb2017-10-31 12:34:02 +00001243/// Try to eliminate select instructions that test the returned flag of cmpxchg
1244/// instructions.
1245///
1246/// If a select instruction tests the returned flag of a cmpxchg instruction and
1247/// selects between the returned value of the cmpxchg instruction its compare
1248/// operand, the result of the select will always be equal to its false value.
1249/// For example:
1250///
1251/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1252/// %1 = extractvalue { i64, i1 } %0, 1
1253/// %2 = extractvalue { i64, i1 } %0, 0
1254/// %3 = select i1 %1, i64 %compare, i64 %2
1255/// ret i64 %3
1256///
1257/// The returned value of the cmpxchg instruction (%2) is the original value
1258/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1259/// must have been equal to %compare. Thus, the result of the select is always
1260/// equal to %2, and the code can be simplified to:
1261///
1262/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1263/// %1 = extractvalue { i64, i1 } %0, 0
1264/// ret i64 %1
1265///
1266static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1267 // A helper that determines if V is an extractvalue instruction whose
1268 // aggregate operand is a cmpxchg instruction and whose single index is equal
1269 // to I. If such conditions are true, the helper returns the cmpxchg
1270 // instruction; otherwise, a nullptr is returned.
1271 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1272 auto *Extract = dyn_cast<ExtractValueInst>(V);
1273 if (!Extract)
1274 return nullptr;
1275 if (Extract->getIndices()[0] != I)
1276 return nullptr;
1277 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1278 };
1279
1280 // If the select has a single user, and this user is a select instruction that
1281 // we can simplify, skip the cmpxchg simplification for now.
1282 if (SI.hasOneUse())
1283 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1284 if (Select->getCondition() == SI.getCondition())
1285 if (Select->getFalseValue() == SI.getTrueValue() ||
1286 Select->getTrueValue() == SI.getFalseValue())
1287 return nullptr;
1288
1289 // Ensure the select condition is the returned flag of a cmpxchg instruction.
1290 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1291 if (!CmpXchg)
1292 return nullptr;
1293
1294 // Check the true value case: The true value of the select is the returned
1295 // value of the same cmpxchg used by the condition, and the false value is the
1296 // cmpxchg instruction's compare operand.
1297 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1298 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1299 SI.setTrueValue(SI.getFalseValue());
1300 return &SI;
1301 }
1302
1303 // Check the false value case: The false value of the select is the returned
1304 // value of the same cmpxchg used by the condition, and the true value is the
1305 // cmpxchg instruction's compare operand.
1306 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1307 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1308 SI.setTrueValue(SI.getFalseValue());
1309 return &SI;
1310 }
1311
1312 return nullptr;
1313}
1314
Sanjay Patel31b4b762018-01-08 15:05:34 +00001315/// Reduce a sequence of min/max with a common operand.
1316static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1317 Value *RHS,
1318 InstCombiner::BuilderTy &Builder) {
1319 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1320 // TODO: Allow FP min/max with nnan/nsz.
1321 if (!LHS->getType()->isIntOrIntVectorTy())
1322 return nullptr;
1323
1324 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1325 Value *A, *B, *C, *D;
1326 SelectPatternResult L = matchSelectPattern(LHS, A, B);
1327 SelectPatternResult R = matchSelectPattern(RHS, C, D);
1328 if (SPF != L.Flavor || L.Flavor != R.Flavor)
1329 return nullptr;
1330
1331 // Look for a common operand. The use checks are different than usual because
1332 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1333 // the select.
1334 Value *MinMaxOp = nullptr;
1335 Value *ThirdOp = nullptr;
Craig Topperee99aa42018-03-12 18:46:05 +00001336 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
Sanjay Patel31b4b762018-01-08 15:05:34 +00001337 // If the LHS is only used in this chain and the RHS is used outside of it,
1338 // reuse the RHS min/max because that will eliminate the LHS.
1339 if (D == A || C == A) {
1340 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1341 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1342 MinMaxOp = RHS;
1343 ThirdOp = B;
1344 } else if (D == B || C == B) {
1345 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1346 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1347 MinMaxOp = RHS;
1348 ThirdOp = A;
1349 }
Craig Topperee99aa42018-03-12 18:46:05 +00001350 } else if (!RHS->hasNUsesOrMore(3)) {
Sanjay Patel31b4b762018-01-08 15:05:34 +00001351 // Reuse the LHS. This will eliminate the RHS.
1352 if (D == A || D == B) {
1353 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1354 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1355 MinMaxOp = LHS;
1356 ThirdOp = C;
1357 } else if (C == A || C == B) {
1358 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1359 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1360 MinMaxOp = LHS;
1361 ThirdOp = D;
1362 }
1363 }
1364 if (!MinMaxOp || !ThirdOp)
1365 return nullptr;
1366
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001367 CmpInst::Predicate P = getMinMaxPred(SPF);
Sanjay Patel31b4b762018-01-08 15:05:34 +00001368 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1369 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1370}
1371
Chris Lattner8f771cb2010-01-05 06:03:12 +00001372Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1373 Value *CondVal = SI.getCondition();
1374 Value *TrueVal = SI.getTrueValue();
1375 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001376 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001377
Wei Mifc0e2452017-07-25 23:37:17 +00001378 // FIXME: Remove this workaround when freeze related patches are done.
1379 // For select with undef operand which feeds into an equality comparison,
1380 // don't simplify it so loop unswitch can know the equality comparison
1381 // may have an undef operand. This is a workaround for PR31652 caused by
1382 // descrepancy about branch on undef between LoopUnswitch and GVN.
1383 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001384 if (llvm::any_of(SI.users(), [&](User *U) {
Wei Mifc0e2452017-07-25 23:37:17 +00001385 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1386 if (CI && CI->isEquality())
1387 return true;
1388 return false;
1389 })) {
1390 return nullptr;
1391 }
1392 }
1393
Craig Toppera4205622017-06-09 03:21:29 +00001394 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1395 SQ.getWithInstruction(&SI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001396 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001397
Sanjay Patelf26710d2016-09-16 22:16:18 +00001398 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1399 return I;
1400
Sanjay Patel72272762017-06-27 17:53:22 +00001401 // Canonicalize a one-use integer compare with a non-canonical predicate by
1402 // inverting the predicate and swapping the select operands. This matches a
1403 // compare canonicalization for conditional branches.
1404 // TODO: Should we do the same for FP compares?
1405 CmpInst::Predicate Pred;
1406 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1407 !isCanonicalPredicate(Pred)) {
1408 // Swap true/false values and condition.
1409 CmpInst *Cond = cast<CmpInst>(CondVal);
1410 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1411 SI.setOperand(1, FalseVal);
1412 SI.setOperand(2, TrueVal);
1413 SI.swapProfMetadata();
1414 Worklist.Add(Cond);
1415 return &SI;
1416 }
1417
Craig Topperfde47232017-07-09 07:04:03 +00001418 if (SelType->isIntOrIntVectorTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001419 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001420 if (match(TrueVal, m_One())) {
1421 // Change: A = select B, true, C --> A = or B, C
1422 return BinaryOperator::CreateOr(CondVal, FalseVal);
1423 }
1424 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001425 // Change: A = select B, false, C --> A = and !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001426 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001427 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001428 }
Sanjay Patelea234362016-07-06 21:01:26 +00001429 if (match(FalseVal, m_Zero())) {
1430 // Change: A = select B, C, false --> A = and B, C
1431 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1432 }
1433 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001434 // Change: A = select B, C, true --> A = or !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001435 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001436 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001437 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001438
Sanjay Patela1a4e102016-07-03 14:08:19 +00001439 // select a, a, b -> a | b
1440 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001441 if (CondVal == TrueVal)
1442 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001443 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001444 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001445
Sanjay Patela1a4e102016-07-03 14:08:19 +00001446 // select a, ~a, b -> (~a) & b
1447 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001448 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1449 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001450 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001451 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001452 }
1453
Sanjay Patel65a51c22016-07-06 22:23:01 +00001454 // Selecting between two integer or vector splat integer constants?
1455 //
1456 // Note that we don't handle a scalar select of vectors:
1457 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1458 // because that may need 3 instructions to splat the condition value:
1459 // extend, insertelement, shufflevector.
Craig Toppere79b3e72017-07-09 03:25:17 +00001460 if (SelType->isIntOrIntVectorTy() &&
1461 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001462 // select C, 1, 0 -> zext C to int
1463 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001464 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001465
1466 // select C, -1, 0 -> sext C to int
1467 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001468 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001469
1470 // select C, 0, 1 -> zext !C to int
1471 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001472 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001473 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001474 }
1475
1476 // select C, 0, -1 -> sext !C to int
1477 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001478 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001479 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001480 }
1481 }
1482
Chris Lattner8f771cb2010-01-05 06:03:12 +00001483 // See if we are selecting two values based on a comparison of the two values.
1484 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1485 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1486 // Transform (X == Y) ? X : Y -> Y
1487 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001488 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001489 // consider X== -0, Y== +0.
1490 // It becomes safe if either operand is a nonzero constant.
1491 ConstantFP *CFPt, *CFPf;
1492 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1493 !CFPt->getValueAPF().isZero()) ||
1494 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1495 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001496 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001497 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001498 // Transform (X une Y) ? X : Y -> X
1499 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001500 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001501 // consider X== -0, Y== +0.
1502 // It becomes safe if either operand is a nonzero constant.
1503 ConstantFP *CFPt, *CFPf;
1504 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1505 !CFPt->getValueAPF().isZero()) ||
1506 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1507 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001508 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001509 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001510
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001511 // Canonicalize to use ordered comparisons by swapping the select
1512 // operands.
1513 //
1514 // e.g.
1515 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1516 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1517 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001518 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1519 Builder.setFastMathFlags(FCI->getFastMathFlags());
1520 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1521 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001522
1523 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1524 SI.getName() + ".p");
1525 }
1526
1527 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001528 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1529 // Transform (X == Y) ? Y : X -> X
1530 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001531 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001532 // consider X== -0, Y== +0.
1533 // It becomes safe if either operand is a nonzero constant.
1534 ConstantFP *CFPt, *CFPf;
1535 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1536 !CFPt->getValueAPF().isZero()) ||
1537 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1538 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001539 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001540 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001541 // Transform (X une Y) ? Y : X -> Y
1542 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001543 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001544 // consider X== -0, Y== +0.
1545 // It becomes safe if either operand is a nonzero constant.
1546 ConstantFP *CFPt, *CFPf;
1547 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1548 !CFPt->getValueAPF().isZero()) ||
1549 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1550 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001551 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001552 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001553
1554 // Canonicalize to use ordered comparisons by swapping the select
1555 // operands.
1556 //
1557 // e.g.
1558 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1559 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1560 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001561 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1562 Builder.setFastMathFlags(FCI->getFastMathFlags());
1563 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1564 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001565
1566 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1567 SI.getName() + ".p");
1568 }
1569
Chris Lattner8f771cb2010-01-05 06:03:12 +00001570 // NOTE: if we wanted to, this is where to detect MIN/MAX
1571 }
1572 // NOTE: if we wanted to, this is where to detect ABS
1573 }
1574
1575 // See if we are selecting two values based on a comparison of the two values.
1576 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001577 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001578 return Result;
1579
Craig Topperbb4069e2017-07-07 23:16:26 +00001580 if (Instruction *Add = foldAddSubSelect(SI, Builder))
Sanjay Patel39293132016-06-08 21:10:01 +00001581 return Add;
1582
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001583 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001584 auto *TI = dyn_cast<Instruction>(TrueVal);
1585 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001586 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001587 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001588 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001589
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001590 if (Instruction *I = foldSelectExtConst(SI))
1591 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001592
Chris Lattner8f771cb2010-01-05 06:03:12 +00001593 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001594 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001595 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001596 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001597
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001598 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001599 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001600 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1601 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001602
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001603 if (SelectPatternResult::isMinOrMax(SPF)) {
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001604 // Canonicalize so that
1605 // - type casts are outside select patterns.
1606 // - float clamp is transformed to min/max pattern
1607
1608 bool IsCastNeeded = LHS->getType() != SelType;
1609 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1610 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1611 if (IsCastNeeded ||
1612 (LHS->getType()->isFPOrFPVectorTy() &&
1613 ((CmpLHS != LHS && CmpLHS != RHS) ||
1614 (CmpRHS != LHS && CmpRHS != RHS)))) {
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001615 CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
James Molloy134bec22015-08-11 09:12:57 +00001616
1617 Value *Cmp;
1618 if (CmpInst::isIntPredicate(Pred)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001619 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001620 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00001621 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
James Molloy134bec22015-08-11 09:12:57 +00001622 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Craig Topperbb4069e2017-07-07 23:16:26 +00001623 Builder.setFastMathFlags(FMF);
1624 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001625 }
1626
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001627 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1628 if (!IsCastNeeded)
1629 return replaceInstUsesWith(SI, NewSI);
1630
1631 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1632 return replaceInstUsesWith(SI, NewCast);
James Molloy2b21a7c2015-05-20 18:41:25 +00001633 }
Sanjay Patel5b6aacf2018-01-05 19:01:17 +00001634
1635 // MAX(~a, ~b) -> ~MIN(a, b)
1636 // MIN(~a, ~b) -> ~MAX(a, b)
1637 Value *A, *B;
Sanjay Patel26a6fcd2018-01-06 17:34:22 +00001638 if (match(LHS, m_Not(m_Value(A))) && match(RHS, m_Not(m_Value(B))) &&
1639 (LHS->getNumUses() <= 2 || RHS->getNumUses() <= 2)) {
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001640 CmpInst::Predicate InvertedPred = getInverseMinMaxPred(SPF);
Sanjay Patel5b6aacf2018-01-05 19:01:17 +00001641 Value *InvertedCmp = Builder.CreateICmp(InvertedPred, A, B);
1642 Value *NewSel = Builder.CreateSelect(InvertedCmp, A, B);
1643 return BinaryOperator::CreateNot(NewSel);
1644 }
Sanjay Patel31b4b762018-01-08 15:05:34 +00001645
1646 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1647 return I;
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001648 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001649
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001650 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001651 // MAX(MAX(a, b), a) -> MAX(a, b)
1652 // MIN(MIN(a, b), a) -> MIN(a, b)
1653 // MAX(MIN(a, b), a) -> a
1654 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001655 // ABS(ABS(a)) -> ABS(a)
1656 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001657 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001658 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001659 SI, SPF, RHS))
1660 return R;
James Molloy134bec22015-08-11 09:12:57 +00001661 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001662 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001663 SI, SPF, LHS))
1664 return R;
1665 }
1666
1667 // TODO.
1668 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001669 }
1670
1671 // See if we can fold the select into a phi node if the condition is a select.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001672 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001673 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001674 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1675 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Craig Topperfb71b7d2017-04-14 19:20:12 +00001676 if (Instruction *NV = foldOpIntoPhi(SI, PN))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001677 return NV;
1678
Nick Lewyckyb074e322011-01-28 03:28:10 +00001679 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001680 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1681 // select(C, select(C, a, b), c) -> select(C, a, c)
1682 if (TrueSI->getCondition() == CondVal) {
1683 if (SI.getTrueValue() == TrueSI->getTrueValue())
1684 return nullptr;
1685 SI.setOperand(1, TrueSI->getTrueValue());
1686 return &SI;
1687 }
1688 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1689 // We choose this as normal form to enable folding on the And and shortening
1690 // paths for the values (this helps GetUnderlyingObjects() for example).
1691 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001692 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001693 SI.setOperand(0, And);
1694 SI.setOperand(1, TrueSI->getTrueValue());
1695 return &SI;
1696 }
Matthias Braun2e404592015-02-06 17:49:36 +00001697 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001698 }
1699 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001700 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1701 // select(C, a, select(C, b, c)) -> select(C, a, c)
1702 if (FalseSI->getCondition() == CondVal) {
1703 if (SI.getFalseValue() == FalseSI->getFalseValue())
1704 return nullptr;
1705 SI.setOperand(2, FalseSI->getFalseValue());
1706 return &SI;
1707 }
1708 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1709 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001710 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001711 SI.setOperand(0, Or);
1712 SI.setOperand(2, FalseSI->getFalseValue());
1713 return &SI;
1714 }
Matthias Braun2e404592015-02-06 17:49:36 +00001715 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001716 }
1717
Craig Topper1c19cc12018-02-14 18:08:33 +00001718 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1719 // The select might be preventing a division by 0.
1720 switch (BO->getOpcode()) {
1721 default:
1722 return true;
1723 case Instruction::SRem:
1724 case Instruction::URem:
1725 case Instruction::SDiv:
1726 case Instruction::UDiv:
1727 return false;
1728 }
1729 };
1730
Craig Topperf7b86722017-11-15 05:23:02 +00001731 // Try to simplify a binop sandwiched between 2 selects with the same
1732 // condition.
1733 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1734 BinaryOperator *TrueBO;
Craig Topper1c19cc12018-02-14 18:08:33 +00001735 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1736 canMergeSelectThroughBinop(TrueBO)) {
Craig Topperf7b86722017-11-15 05:23:02 +00001737 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1738 if (TrueBOSI->getCondition() == CondVal) {
1739 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1740 Worklist.Add(TrueBO);
1741 return &SI;
1742 }
1743 }
1744 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1745 if (TrueBOSI->getCondition() == CondVal) {
1746 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1747 Worklist.Add(TrueBO);
1748 return &SI;
1749 }
1750 }
1751 }
1752
1753 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1754 BinaryOperator *FalseBO;
Craig Topper1c19cc12018-02-14 18:08:33 +00001755 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1756 canMergeSelectThroughBinop(FalseBO)) {
Craig Topperf7b86722017-11-15 05:23:02 +00001757 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1758 if (FalseBOSI->getCondition() == CondVal) {
1759 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1760 Worklist.Add(FalseBO);
1761 return &SI;
1762 }
1763 }
1764 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1765 if (FalseBOSI->getCondition() == CondVal) {
1766 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1767 Worklist.Add(FalseBO);
1768 return &SI;
1769 }
1770 }
1771 }
1772
Chris Lattner8f771cb2010-01-05 06:03:12 +00001773 if (BinaryOperator::isNot(CondVal)) {
1774 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1775 SI.setOperand(1, FalseVal);
1776 SI.setOperand(2, TrueVal);
1777 return &SI;
1778 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001779
Sanjay Patel4e463b42016-09-06 18:16:31 +00001780 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001781 unsigned VWidth = VecTy->getNumElements();
1782 APInt UndefElts(VWidth, 0);
1783 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1784 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1785 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001786 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001787 return &SI;
1788 }
1789 }
1790
Chad Rosiercd62bf52016-04-29 21:12:31 +00001791 // See if we can determine the result of this select based on a dominating
1792 // condition.
1793 BasicBlock *Parent = SI.getParent();
1794 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1795 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1796 if (PBI && PBI->isConditional() &&
1797 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1798 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
Chad Rosierdfd1de62017-08-01 20:18:54 +00001799 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
Chad Rosiercd62bf52016-04-29 21:12:31 +00001800 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00001801 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
Chad Rosiercd62bf52016-04-29 21:12:31 +00001802 if (Implication) {
1803 Value *V = *Implication ? TrueVal : FalseVal;
1804 return replaceInstUsesWith(SI, V);
1805 }
1806 }
1807 }
1808
Sanjay Patel51783632017-01-13 17:02:42 +00001809 // If we can compute the condition, there's no need for a select.
1810 // Like the above fold, we are attempting to reduce compile-time cost by
1811 // putting this fold here with limitations rather than in InstSimplify.
1812 // The motivation for this call into value tracking is to take advantage of
1813 // the assumption cache, so make sure that is populated.
1814 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001815 KnownBits Known(1);
1816 computeKnownBits(CondVal, Known, 0, &SI);
Craig Topper73ba1c82017-06-07 07:40:37 +00001817 if (Known.One.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001818 return replaceInstUsesWith(SI, TrueVal);
Craig Topper73ba1c82017-06-07 07:40:37 +00001819 if (Known.Zero.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001820 return replaceInstUsesWith(SI, FalseVal);
1821 }
1822
Craig Topperbb4069e2017-07-07 23:16:26 +00001823 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
Sanjay Patel978f8272016-10-29 15:22:04 +00001824 return BitCastSel;
1825
Matthew Simpsonb6915fb2017-10-31 12:34:02 +00001826 // Simplify selects that test the returned flag of cmpxchg instructions.
1827 if (Instruction *Select = foldSelectCmpXchg(SI))
1828 return Select;
1829
Craig Topperf40110f2014-04-25 05:29:35 +00001830 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001831}