1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
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 //
10 // This file implements the visitSelect function.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #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"
20 #include "llvm/Analysis/CmpInstAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #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"
34 #include "llvm/IR/PatternMatch.h"
35 #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"
40 #include "llvm/Support/KnownBits.h"
41 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42 #include <cassert>
43 #include <utility>
44
45 using namespace llvm;
46 using namespace PatternMatch;
47
48 #define DEBUG_TYPE "instcombine"
49
createMinMax(InstCombiner::BuilderTy & Builder,SelectPatternFlavor SPF,Value * A,Value * B)50 static 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");
54 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
55 }
56
57 /// Replace a select operand based on an equality comparison with the identity
58 /// constant of a binop.
foldSelectBinOpIdentity(SelectInst & Sel,const TargetLibraryInfo & TLI)59 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
60 const TargetLibraryInfo &TLI) {
61 // The select condition must be an equality compare with a constant operand.
62 Value *X;
63 Constant *C;
64 CmpInst::Predicate Pred;
65 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
66 return nullptr;
67
68 bool IsEq;
69 if (ICmpInst::isEquality(Pred))
70 IsEq = Pred == ICmpInst::ICMP_EQ;
71 else if (Pred == FCmpInst::FCMP_OEQ)
72 IsEq = true;
73 else if (Pred == FCmpInst::FCMP_UNE)
74 IsEq = false;
75 else
76 return nullptr;
77
78 // A select operand must be a binop.
79 BinaryOperator *BO;
80 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
81 return nullptr;
82
83 // The compare constant must be the identity constant for that binop.
84 // If this a floating-point compare with 0.0, any zero constant will do.
85 Type *Ty = BO->getType();
86 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
87 if (IdC != C) {
88 if (!IdC || !CmpInst::isFPPredicate(Pred))
89 return nullptr;
90 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
91 return nullptr;
92 }
93
94 // Last, match the compare variable operand with a binop operand.
95 Value *Y;
96 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
97 return nullptr;
98 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
99 return nullptr;
100
101 // +0.0 compares equal to -0.0, and so it does not behave as required for this
102 // transform. Bail out if we can not exclude that possibility.
103 if (isa<FPMathOperator>(BO))
104 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
105 return nullptr;
106
107 // BO = binop Y, X
108 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
109 // =>
110 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
111 Sel.setOperand(IsEq ? 1 : 2, Y);
112 return &Sel;
113 }
114
115 /// This folds:
116 /// select (icmp eq (and X, C1)), TC, FC
117 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
118 /// To something like:
119 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
120 /// Or:
121 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
122 /// With some variations depending if FC is larger than TC, or the shift
123 /// isn't needed, or the bit widths don't match.
foldSelectICmpAnd(SelectInst & Sel,ICmpInst * Cmp,InstCombiner::BuilderTy & Builder)124 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
125 InstCombiner::BuilderTy &Builder) {
126 const APInt *SelTC, *SelFC;
127 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
128 !match(Sel.getFalseValue(), m_APInt(SelFC)))
129 return nullptr;
130
131 // If this is a vector select, we need a vector compare.
132 Type *SelType = Sel.getType();
133 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
134 return nullptr;
135
136 Value *V;
137 APInt AndMask;
138 bool CreateAnd = false;
139 ICmpInst::Predicate Pred = Cmp->getPredicate();
140 if (ICmpInst::isEquality(Pred)) {
141 if (!match(Cmp->getOperand(1), m_Zero()))
142 return nullptr;
143
144 V = Cmp->getOperand(0);
145 const APInt *AndRHS;
146 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
147 return nullptr;
148
149 AndMask = *AndRHS;
150 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
151 Pred, V, AndMask)) {
152 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
153 if (!AndMask.isPowerOf2())
154 return nullptr;
155
156 CreateAnd = true;
157 } else {
158 return nullptr;
159 }
160
161 // In general, when both constants are non-zero, we would need an offset to
162 // replace the select. This would require more instructions than we started
163 // with. But there's one special-case that we handle here because it can
164 // simplify/reduce the instructions.
165 APInt TC = *SelTC;
166 APInt FC = *SelFC;
167 if (!TC.isNullValue() && !FC.isNullValue()) {
168 // If the select constants differ by exactly one bit and that's the same
169 // bit that is masked and checked by the select condition, the select can
170 // be replaced by bitwise logic to set/clear one bit of the constant result.
171 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
172 return nullptr;
173 if (CreateAnd) {
174 // If we have to create an 'and', then we must kill the cmp to not
175 // increase the instruction count.
176 if (!Cmp->hasOneUse())
177 return nullptr;
178 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
179 }
180 bool ExtraBitInTC = TC.ugt(FC);
181 if (Pred == ICmpInst::ICMP_EQ) {
182 // If the masked bit in V is clear, clear or set the bit in the result:
183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
184 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
185 Constant *C = ConstantInt::get(SelType, TC);
186 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
187 }
188 if (Pred == ICmpInst::ICMP_NE) {
189 // If the masked bit in V is set, set or clear the bit in the result:
190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
191 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
192 Constant *C = ConstantInt::get(SelType, FC);
193 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
194 }
195 llvm_unreachable("Only expecting equality predicates");
196 }
197
198 // Make sure one of the select arms is a power-of-2.
199 if (!TC.isPowerOf2() && !FC.isPowerOf2())
200 return nullptr;
201
202 // Determine which shift is needed to transform result of the 'and' into the
203 // desired result.
204 const APInt &ValC = !TC.isNullValue() ? TC : FC;
205 unsigned ValZeros = ValC.logBase2();
206 unsigned AndZeros = AndMask.logBase2();
207
208 // Insert the 'and' instruction on the input to the truncate.
209 if (CreateAnd)
210 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
211
212 // If types don't match, we can still convert the select by introducing a zext
213 // or a trunc of the 'and'.
214 if (ValZeros > AndZeros) {
215 V = Builder.CreateZExtOrTrunc(V, SelType);
216 V = Builder.CreateShl(V, ValZeros - AndZeros);
217 } else if (ValZeros < AndZeros) {
218 V = Builder.CreateLShr(V, AndZeros - ValZeros);
219 V = Builder.CreateZExtOrTrunc(V, SelType);
220 } else {
221 V = Builder.CreateZExtOrTrunc(V, SelType);
222 }
223
224 // Okay, now we know that everything is set up, we just don't know whether we
225 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
226 bool ShouldNotVal = !TC.isNullValue();
227 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
228 if (ShouldNotVal)
229 V = Builder.CreateXor(V, ValC);
230
231 return V;
232 }
233
234 /// We want to turn code that looks like this:
235 /// %C = or %A, %B
236 /// %D = select %cond, %C, %A
237 /// into:
238 /// %C = select %cond, %B, 0
239 /// %D = or %A, %C
240 ///
241 /// Assuming that the specified instruction is an operand to the select, return
242 /// a bitmask indicating which operands of this instruction are foldable if they
243 /// equal the other incoming value of the select.
getSelectFoldableOperands(BinaryOperator * I)244 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
245 switch (I->getOpcode()) {
246 case Instruction::Add:
247 case Instruction::Mul:
248 case Instruction::And:
249 case Instruction::Or:
250 case Instruction::Xor:
251 return 3; // Can fold through either operand.
252 case Instruction::Sub: // Can only fold on the amount subtracted.
253 case Instruction::Shl: // Can only fold on the shift amount.
254 case Instruction::LShr:
255 case Instruction::AShr:
256 return 1;
257 default:
258 return 0; // Cannot fold
259 }
260 }
261
262 /// For the same transformation as the previous function, return the identity
263 /// constant that goes into the select.
getSelectFoldableConstant(BinaryOperator * I)264 static APInt getSelectFoldableConstant(BinaryOperator *I) {
265 switch (I->getOpcode()) {
266 default: llvm_unreachable("This cannot happen!");
267 case Instruction::Add:
268 case Instruction::Sub:
269 case Instruction::Or:
270 case Instruction::Xor:
271 case Instruction::Shl:
272 case Instruction::LShr:
273 case Instruction::AShr:
274 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
275 case Instruction::And:
276 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
277 case Instruction::Mul:
278 return APInt(I->getType()->getScalarSizeInBits(), 1);
279 }
280 }
281
282 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
foldSelectOpOp(SelectInst & SI,Instruction * TI,Instruction * FI)283 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
284 Instruction *FI) {
285 // Don't break up min/max patterns. The hasOneUse checks below prevent that
286 // for most cases, but vector min/max with bitcasts can be transformed. If the
287 // one-use restrictions are eased for other patterns, we still don't want to
288 // obfuscate min/max.
289 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
290 match(&SI, m_SMax(m_Value(), m_Value())) ||
291 match(&SI, m_UMin(m_Value(), m_Value())) ||
292 match(&SI, m_UMax(m_Value(), m_Value()))))
293 return nullptr;
294
295 // If this is a cast from the same type, merge.
296 if (TI->getNumOperands() == 1 && TI->isCast()) {
297 Type *FIOpndTy = FI->getOperand(0)->getType();
298 if (TI->getOperand(0)->getType() != FIOpndTy)
299 return nullptr;
300
301 // The select condition may be a vector. We may only change the operand
302 // type if the vector width remains the same (and matches the condition).
303 Type *CondTy = SI.getCondition()->getType();
304 if (CondTy->isVectorTy()) {
305 if (!FIOpndTy->isVectorTy())
306 return nullptr;
307 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
308 return nullptr;
309
310 // TODO: If the backend knew how to deal with casts better, we could
311 // remove this limitation. For now, there's too much potential to create
312 // worse codegen by promoting the select ahead of size-altering casts
313 // (PR28160).
314 //
315 // Note that ValueTracking's matchSelectPattern() looks through casts
316 // without checking 'hasOneUse' when it matches min/max patterns, so this
317 // transform may end up happening anyway.
318 if (TI->getOpcode() != Instruction::BitCast &&
319 (!TI->hasOneUse() || !FI->hasOneUse()))
320 return nullptr;
321 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
322 // TODO: The one-use restrictions for a scalar select could be eased if
323 // the fold of a select in visitLoadInst() was enhanced to match a pattern
324 // that includes a cast.
325 return nullptr;
326 }
327
328 // Fold this by inserting a select from the input values.
329 Value *NewSI =
330 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
331 FI->getOperand(0), SI.getName() + ".v", &SI);
332 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
333 TI->getType());
334 }
335
336 // Only handle binary operators (including two-operand getelementptr) with
337 // one-use here. As with the cast case above, it may be possible to relax the
338 // one-use constraint, but that needs be examined carefully since it may not
339 // reduce the total number of instructions.
340 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
341 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
342 !TI->hasOneUse() || !FI->hasOneUse())
343 return nullptr;
344
345 // Figure out if the operations have any operands in common.
346 Value *MatchOp, *OtherOpT, *OtherOpF;
347 bool MatchIsOpZero;
348 if (TI->getOperand(0) == FI->getOperand(0)) {
349 MatchOp = TI->getOperand(0);
350 OtherOpT = TI->getOperand(1);
351 OtherOpF = FI->getOperand(1);
352 MatchIsOpZero = true;
353 } else if (TI->getOperand(1) == FI->getOperand(1)) {
354 MatchOp = TI->getOperand(1);
355 OtherOpT = TI->getOperand(0);
356 OtherOpF = FI->getOperand(0);
357 MatchIsOpZero = false;
358 } else if (!TI->isCommutative()) {
359 return nullptr;
360 } else if (TI->getOperand(0) == FI->getOperand(1)) {
361 MatchOp = TI->getOperand(0);
362 OtherOpT = TI->getOperand(1);
363 OtherOpF = FI->getOperand(0);
364 MatchIsOpZero = true;
365 } else if (TI->getOperand(1) == FI->getOperand(0)) {
366 MatchOp = TI->getOperand(1);
367 OtherOpT = TI->getOperand(0);
368 OtherOpF = FI->getOperand(1);
369 MatchIsOpZero = true;
370 } else {
371 return nullptr;
372 }
373
374 // If the select condition is a vector, the operands of the original select's
375 // operands also must be vectors. This may not be the case for getelementptr
376 // for example.
377 if (SI.getCondition()->getType()->isVectorTy() &&
378 (!OtherOpT->getType()->isVectorTy() ||
379 !OtherOpF->getType()->isVectorTy()))
380 return nullptr;
381
382 // If we reach here, they do have operations in common.
383 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
384 SI.getName() + ".v", &SI);
385 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
386 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
387 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
388 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
389 NewBO->copyIRFlags(TI);
390 NewBO->andIRFlags(FI);
391 return NewBO;
392 }
393 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
394 auto *FGEP = cast<GetElementPtrInst>(FI);
395 Type *ElementType = TGEP->getResultElementType();
396 return TGEP->isInBounds() && FGEP->isInBounds()
397 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
398 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
399 }
400 llvm_unreachable("Expected BinaryOperator or GEP");
401 return nullptr;
402 }
403
isSelect01(const APInt & C1I,const APInt & C2I)404 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
405 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
406 return false;
407 return C1I.isOneValue() || C1I.isAllOnesValue() ||
408 C2I.isOneValue() || C2I.isAllOnesValue();
409 }
410
411 /// Try to fold the select into one of the operands to allow further
412 /// optimization.
foldSelectIntoOp(SelectInst & SI,Value * TrueVal,Value * FalseVal)413 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
414 Value *FalseVal) {
415 // See the comment above GetSelectFoldableOperands for a description of the
416 // transformation we are doing here.
417 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
418 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
419 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
420 unsigned OpToFold = 0;
421 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
422 OpToFold = 1;
423 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
424 OpToFold = 2;
425 }
426
427 if (OpToFold) {
428 APInt CI = getSelectFoldableConstant(TVI);
429 Value *OOp = TVI->getOperand(2-OpToFold);
430 // Avoid creating select between 2 constants unless it's selecting
431 // between 0, 1 and -1.
432 const APInt *OOpC;
433 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
434 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
435 Value *C = ConstantInt::get(OOp->getType(), CI);
436 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
437 NewSel->takeName(TVI);
438 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
439 FalseVal, NewSel);
440 BO->copyIRFlags(TVI);
441 return BO;
442 }
443 }
444 }
445 }
446 }
447
448 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
449 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
450 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
451 unsigned OpToFold = 0;
452 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
453 OpToFold = 1;
454 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
455 OpToFold = 2;
456 }
457
458 if (OpToFold) {
459 APInt CI = getSelectFoldableConstant(FVI);
460 Value *OOp = FVI->getOperand(2-OpToFold);
461 // Avoid creating select between 2 constants unless it's selecting
462 // between 0, 1 and -1.
463 const APInt *OOpC;
464 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
465 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
466 Value *C = ConstantInt::get(OOp->getType(), CI);
467 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
468 NewSel->takeName(FVI);
469 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
470 TrueVal, NewSel);
471 BO->copyIRFlags(FVI);
472 return BO;
473 }
474 }
475 }
476 }
477 }
478
479 return nullptr;
480 }
481
482 /// We want to turn:
483 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
484 /// into:
485 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
486 /// Note:
487 /// Z may be 0 if lshr is missing.
488 /// Worst-case scenario is that we will replace 5 instructions with 5 different
489 /// instructions, but we got rid of select.
foldSelectICmpAndAnd(Type * SelType,const ICmpInst * Cmp,Value * TVal,Value * FVal,InstCombiner::BuilderTy & Builder)490 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
491 Value *TVal, Value *FVal,
492 InstCombiner::BuilderTy &Builder) {
493 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
494 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
495 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
496 return nullptr;
497
498 // The TrueVal has general form of: and %B, 1
499 Value *B;
500 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
501 return nullptr;
502
503 // Where %B may be optionally shifted: lshr %X, %Z.
504 Value *X, *Z;
505 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
506 if (!HasShift)
507 X = B;
508
509 Value *Y;
510 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
511 return nullptr;
512
513 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
514 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
515 Constant *One = ConstantInt::get(SelType, 1);
516 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
517 Value *FullMask = Builder.CreateOr(Y, MaskB);
518 Value *MaskedX = Builder.CreateAnd(X, FullMask);
519 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
520 return new ZExtInst(ICmpNeZero, SelType);
521 }
522
523 /// We want to turn:
524 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
525 /// into:
526 /// (or (shl (and X, C1), C3), Y)
527 /// iff:
528 /// C1 and C2 are both powers of 2
529 /// where:
530 /// C3 = Log(C2) - Log(C1)
531 ///
532 /// This transform handles cases where:
533 /// 1. The icmp predicate is inverted
534 /// 2. The select operands are reversed
535 /// 3. The magnitude of C2 and C1 are flipped
foldSelectICmpAndOr(const ICmpInst * IC,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)536 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
537 Value *FalseVal,
538 InstCombiner::BuilderTy &Builder) {
539 // Only handle integer compares. Also, if this is a vector select, we need a
540 // vector compare.
541 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
542 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
543 return nullptr;
544
545 Value *CmpLHS = IC->getOperand(0);
546 Value *CmpRHS = IC->getOperand(1);
547
548 Value *V;
549 unsigned C1Log;
550 bool IsEqualZero;
551 bool NeedAnd = false;
552 if (IC->isEquality()) {
553 if (!match(CmpRHS, m_Zero()))
554 return nullptr;
555
556 const APInt *C1;
557 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
558 return nullptr;
559
560 V = CmpLHS;
561 C1Log = C1->logBase2();
562 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
563 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
564 IC->getPredicate() == ICmpInst::ICMP_SGT) {
565 // We also need to recognize (icmp slt (trunc (X)), 0) and
566 // (icmp sgt (trunc (X)), -1).
567 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
568 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
569 (!IsEqualZero && !match(CmpRHS, m_Zero())))
570 return nullptr;
571
572 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
573 return nullptr;
574
575 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
576 NeedAnd = true;
577 } else {
578 return nullptr;
579 }
580
581 const APInt *C2;
582 bool OrOnTrueVal = false;
583 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
584 if (!OrOnFalseVal)
585 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
586
587 if (!OrOnFalseVal && !OrOnTrueVal)
588 return nullptr;
589
590 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
591
592 unsigned C2Log = C2->logBase2();
593
594 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
595 bool NeedShift = C1Log != C2Log;
596 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
597 V->getType()->getScalarSizeInBits();
598
599 // Make sure we don't create more instructions than we save.
600 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
601 if ((NeedShift + NeedXor + NeedZExtTrunc) >
602 (IC->hasOneUse() + Or->hasOneUse()))
603 return nullptr;
604
605 if (NeedAnd) {
606 // Insert the AND instruction on the input to the truncate.
607 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
608 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
609 }
610
611 if (C2Log > C1Log) {
612 V = Builder.CreateZExtOrTrunc(V, Y->getType());
613 V = Builder.CreateShl(V, C2Log - C1Log);
614 } else if (C1Log > C2Log) {
615 V = Builder.CreateLShr(V, C1Log - C2Log);
616 V = Builder.CreateZExtOrTrunc(V, Y->getType());
617 } else
618 V = Builder.CreateZExtOrTrunc(V, Y->getType());
619
620 if (NeedXor)
621 V = Builder.CreateXor(V, *C2);
622
623 return Builder.CreateOr(V, Y);
624 }
625
626 /// Transform patterns such as: (a > b) ? a - b : 0
627 /// into: ((a > b) ? a : b) - b)
628 /// This produces a canonical max pattern that is more easily recognized by the
629 /// backend and converted into saturated subtraction instructions if those
630 /// exist.
631 /// There are 8 commuted/swapped variants of this pattern.
632 /// TODO: Also support a - UMIN(a,b) patterns.
canonicalizeSaturatedSubtract(const ICmpInst * ICI,const Value * TrueVal,const Value * FalseVal,InstCombiner::BuilderTy & Builder)633 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
634 const Value *TrueVal,
635 const Value *FalseVal,
636 InstCombiner::BuilderTy &Builder) {
637 ICmpInst::Predicate Pred = ICI->getPredicate();
638 if (!ICmpInst::isUnsigned(Pred))
639 return nullptr;
640
641 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
642 if (match(TrueVal, m_Zero())) {
643 Pred = ICmpInst::getInversePredicate(Pred);
644 std::swap(TrueVal, FalseVal);
645 }
646 if (!match(FalseVal, m_Zero()))
647 return nullptr;
648
649 Value *A = ICI->getOperand(0);
650 Value *B = ICI->getOperand(1);
651 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
652 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
653 std::swap(A, B);
654 Pred = ICmpInst::getSwappedPredicate(Pred);
655 }
656
657 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
658 "Unexpected isUnsigned predicate!");
659
660 // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
661 bool IsNegative = false;
662 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
663 IsNegative = true;
664 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
665 return nullptr;
666
667 // If sub is used anywhere else, we wouldn't be able to eliminate it
668 // afterwards.
669 if (!TrueVal->hasOneUse())
670 return nullptr;
671
672 // All checks passed, convert to canonical unsigned saturated subtraction
673 // form: sub(max()).
674 // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
675 Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
676 return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
677 }
678
679 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
680 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
681 ///
682 /// For example, we can fold the following code sequence:
683 /// \code
684 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
685 /// %1 = icmp ne i32 %x, 0
686 /// %2 = select i1 %1, i32 %0, i32 32
687 /// \code
688 ///
689 /// into:
690 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
foldSelectCttzCtlz(ICmpInst * ICI,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)691 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
692 InstCombiner::BuilderTy &Builder) {
693 ICmpInst::Predicate Pred = ICI->getPredicate();
694 Value *CmpLHS = ICI->getOperand(0);
695 Value *CmpRHS = ICI->getOperand(1);
696
697 // Check if the condition value compares a value for equality against zero.
698 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
699 return nullptr;
700
701 Value *Count = FalseVal;
702 Value *ValueOnZero = TrueVal;
703 if (Pred == ICmpInst::ICMP_NE)
704 std::swap(Count, ValueOnZero);
705
706 // Skip zero extend/truncate.
707 Value *V = nullptr;
708 if (match(Count, m_ZExt(m_Value(V))) ||
709 match(Count, m_Trunc(m_Value(V))))
710 Count = V;
711
712 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
713 // input to the cttz/ctlz is used as LHS for the compare instruction.
714 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
715 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
716 return nullptr;
717
718 IntrinsicInst *II = cast<IntrinsicInst>(Count);
719
720 // Check if the value propagated on zero is a constant number equal to the
721 // sizeof in bits of 'Count'.
722 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
723 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
724 // Explicitly clear the 'undef_on_zero' flag.
725 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
726 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
727 Builder.Insert(NewI);
728 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
729 }
730
731 // If the ValueOnZero is not the bitwidth, we can at least make use of the
732 // fact that the cttz/ctlz result will not be used if the input is zero, so
733 // it's okay to relax it to undef for that case.
734 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
735 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
736
737 return nullptr;
738 }
739
740 /// Return true if we find and adjust an icmp+select pattern where the compare
741 /// is with a constant that can be incremented or decremented to match the
742 /// minimum or maximum idiom.
adjustMinMax(SelectInst & Sel,ICmpInst & Cmp)743 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
744 ICmpInst::Predicate Pred = Cmp.getPredicate();
745 Value *CmpLHS = Cmp.getOperand(0);
746 Value *CmpRHS = Cmp.getOperand(1);
747 Value *TrueVal = Sel.getTrueValue();
748 Value *FalseVal = Sel.getFalseValue();
749
750 // We may move or edit the compare, so make sure the select is the only user.
751 const APInt *CmpC;
752 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
753 return false;
754
755 // These transforms only work for selects of integers or vector selects of
756 // integer vectors.
757 Type *SelTy = Sel.getType();
758 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
759 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
760 return false;
761
762 Constant *AdjustedRHS;
763 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
764 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
765 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
766 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
767 else
768 return false;
769
770 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
771 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
772 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
773 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
774 ; // Nothing to do here. Values match without any sign/zero extension.
775 }
776 // Types do not match. Instead of calculating this with mixed types, promote
777 // all to the larger type. This enables scalar evolution to analyze this
778 // expression.
779 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
780 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
781
782 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
783 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
784 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
785 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
786 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
787 CmpLHS = TrueVal;
788 AdjustedRHS = SextRHS;
789 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
790 SextRHS == TrueVal) {
791 CmpLHS = FalseVal;
792 AdjustedRHS = SextRHS;
793 } else if (Cmp.isUnsigned()) {
794 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
795 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
796 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
797 // zext + signed compare cannot be changed:
798 // 0xff <s 0x00, but 0x00ff >s 0x0000
799 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
800 CmpLHS = TrueVal;
801 AdjustedRHS = ZextRHS;
802 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
803 ZextRHS == TrueVal) {
804 CmpLHS = FalseVal;
805 AdjustedRHS = ZextRHS;
806 } else {
807 return false;
808 }
809 } else {
810 return false;
811 }
812 } else {
813 return false;
814 }
815
816 Pred = ICmpInst::getSwappedPredicate(Pred);
817 CmpRHS = AdjustedRHS;
818 std::swap(FalseVal, TrueVal);
819 Cmp.setPredicate(Pred);
820 Cmp.setOperand(0, CmpLHS);
821 Cmp.setOperand(1, CmpRHS);
822 Sel.setOperand(1, TrueVal);
823 Sel.setOperand(2, FalseVal);
824 Sel.swapProfMetadata();
825
826 // Move the compare instruction right before the select instruction. Otherwise
827 // the sext/zext value may be defined after the compare instruction uses it.
828 Cmp.moveBefore(&Sel);
829
830 return true;
831 }
832
833 /// If this is an integer min/max (icmp + select) with a constant operand,
834 /// create the canonical icmp for the min/max operation and canonicalize the
835 /// constant to the 'false' operand of the select:
836 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
837 /// Note: if C1 != C2, this will change the icmp constant to the existing
838 /// constant operand of the select.
839 static Instruction *
canonicalizeMinMaxWithConstant(SelectInst & Sel,ICmpInst & Cmp,InstCombiner::BuilderTy & Builder)840 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
841 InstCombiner::BuilderTy &Builder) {
842 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
843 return nullptr;
844
845 // Canonicalize the compare predicate based on whether we have min or max.
846 Value *LHS, *RHS;
847 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
848 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
849 return nullptr;
850
851 // Is this already canonical?
852 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
853 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
854 Cmp.getPredicate() == CanonicalPred)
855 return nullptr;
856
857 // Create the canonical compare and plug it into the select.
858 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
859
860 // If the select operands did not change, we're done.
861 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
862 return &Sel;
863
864 // If we are swapping the select operands, swap the metadata too.
865 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
866 "Unexpected results from matchSelectPattern");
867 Sel.setTrueValue(LHS);
868 Sel.setFalseValue(RHS);
869 Sel.swapProfMetadata();
870 return &Sel;
871 }
872
873 /// There are many select variants for each of ABS/NABS.
874 /// In matchSelectPattern(), there are different compare constants, compare
875 /// predicates/operands and select operands.
876 /// In isKnownNegation(), there are different formats of negated operands.
877 /// Canonicalize all these variants to 1 pattern.
878 /// This makes CSE more likely.
canonicalizeAbsNabs(SelectInst & Sel,ICmpInst & Cmp,InstCombiner::BuilderTy & Builder)879 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
880 InstCombiner::BuilderTy &Builder) {
881 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
882 return nullptr;
883
884 // Choose a sign-bit check for the compare (likely simpler for codegen).
885 // ABS: (X <s 0) ? -X : X
886 // NABS: (X <s 0) ? X : -X
887 Value *LHS, *RHS;
888 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
889 if (SPF != SelectPatternFlavor::SPF_ABS &&
890 SPF != SelectPatternFlavor::SPF_NABS)
891 return nullptr;
892
893 Value *TVal = Sel.getTrueValue();
894 Value *FVal = Sel.getFalseValue();
895 assert(isKnownNegation(TVal, FVal) &&
896 "Unexpected result from matchSelectPattern");
897
898 // The compare may use the negated abs()/nabs() operand, or it may use
899 // negation in non-canonical form such as: sub A, B.
900 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
901 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
902
903 bool CmpCanonicalized = !CmpUsesNegatedOp &&
904 match(Cmp.getOperand(1), m_ZeroInt()) &&
905 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
906 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
907
908 // Is this already canonical?
909 if (CmpCanonicalized && RHSCanonicalized)
910 return nullptr;
911
912 // If RHS is used by other instructions except compare and select, don't
913 // canonicalize it to not increase the instruction count.
914 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
915 return nullptr;
916
917 // Create the canonical compare: icmp slt LHS 0.
918 if (!CmpCanonicalized) {
919 Cmp.setPredicate(ICmpInst::ICMP_SLT);
920 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
921 if (CmpUsesNegatedOp)
922 Cmp.setOperand(0, LHS);
923 }
924
925 // Create the canonical RHS: RHS = sub (0, LHS).
926 if (!RHSCanonicalized) {
927 assert(RHS->hasOneUse() && "RHS use number is not right");
928 RHS = Builder.CreateNeg(LHS);
929 if (TVal == LHS) {
930 Sel.setFalseValue(RHS);
931 FVal = RHS;
932 } else {
933 Sel.setTrueValue(RHS);
934 TVal = RHS;
935 }
936 }
937
938 // If the select operands do not change, we're done.
939 if (SPF == SelectPatternFlavor::SPF_NABS) {
940 if (TVal == LHS)
941 return &Sel;
942 assert(FVal == LHS && "Unexpected results from matchSelectPattern");
943 } else {
944 if (FVal == LHS)
945 return &Sel;
946 assert(TVal == LHS && "Unexpected results from matchSelectPattern");
947 }
948
949 // We are swapping the select operands, so swap the metadata too.
950 Sel.setTrueValue(FVal);
951 Sel.setFalseValue(TVal);
952 Sel.swapProfMetadata();
953 return &Sel;
954 }
955
956 /// Visit a SelectInst that has an ICmpInst as its first operand.
foldSelectInstWithICmp(SelectInst & SI,ICmpInst * ICI)957 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
958 ICmpInst *ICI) {
959 Value *TrueVal = SI.getTrueValue();
960 Value *FalseVal = SI.getFalseValue();
961
962 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
963 return NewSel;
964
965 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
966 return NewAbs;
967
968 bool Changed = adjustMinMax(SI, *ICI);
969
970 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
971 return replaceInstUsesWith(SI, V);
972
973 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
974 ICmpInst::Predicate Pred = ICI->getPredicate();
975 Value *CmpLHS = ICI->getOperand(0);
976 Value *CmpRHS = ICI->getOperand(1);
977 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
978 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
979 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
980 SI.setOperand(1, CmpRHS);
981 Changed = true;
982 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
983 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
984 SI.setOperand(2, CmpRHS);
985 Changed = true;
986 }
987 }
988
989 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
990 // decomposeBitTestICmp() might help.
991 {
992 unsigned BitWidth =
993 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
994 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
995 Value *X;
996 const APInt *Y, *C;
997 bool TrueWhenUnset;
998 bool IsBitTest = false;
999 if (ICmpInst::isEquality(Pred) &&
1000 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1001 match(CmpRHS, m_Zero())) {
1002 IsBitTest = true;
1003 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1004 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1005 X = CmpLHS;
1006 Y = &MinSignedValue;
1007 IsBitTest = true;
1008 TrueWhenUnset = false;
1009 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1010 X = CmpLHS;
1011 Y = &MinSignedValue;
1012 IsBitTest = true;
1013 TrueWhenUnset = true;
1014 }
1015 if (IsBitTest) {
1016 Value *V = nullptr;
1017 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1018 if (TrueWhenUnset && TrueVal == X &&
1019 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1020 V = Builder.CreateAnd(X, ~(*Y));
1021 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1022 else if (!TrueWhenUnset && FalseVal == X &&
1023 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1024 V = Builder.CreateAnd(X, ~(*Y));
1025 // (X & Y) == 0 ? X ^ Y : X --> X | Y
1026 else if (TrueWhenUnset && FalseVal == X &&
1027 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1028 V = Builder.CreateOr(X, *Y);
1029 // (X & Y) != 0 ? X : X ^ Y --> X | Y
1030 else if (!TrueWhenUnset && TrueVal == X &&
1031 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1032 V = Builder.CreateOr(X, *Y);
1033
1034 if (V)
1035 return replaceInstUsesWith(SI, V);
1036 }
1037 }
1038
1039 if (Instruction *V =
1040 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1041 return V;
1042
1043 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1044 return replaceInstUsesWith(SI, V);
1045
1046 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1047 return replaceInstUsesWith(SI, V);
1048
1049 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1050 return replaceInstUsesWith(SI, V);
1051
1052 return Changed ? &SI : nullptr;
1053 }
1054
1055 /// SI is a select whose condition is a PHI node (but the two may be in
1056 /// different blocks). See if the true/false values (V) are live in all of the
1057 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1058 ///
1059 /// X = phi [ C1, BB1], [C2, BB2]
1060 /// Y = add
1061 /// Z = select X, Y, 0
1062 ///
1063 /// because Y is not live in BB1/BB2.
canSelectOperandBeMappingIntoPredBlock(const Value * V,const SelectInst & SI)1064 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1065 const SelectInst &SI) {
1066 // If the value is a non-instruction value like a constant or argument, it
1067 // can always be mapped.
1068 const Instruction *I = dyn_cast<Instruction>(V);
1069 if (!I) return true;
1070
1071 // If V is a PHI node defined in the same block as the condition PHI, we can
1072 // map the arguments.
1073 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1074
1075 if (const PHINode *VP = dyn_cast<PHINode>(I))
1076 if (VP->getParent() == CondPHI->getParent())
1077 return true;
1078
1079 // Otherwise, if the PHI and select are defined in the same block and if V is
1080 // defined in a different block, then we can transform it.
1081 if (SI.getParent() == CondPHI->getParent() &&
1082 I->getParent() != CondPHI->getParent())
1083 return true;
1084
1085 // Otherwise we have a 'hard' case and we can't tell without doing more
1086 // detailed dominator based analysis, punt.
1087 return false;
1088 }
1089
1090 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1091 /// SPF2(SPF1(A, B), C)
foldSPFofSPF(Instruction * Inner,SelectPatternFlavor SPF1,Value * A,Value * B,Instruction & Outer,SelectPatternFlavor SPF2,Value * C)1092 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1093 SelectPatternFlavor SPF1,
1094 Value *A, Value *B,
1095 Instruction &Outer,
1096 SelectPatternFlavor SPF2, Value *C) {
1097 if (Outer.getType() != Inner->getType())
1098 return nullptr;
1099
1100 if (C == A || C == B) {
1101 // MAX(MAX(A, B), B) -> MAX(A, B)
1102 // MIN(MIN(a, b), a) -> MIN(a, b)
1103 // TODO: This could be done in instsimplify.
1104 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1105 return replaceInstUsesWith(Outer, Inner);
1106
1107 // MAX(MIN(a, b), a) -> a
1108 // MIN(MAX(a, b), a) -> a
1109 // TODO: This could be done in instsimplify.
1110 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1111 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1112 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1113 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1114 return replaceInstUsesWith(Outer, C);
1115 }
1116
1117 if (SPF1 == SPF2) {
1118 const APInt *CB, *CC;
1119 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1120 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1121 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1122 // TODO: This could be done in instsimplify.
1123 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1124 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1125 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1126 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1127 return replaceInstUsesWith(Outer, Inner);
1128
1129 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1130 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1131 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1132 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1133 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1134 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1135 Outer.replaceUsesOfWith(Inner, A);
1136 return &Outer;
1137 }
1138 }
1139 }
1140
1141 // ABS(ABS(X)) -> ABS(X)
1142 // NABS(NABS(X)) -> NABS(X)
1143 // TODO: This could be done in instsimplify.
1144 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1145 return replaceInstUsesWith(Outer, Inner);
1146 }
1147
1148 // ABS(NABS(X)) -> ABS(X)
1149 // NABS(ABS(X)) -> NABS(X)
1150 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1151 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1152 SelectInst *SI = cast<SelectInst>(Inner);
1153 Value *NewSI =
1154 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1155 SI->getTrueValue(), SI->getName(), SI);
1156 return replaceInstUsesWith(Outer, NewSI);
1157 }
1158
1159 auto IsFreeOrProfitableToInvert =
1160 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1161 if (match(V, m_Not(m_Value(NotV)))) {
1162 // If V has at most 2 uses then we can get rid of the xor operation
1163 // entirely.
1164 ElidesXor |= !V->hasNUsesOrMore(3);
1165 return true;
1166 }
1167
1168 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1169 NotV = nullptr;
1170 return true;
1171 }
1172
1173 return false;
1174 };
1175
1176 Value *NotA, *NotB, *NotC;
1177 bool ElidesXor = false;
1178
1179 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1180 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1181 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1182 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1183 //
1184 // This transform is performance neutral if we can elide at least one xor from
1185 // the set of three operands, since we'll be tacking on an xor at the very
1186 // end.
1187 if (SelectPatternResult::isMinOrMax(SPF1) &&
1188 SelectPatternResult::isMinOrMax(SPF2) &&
1189 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1190 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1191 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1192 if (!NotA)
1193 NotA = Builder.CreateNot(A);
1194 if (!NotB)
1195 NotB = Builder.CreateNot(B);
1196 if (!NotC)
1197 NotC = Builder.CreateNot(C);
1198
1199 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1200 NotB);
1201 Value *NewOuter = Builder.CreateNot(
1202 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1203 return replaceInstUsesWith(Outer, NewOuter);
1204 }
1205
1206 return nullptr;
1207 }
1208
1209 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1210 /// This is even legal for FP.
foldAddSubSelect(SelectInst & SI,InstCombiner::BuilderTy & Builder)1211 static Instruction *foldAddSubSelect(SelectInst &SI,
1212 InstCombiner::BuilderTy &Builder) {
1213 Value *CondVal = SI.getCondition();
1214 Value *TrueVal = SI.getTrueValue();
1215 Value *FalseVal = SI.getFalseValue();
1216 auto *TI = dyn_cast<Instruction>(TrueVal);
1217 auto *FI = dyn_cast<Instruction>(FalseVal);
1218 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1219 return nullptr;
1220
1221 Instruction *AddOp = nullptr, *SubOp = nullptr;
1222 if ((TI->getOpcode() == Instruction::Sub &&
1223 FI->getOpcode() == Instruction::Add) ||
1224 (TI->getOpcode() == Instruction::FSub &&
1225 FI->getOpcode() == Instruction::FAdd)) {
1226 AddOp = FI;
1227 SubOp = TI;
1228 } else if ((FI->getOpcode() == Instruction::Sub &&
1229 TI->getOpcode() == Instruction::Add) ||
1230 (FI->getOpcode() == Instruction::FSub &&
1231 TI->getOpcode() == Instruction::FAdd)) {
1232 AddOp = TI;
1233 SubOp = FI;
1234 }
1235
1236 if (AddOp) {
1237 Value *OtherAddOp = nullptr;
1238 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1239 OtherAddOp = AddOp->getOperand(1);
1240 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1241 OtherAddOp = AddOp->getOperand(0);
1242 }
1243
1244 if (OtherAddOp) {
1245 // So at this point we know we have (Y -> OtherAddOp):
1246 // select C, (add X, Y), (sub X, Z)
1247 Value *NegVal; // Compute -Z
1248 if (SI.getType()->isFPOrFPVectorTy()) {
1249 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1250 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1251 FastMathFlags Flags = AddOp->getFastMathFlags();
1252 Flags &= SubOp->getFastMathFlags();
1253 NegInst->setFastMathFlags(Flags);
1254 }
1255 } else {
1256 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1257 }
1258
1259 Value *NewTrueOp = OtherAddOp;
1260 Value *NewFalseOp = NegVal;
1261 if (AddOp != TI)
1262 std::swap(NewTrueOp, NewFalseOp);
1263 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1264 SI.getName() + ".p", &SI);
1265
1266 if (SI.getType()->isFPOrFPVectorTy()) {
1267 Instruction *RI =
1268 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1269
1270 FastMathFlags Flags = AddOp->getFastMathFlags();
1271 Flags &= SubOp->getFastMathFlags();
1272 RI->setFastMathFlags(Flags);
1273 return RI;
1274 } else
1275 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1276 }
1277 }
1278 return nullptr;
1279 }
1280
foldSelectExtConst(SelectInst & Sel)1281 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1282 Constant *C;
1283 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1284 !match(Sel.getFalseValue(), m_Constant(C)))
1285 return nullptr;
1286
1287 Instruction *ExtInst;
1288 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1289 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1290 return nullptr;
1291
1292 auto ExtOpcode = ExtInst->getOpcode();
1293 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1294 return nullptr;
1295
1296 // If we are extending from a boolean type or if we can create a select that
1297 // has the same size operands as its condition, try to narrow the select.
1298 Value *X = ExtInst->getOperand(0);
1299 Type *SmallType = X->getType();
1300 Value *Cond = Sel.getCondition();
1301 auto *Cmp = dyn_cast<CmpInst>(Cond);
1302 if (!SmallType->isIntOrIntVectorTy(1) &&
1303 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1304 return nullptr;
1305
1306 // If the constant is the same after truncation to the smaller type and
1307 // extension to the original type, we can narrow the select.
1308 Type *SelType = Sel.getType();
1309 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1310 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1311 if (ExtC == C) {
1312 Value *TruncCVal = cast<Value>(TruncC);
1313 if (ExtInst == Sel.getFalseValue())
1314 std::swap(X, TruncCVal);
1315
1316 // select Cond, (ext X), C --> ext(select Cond, X, C')
1317 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1318 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1319 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1320 }
1321
1322 // If one arm of the select is the extend of the condition, replace that arm
1323 // with the extension of the appropriate known bool value.
1324 if (Cond == X) {
1325 if (ExtInst == Sel.getTrueValue()) {
1326 // select X, (sext X), C --> select X, -1, C
1327 // select X, (zext X), C --> select X, 1, C
1328 Constant *One = ConstantInt::getTrue(SmallType);
1329 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1330 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1331 } else {
1332 // select X, C, (sext X) --> select X, C, 0
1333 // select X, C, (zext X) --> select X, C, 0
1334 Constant *Zero = ConstantInt::getNullValue(SelType);
1335 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1336 }
1337 }
1338
1339 return nullptr;
1340 }
1341
1342 /// Try to transform a vector select with a constant condition vector into a
1343 /// shuffle for easier combining with other shuffles and insert/extract.
canonicalizeSelectToShuffle(SelectInst & SI)1344 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1345 Value *CondVal = SI.getCondition();
1346 Constant *CondC;
1347 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1348 return nullptr;
1349
1350 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1351 SmallVector<Constant *, 16> Mask;
1352 Mask.reserve(NumElts);
1353 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1354 for (unsigned i = 0; i != NumElts; ++i) {
1355 Constant *Elt = CondC->getAggregateElement(i);
1356 if (!Elt)
1357 return nullptr;
1358
1359 if (Elt->isOneValue()) {
1360 // If the select condition element is true, choose from the 1st vector.
1361 Mask.push_back(ConstantInt::get(Int32Ty, i));
1362 } else if (Elt->isNullValue()) {
1363 // If the select condition element is false, choose from the 2nd vector.
1364 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1365 } else if (isa<UndefValue>(Elt)) {
1366 // Undef in a select condition (choose one of the operands) does not mean
1367 // the same thing as undef in a shuffle mask (any value is acceptable), so
1368 // give up.
1369 return nullptr;
1370 } else {
1371 // Bail out on a constant expression.
1372 return nullptr;
1373 }
1374 }
1375
1376 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1377 ConstantVector::get(Mask));
1378 }
1379
1380 /// Reuse bitcasted operands between a compare and select:
1381 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1382 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
foldSelectCmpBitcasts(SelectInst & Sel,InstCombiner::BuilderTy & Builder)1383 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1384 InstCombiner::BuilderTy &Builder) {
1385 Value *Cond = Sel.getCondition();
1386 Value *TVal = Sel.getTrueValue();
1387 Value *FVal = Sel.getFalseValue();
1388
1389 CmpInst::Predicate Pred;
1390 Value *A, *B;
1391 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1392 return nullptr;
1393
1394 // The select condition is a compare instruction. If the select's true/false
1395 // values are already the same as the compare operands, there's nothing to do.
1396 if (TVal == A || TVal == B || FVal == A || FVal == B)
1397 return nullptr;
1398
1399 Value *C, *D;
1400 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1401 return nullptr;
1402
1403 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1404 Value *TSrc, *FSrc;
1405 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1406 !match(FVal, m_BitCast(m_Value(FSrc))))
1407 return nullptr;
1408
1409 // If the select true/false values are *different bitcasts* of the same source
1410 // operands, make the select operands the same as the compare operands and
1411 // cast the result. This is the canonical select form for min/max.
1412 Value *NewSel;
1413 if (TSrc == C && FSrc == D) {
1414 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1415 // bitcast (select (cmp A, B), A, B)
1416 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1417 } else if (TSrc == D && FSrc == C) {
1418 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1419 // bitcast (select (cmp A, B), B, A)
1420 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1421 } else {
1422 return nullptr;
1423 }
1424 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1425 }
1426
1427 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1428 /// instructions.
1429 ///
1430 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1431 /// selects between the returned value of the cmpxchg instruction its compare
1432 /// operand, the result of the select will always be equal to its false value.
1433 /// For example:
1434 ///
1435 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1436 /// %1 = extractvalue { i64, i1 } %0, 1
1437 /// %2 = extractvalue { i64, i1 } %0, 0
1438 /// %3 = select i1 %1, i64 %compare, i64 %2
1439 /// ret i64 %3
1440 ///
1441 /// The returned value of the cmpxchg instruction (%2) is the original value
1442 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1443 /// must have been equal to %compare. Thus, the result of the select is always
1444 /// equal to %2, and the code can be simplified to:
1445 ///
1446 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1447 /// %1 = extractvalue { i64, i1 } %0, 0
1448 /// ret i64 %1
1449 ///
foldSelectCmpXchg(SelectInst & SI)1450 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1451 // A helper that determines if V is an extractvalue instruction whose
1452 // aggregate operand is a cmpxchg instruction and whose single index is equal
1453 // to I. If such conditions are true, the helper returns the cmpxchg
1454 // instruction; otherwise, a nullptr is returned.
1455 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1456 auto *Extract = dyn_cast<ExtractValueInst>(V);
1457 if (!Extract)
1458 return nullptr;
1459 if (Extract->getIndices()[0] != I)
1460 return nullptr;
1461 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1462 };
1463
1464 // If the select has a single user, and this user is a select instruction that
1465 // we can simplify, skip the cmpxchg simplification for now.
1466 if (SI.hasOneUse())
1467 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1468 if (Select->getCondition() == SI.getCondition())
1469 if (Select->getFalseValue() == SI.getTrueValue() ||
1470 Select->getTrueValue() == SI.getFalseValue())
1471 return nullptr;
1472
1473 // Ensure the select condition is the returned flag of a cmpxchg instruction.
1474 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1475 if (!CmpXchg)
1476 return nullptr;
1477
1478 // Check the true value case: The true value of the select is the returned
1479 // value of the same cmpxchg used by the condition, and the false value is the
1480 // cmpxchg instruction's compare operand.
1481 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1482 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1483 SI.setTrueValue(SI.getFalseValue());
1484 return &SI;
1485 }
1486
1487 // Check the false value case: The false value of the select is the returned
1488 // value of the same cmpxchg used by the condition, and the true value is the
1489 // cmpxchg instruction's compare operand.
1490 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1491 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1492 SI.setTrueValue(SI.getFalseValue());
1493 return &SI;
1494 }
1495
1496 return nullptr;
1497 }
1498
1499 /// Reduce a sequence of min/max with a common operand.
factorizeMinMaxTree(SelectPatternFlavor SPF,Value * LHS,Value * RHS,InstCombiner::BuilderTy & Builder)1500 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1501 Value *RHS,
1502 InstCombiner::BuilderTy &Builder) {
1503 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1504 // TODO: Allow FP min/max with nnan/nsz.
1505 if (!LHS->getType()->isIntOrIntVectorTy())
1506 return nullptr;
1507
1508 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1509 Value *A, *B, *C, *D;
1510 SelectPatternResult L = matchSelectPattern(LHS, A, B);
1511 SelectPatternResult R = matchSelectPattern(RHS, C, D);
1512 if (SPF != L.Flavor || L.Flavor != R.Flavor)
1513 return nullptr;
1514
1515 // Look for a common operand. The use checks are different than usual because
1516 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1517 // the select.
1518 Value *MinMaxOp = nullptr;
1519 Value *ThirdOp = nullptr;
1520 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
1521 // If the LHS is only used in this chain and the RHS is used outside of it,
1522 // reuse the RHS min/max because that will eliminate the LHS.
1523 if (D == A || C == A) {
1524 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1525 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1526 MinMaxOp = RHS;
1527 ThirdOp = B;
1528 } else if (D == B || C == B) {
1529 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1530 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1531 MinMaxOp = RHS;
1532 ThirdOp = A;
1533 }
1534 } else if (!RHS->hasNUsesOrMore(3)) {
1535 // Reuse the LHS. This will eliminate the RHS.
1536 if (D == A || D == B) {
1537 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1538 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1539 MinMaxOp = LHS;
1540 ThirdOp = C;
1541 } else if (C == A || C == B) {
1542 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1543 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1544 MinMaxOp = LHS;
1545 ThirdOp = D;
1546 }
1547 }
1548 if (!MinMaxOp || !ThirdOp)
1549 return nullptr;
1550
1551 CmpInst::Predicate P = getMinMaxPred(SPF);
1552 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1553 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1554 }
1555
1556 /// Try to reduce a rotate pattern that includes a compare and select into a
1557 /// funnel shift intrinsic. Example:
1558 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
1559 /// --> call llvm.fshl.i32(a, a, b)
foldSelectRotate(SelectInst & Sel)1560 static Instruction *foldSelectRotate(SelectInst &Sel) {
1561 // The false value of the select must be a rotate of the true value.
1562 Value *Or0, *Or1;
1563 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
1564 return nullptr;
1565
1566 Value *TVal = Sel.getTrueValue();
1567 Value *SA0, *SA1;
1568 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
1569 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
1570 return nullptr;
1571
1572 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
1573 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
1574 if (ShiftOpcode0 == ShiftOpcode1)
1575 return nullptr;
1576
1577 // We have one of these patterns so far:
1578 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
1579 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
1580 // This must be a power-of-2 rotate for a bitmasking transform to be valid.
1581 unsigned Width = Sel.getType()->getScalarSizeInBits();
1582 if (!isPowerOf2_32(Width))
1583 return nullptr;
1584
1585 // Check the shift amounts to see if they are an opposite pair.
1586 Value *ShAmt;
1587 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
1588 ShAmt = SA0;
1589 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
1590 ShAmt = SA1;
1591 else
1592 return nullptr;
1593
1594 // Finally, see if the select is filtering out a shift-by-zero.
1595 Value *Cond = Sel.getCondition();
1596 ICmpInst::Predicate Pred;
1597 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
1598 Pred != ICmpInst::ICMP_EQ)
1599 return nullptr;
1600
1601 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
1602 // Convert to funnel shift intrinsic.
1603 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
1604 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
1605 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
1606 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
1607 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
1608 }
1609
visitSelectInst(SelectInst & SI)1610 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1611 Value *CondVal = SI.getCondition();
1612 Value *TrueVal = SI.getTrueValue();
1613 Value *FalseVal = SI.getFalseValue();
1614 Type *SelType = SI.getType();
1615
1616 // FIXME: Remove this workaround when freeze related patches are done.
1617 // For select with undef operand which feeds into an equality comparison,
1618 // don't simplify it so loop unswitch can know the equality comparison
1619 // may have an undef operand. This is a workaround for PR31652 caused by
1620 // descrepancy about branch on undef between LoopUnswitch and GVN.
1621 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1622 if (llvm::any_of(SI.users(), [&](User *U) {
1623 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1624 if (CI && CI->isEquality())
1625 return true;
1626 return false;
1627 })) {
1628 return nullptr;
1629 }
1630 }
1631
1632 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1633 SQ.getWithInstruction(&SI)))
1634 return replaceInstUsesWith(SI, V);
1635
1636 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1637 return I;
1638
1639 // Canonicalize a one-use integer compare with a non-canonical predicate by
1640 // inverting the predicate and swapping the select operands. This matches a
1641 // compare canonicalization for conditional branches.
1642 // TODO: Should we do the same for FP compares?
1643 CmpInst::Predicate Pred;
1644 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1645 !isCanonicalPredicate(Pred)) {
1646 // Swap true/false values and condition.
1647 CmpInst *Cond = cast<CmpInst>(CondVal);
1648 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1649 SI.setOperand(1, FalseVal);
1650 SI.setOperand(2, TrueVal);
1651 SI.swapProfMetadata();
1652 Worklist.Add(Cond);
1653 return &SI;
1654 }
1655
1656 if (SelType->isIntOrIntVectorTy(1) &&
1657 TrueVal->getType() == CondVal->getType()) {
1658 if (match(TrueVal, m_One())) {
1659 // Change: A = select B, true, C --> A = or B, C
1660 return BinaryOperator::CreateOr(CondVal, FalseVal);
1661 }
1662 if (match(TrueVal, m_Zero())) {
1663 // Change: A = select B, false, C --> A = and !B, C
1664 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1665 return BinaryOperator::CreateAnd(NotCond, FalseVal);
1666 }
1667 if (match(FalseVal, m_Zero())) {
1668 // Change: A = select B, C, false --> A = and B, C
1669 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1670 }
1671 if (match(FalseVal, m_One())) {
1672 // Change: A = select B, C, true --> A = or !B, C
1673 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1674 return BinaryOperator::CreateOr(NotCond, TrueVal);
1675 }
1676
1677 // select a, a, b -> a | b
1678 // select a, b, a -> a & b
1679 if (CondVal == TrueVal)
1680 return BinaryOperator::CreateOr(CondVal, FalseVal);
1681 if (CondVal == FalseVal)
1682 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1683
1684 // select a, ~a, b -> (~a) & b
1685 // select a, b, ~a -> (~a) | b
1686 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1687 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1688 if (match(FalseVal, m_Not(m_Specific(CondVal))))
1689 return BinaryOperator::CreateOr(TrueVal, FalseVal);
1690 }
1691
1692 // Selecting between two integer or vector splat integer constants?
1693 //
1694 // Note that we don't handle a scalar select of vectors:
1695 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1696 // because that may need 3 instructions to splat the condition value:
1697 // extend, insertelement, shufflevector.
1698 if (SelType->isIntOrIntVectorTy() &&
1699 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1700 // select C, 1, 0 -> zext C to int
1701 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1702 return new ZExtInst(CondVal, SelType);
1703
1704 // select C, -1, 0 -> sext C to int
1705 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1706 return new SExtInst(CondVal, SelType);
1707
1708 // select C, 0, 1 -> zext !C to int
1709 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1710 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1711 return new ZExtInst(NotCond, SelType);
1712 }
1713
1714 // select C, 0, -1 -> sext !C to int
1715 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1716 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1717 return new SExtInst(NotCond, SelType);
1718 }
1719 }
1720
1721 // See if we are selecting two values based on a comparison of the two values.
1722 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1723 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1724 // Canonicalize to use ordered comparisons by swapping the select
1725 // operands.
1726 //
1727 // e.g.
1728 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1729 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1730 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1731 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1732 Builder.setFastMathFlags(FCI->getFastMathFlags());
1733 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1734 FCI->getName() + ".inv");
1735
1736 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1737 SI.getName() + ".p");
1738 }
1739
1740 // NOTE: if we wanted to, this is where to detect MIN/MAX
1741 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1742 // Canonicalize to use ordered comparisons by swapping the select
1743 // operands.
1744 //
1745 // e.g.
1746 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1747 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1748 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1749 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1750 Builder.setFastMathFlags(FCI->getFastMathFlags());
1751 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1752 FCI->getName() + ".inv");
1753
1754 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1755 SI.getName() + ".p");
1756 }
1757
1758 // NOTE: if we wanted to, this is where to detect MIN/MAX
1759 }
1760
1761 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1762 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1763 // also require nnan because we do not want to unintentionally change the
1764 // sign of a NaN value.
1765 Value *X = FCI->getOperand(0);
1766 FCmpInst::Predicate Pred = FCI->getPredicate();
1767 if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1768 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1769 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
1770 if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1771 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1772 (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1773 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
1774 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1775 return replaceInstUsesWith(SI, Fabs);
1776 }
1777 // With nsz:
1778 // (X < +/-0.0) ? -X : X --> fabs(X)
1779 // (X <= +/-0.0) ? -X : X --> fabs(X)
1780 // (X > +/-0.0) ? X : -X --> fabs(X)
1781 // (X >= +/-0.0) ? X : -X --> fabs(X)
1782 if (FCI->hasNoSignedZeros() &&
1783 ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1784 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1785 (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1786 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1787 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1788 return replaceInstUsesWith(SI, Fabs);
1789 }
1790 }
1791 }
1792
1793 // See if we are selecting two values based on a comparison of the two values.
1794 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1795 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1796 return Result;
1797
1798 if (Instruction *Add = foldAddSubSelect(SI, Builder))
1799 return Add;
1800
1801 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1802 auto *TI = dyn_cast<Instruction>(TrueVal);
1803 auto *FI = dyn_cast<Instruction>(FalseVal);
1804 if (TI && FI && TI->getOpcode() == FI->getOpcode())
1805 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1806 return IV;
1807
1808 if (Instruction *I = foldSelectExtConst(SI))
1809 return I;
1810
1811 // See if we can fold the select into one of our operands.
1812 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1813 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1814 return FoldI;
1815
1816 Value *LHS, *RHS;
1817 Instruction::CastOps CastOp;
1818 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1819 auto SPF = SPR.Flavor;
1820 if (SPF) {
1821 Value *LHS2, *RHS2;
1822 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1823 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
1824 RHS2, SI, SPF, RHS))
1825 return R;
1826 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1827 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
1828 RHS2, SI, SPF, LHS))
1829 return R;
1830 // TODO.
1831 // ABS(-X) -> ABS(X)
1832 }
1833
1834 if (SelectPatternResult::isMinOrMax(SPF)) {
1835 // Canonicalize so that
1836 // - type casts are outside select patterns.
1837 // - float clamp is transformed to min/max pattern
1838
1839 bool IsCastNeeded = LHS->getType() != SelType;
1840 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1841 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1842 if (IsCastNeeded ||
1843 (LHS->getType()->isFPOrFPVectorTy() &&
1844 ((CmpLHS != LHS && CmpLHS != RHS) ||
1845 (CmpRHS != LHS && CmpRHS != RHS)))) {
1846 CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1847
1848 Value *Cmp;
1849 if (CmpInst::isIntPredicate(Pred)) {
1850 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1851 } else {
1852 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1853 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1854 Builder.setFastMathFlags(FMF);
1855 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1856 }
1857
1858 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1859 if (!IsCastNeeded)
1860 return replaceInstUsesWith(SI, NewSI);
1861
1862 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1863 return replaceInstUsesWith(SI, NewCast);
1864 }
1865
1866 // MAX(~a, ~b) -> ~MIN(a, b)
1867 // MAX(~a, C) -> ~MIN(a, ~C)
1868 // MIN(~a, ~b) -> ~MAX(a, b)
1869 // MIN(~a, C) -> ~MAX(a, ~C)
1870 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1871 Value *A;
1872 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
1873 !IsFreeToInvert(A, A->hasOneUse()) &&
1874 // Passing false to only consider m_Not and constants.
1875 IsFreeToInvert(Y, false)) {
1876 Value *B = Builder.CreateNot(Y);
1877 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
1878 A, B);
1879 // Copy the profile metadata.
1880 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
1881 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
1882 // Swap the metadata if the operands are swapped.
1883 if (X == SI.getFalseValue() && Y == SI.getTrueValue())
1884 cast<SelectInst>(NewMinMax)->swapProfMetadata();
1885 }
1886
1887 return BinaryOperator::CreateNot(NewMinMax);
1888 }
1889
1890 return nullptr;
1891 };
1892
1893 if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
1894 return I;
1895 if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
1896 return I;
1897
1898 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1899 return I;
1900 }
1901 }
1902
1903 // See if we can fold the select into a phi node if the condition is a select.
1904 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1905 // The true/false values have to be live in the PHI predecessor's blocks.
1906 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1907 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1908 if (Instruction *NV = foldOpIntoPhi(SI, PN))
1909 return NV;
1910
1911 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1912 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1913 // select(C, select(C, a, b), c) -> select(C, a, c)
1914 if (TrueSI->getCondition() == CondVal) {
1915 if (SI.getTrueValue() == TrueSI->getTrueValue())
1916 return nullptr;
1917 SI.setOperand(1, TrueSI->getTrueValue());
1918 return &SI;
1919 }
1920 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1921 // We choose this as normal form to enable folding on the And and shortening
1922 // paths for the values (this helps GetUnderlyingObjects() for example).
1923 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1924 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1925 SI.setOperand(0, And);
1926 SI.setOperand(1, TrueSI->getTrueValue());
1927 return &SI;
1928 }
1929 }
1930 }
1931 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1932 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1933 // select(C, a, select(C, b, c)) -> select(C, a, c)
1934 if (FalseSI->getCondition() == CondVal) {
1935 if (SI.getFalseValue() == FalseSI->getFalseValue())
1936 return nullptr;
1937 SI.setOperand(2, FalseSI->getFalseValue());
1938 return &SI;
1939 }
1940 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1941 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1942 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1943 SI.setOperand(0, Or);
1944 SI.setOperand(2, FalseSI->getFalseValue());
1945 return &SI;
1946 }
1947 }
1948 }
1949
1950 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1951 // The select might be preventing a division by 0.
1952 switch (BO->getOpcode()) {
1953 default:
1954 return true;
1955 case Instruction::SRem:
1956 case Instruction::URem:
1957 case Instruction::SDiv:
1958 case Instruction::UDiv:
1959 return false;
1960 }
1961 };
1962
1963 // Try to simplify a binop sandwiched between 2 selects with the same
1964 // condition.
1965 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1966 BinaryOperator *TrueBO;
1967 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1968 canMergeSelectThroughBinop(TrueBO)) {
1969 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1970 if (TrueBOSI->getCondition() == CondVal) {
1971 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1972 Worklist.Add(TrueBO);
1973 return &SI;
1974 }
1975 }
1976 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1977 if (TrueBOSI->getCondition() == CondVal) {
1978 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1979 Worklist.Add(TrueBO);
1980 return &SI;
1981 }
1982 }
1983 }
1984
1985 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1986 BinaryOperator *FalseBO;
1987 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1988 canMergeSelectThroughBinop(FalseBO)) {
1989 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1990 if (FalseBOSI->getCondition() == CondVal) {
1991 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1992 Worklist.Add(FalseBO);
1993 return &SI;
1994 }
1995 }
1996 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1997 if (FalseBOSI->getCondition() == CondVal) {
1998 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1999 Worklist.Add(FalseBO);
2000 return &SI;
2001 }
2002 }
2003 }
2004
2005 Value *NotCond;
2006 if (match(CondVal, m_Not(m_Value(NotCond)))) {
2007 SI.setOperand(0, NotCond);
2008 SI.setOperand(1, FalseVal);
2009 SI.setOperand(2, TrueVal);
2010 SI.swapProfMetadata();
2011 return &SI;
2012 }
2013
2014 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2015 unsigned VWidth = VecTy->getNumElements();
2016 APInt UndefElts(VWidth, 0);
2017 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2018 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2019 if (V != &SI)
2020 return replaceInstUsesWith(SI, V);
2021 return &SI;
2022 }
2023 }
2024
2025 // If we can compute the condition, there's no need for a select.
2026 // Like the above fold, we are attempting to reduce compile-time cost by
2027 // putting this fold here with limitations rather than in InstSimplify.
2028 // The motivation for this call into value tracking is to take advantage of
2029 // the assumption cache, so make sure that is populated.
2030 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2031 KnownBits Known(1);
2032 computeKnownBits(CondVal, Known, 0, &SI);
2033 if (Known.One.isOneValue())
2034 return replaceInstUsesWith(SI, TrueVal);
2035 if (Known.Zero.isOneValue())
2036 return replaceInstUsesWith(SI, FalseVal);
2037 }
2038
2039 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2040 return BitCastSel;
2041
2042 // Simplify selects that test the returned flag of cmpxchg instructions.
2043 if (Instruction *Select = foldSelectCmpXchg(SI))
2044 return Select;
2045
2046 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
2047 return Select;
2048
2049 if (Instruction *Rot = foldSelectRotate(SI))
2050 return Rot;
2051
2052 return nullptr;
2053 }
2054