1 //===- InstCombineSelect.cpp ----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the visitSelect function.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CmpInstAnalysis.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
45 using namespace PatternMatch;
47 #define DEBUG_TYPE "instcombine"
49 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
50 SelectPatternFlavor SPF, Value *A, Value *B) {
51 CmpInst::Predicate Pred = getMinMaxPred(SPF);
52 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
53 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
56 /// Replace a select operand based on an equality comparison with the identity
57 /// constant of a binop.
58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
59 const TargetLibraryInfo &TLI,
61 // The select condition must be an equality compare with a constant operand.
64 CmpInst::Predicate Pred;
65 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
69 if (ICmpInst::isEquality(Pred))
70 IsEq = Pred == ICmpInst::ICMP_EQ;
71 else if (Pred == FCmpInst::FCMP_OEQ)
73 else if (Pred == FCmpInst::FCMP_UNE)
78 // A select operand must be a binop.
80 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
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);
88 if (!IdC || !CmpInst::isFPPredicate(Pred))
90 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
94 // Last, match the compare variable operand with a binop operand.
96 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
98 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
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))
108 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
110 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
111 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
115 /// select (icmp eq (and X, C1)), TC, FC
116 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117 /// To something like:
118 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
120 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121 /// With some variations depending if FC is larger than TC, or the shift
122 /// isn't needed, or the bit widths don't match.
123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
124 InstCombiner::BuilderTy &Builder) {
125 const APInt *SelTC, *SelFC;
126 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127 !match(Sel.getFalseValue(), m_APInt(SelFC)))
130 // If this is a vector select, we need a vector compare.
131 Type *SelType = Sel.getType();
132 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
137 bool CreateAnd = false;
138 ICmpInst::Predicate Pred = Cmp->getPredicate();
139 if (ICmpInst::isEquality(Pred)) {
140 if (!match(Cmp->getOperand(1), m_Zero()))
143 V = Cmp->getOperand(0);
145 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
149 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
151 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
152 if (!AndMask.isPowerOf2())
160 // In general, when both constants are non-zero, we would need an offset to
161 // replace the select. This would require more instructions than we started
162 // with. But there's one special-case that we handle here because it can
163 // simplify/reduce the instructions.
166 if (!TC.isNullValue() && !FC.isNullValue()) {
167 // If the select constants differ by exactly one bit and that's the same
168 // bit that is masked and checked by the select condition, the select can
169 // be replaced by bitwise logic to set/clear one bit of the constant result.
170 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
173 // If we have to create an 'and', then we must kill the cmp to not
174 // increase the instruction count.
175 if (!Cmp->hasOneUse())
177 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
179 bool ExtraBitInTC = TC.ugt(FC);
180 if (Pred == ICmpInst::ICMP_EQ) {
181 // If the masked bit in V is clear, clear or set the bit in the result:
182 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184 Constant *C = ConstantInt::get(SelType, TC);
185 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
187 if (Pred == ICmpInst::ICMP_NE) {
188 // If the masked bit in V is set, set or clear the bit in the result:
189 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191 Constant *C = ConstantInt::get(SelType, FC);
192 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
194 llvm_unreachable("Only expecting equality predicates");
197 // Make sure one of the select arms is a power-of-2.
198 if (!TC.isPowerOf2() && !FC.isPowerOf2())
201 // Determine which shift is needed to transform result of the 'and' into the
203 const APInt &ValC = !TC.isNullValue() ? TC : FC;
204 unsigned ValZeros = ValC.logBase2();
205 unsigned AndZeros = AndMask.logBase2();
207 // Insert the 'and' instruction on the input to the truncate.
209 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
211 // If types don't match, we can still convert the select by introducing a zext
212 // or a trunc of the 'and'.
213 if (ValZeros > AndZeros) {
214 V = Builder.CreateZExtOrTrunc(V, SelType);
215 V = Builder.CreateShl(V, ValZeros - AndZeros);
216 } else if (ValZeros < AndZeros) {
217 V = Builder.CreateLShr(V, AndZeros - ValZeros);
218 V = Builder.CreateZExtOrTrunc(V, SelType);
220 V = Builder.CreateZExtOrTrunc(V, SelType);
223 // Okay, now we know that everything is set up, we just don't know whether we
224 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225 bool ShouldNotVal = !TC.isNullValue();
226 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
228 V = Builder.CreateXor(V, ValC);
233 /// We want to turn code that looks like this:
235 /// %D = select %cond, %C, %A
237 /// %C = select %cond, %B, 0
240 /// Assuming that the specified instruction is an operand to the select, return
241 /// a bitmask indicating which operands of this instruction are foldable if they
242 /// equal the other incoming value of the select.
243 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
244 switch (I->getOpcode()) {
245 case Instruction::Add:
246 case Instruction::Mul:
247 case Instruction::And:
248 case Instruction::Or:
249 case Instruction::Xor:
250 return 3; // Can fold through either operand.
251 case Instruction::Sub: // Can only fold on the amount subtracted.
252 case Instruction::Shl: // Can only fold on the shift amount.
253 case Instruction::LShr:
254 case Instruction::AShr:
257 return 0; // Cannot fold
261 /// For the same transformation as the previous function, return the identity
262 /// constant that goes into the select.
263 static APInt getSelectFoldableConstant(BinaryOperator *I) {
264 switch (I->getOpcode()) {
265 default: llvm_unreachable("This cannot happen!");
266 case Instruction::Add:
267 case Instruction::Sub:
268 case Instruction::Or:
269 case Instruction::Xor:
270 case Instruction::Shl:
271 case Instruction::LShr:
272 case Instruction::AShr:
273 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
274 case Instruction::And:
275 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
276 case Instruction::Mul:
277 return APInt(I->getType()->getScalarSizeInBits(), 1);
281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
284 // Don't break up min/max patterns. The hasOneUse checks below prevent that
285 // for most cases, but vector min/max with bitcasts can be transformed. If the
286 // one-use restrictions are eased for other patterns, we still don't want to
287 // obfuscate min/max.
288 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289 match(&SI, m_SMax(m_Value(), m_Value())) ||
290 match(&SI, m_UMin(m_Value(), m_Value())) ||
291 match(&SI, m_UMax(m_Value(), m_Value()))))
294 // If this is a cast from the same type, merge.
295 Value *Cond = SI.getCondition();
296 Type *CondTy = Cond->getType();
297 if (TI->getNumOperands() == 1 && TI->isCast()) {
298 Type *FIOpndTy = FI->getOperand(0)->getType();
299 if (TI->getOperand(0)->getType() != FIOpndTy)
302 // The select condition may be a vector. We may only change the operand
303 // type if the vector width remains the same (and matches the condition).
304 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
305 if (!FIOpndTy->isVectorTy())
307 if (CondVTy->getNumElements() !=
308 cast<VectorType>(FIOpndTy)->getNumElements())
311 // TODO: If the backend knew how to deal with casts better, we could
312 // remove this limitation. For now, there's too much potential to create
313 // worse codegen by promoting the select ahead of size-altering casts
316 // Note that ValueTracking's matchSelectPattern() looks through casts
317 // without checking 'hasOneUse' when it matches min/max patterns, so this
318 // transform may end up happening anyway.
319 if (TI->getOpcode() != Instruction::BitCast &&
320 (!TI->hasOneUse() || !FI->hasOneUse()))
322 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
323 // TODO: The one-use restrictions for a scalar select could be eased if
324 // the fold of a select in visitLoadInst() was enhanced to match a pattern
325 // that includes a cast.
329 // Fold this by inserting a select from the input values.
331 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
332 SI.getName() + ".v", &SI);
333 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
337 // Cond ? -X : -Y --> -(Cond ? X : Y)
339 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
340 (TI->hasOneUse() || FI->hasOneUse())) {
341 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
342 return UnaryOperator::CreateFNegFMF(NewSel, TI);
345 // Only handle binary operators (including two-operand getelementptr) with
346 // one-use here. As with the cast case above, it may be possible to relax the
347 // one-use constraint, but that needs be examined carefully since it may not
348 // reduce the total number of instructions.
349 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
350 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
351 !TI->hasOneUse() || !FI->hasOneUse())
354 // Figure out if the operations have any operands in common.
355 Value *MatchOp, *OtherOpT, *OtherOpF;
357 if (TI->getOperand(0) == FI->getOperand(0)) {
358 MatchOp = TI->getOperand(0);
359 OtherOpT = TI->getOperand(1);
360 OtherOpF = FI->getOperand(1);
361 MatchIsOpZero = true;
362 } else if (TI->getOperand(1) == FI->getOperand(1)) {
363 MatchOp = TI->getOperand(1);
364 OtherOpT = TI->getOperand(0);
365 OtherOpF = FI->getOperand(0);
366 MatchIsOpZero = false;
367 } else if (!TI->isCommutative()) {
369 } else if (TI->getOperand(0) == FI->getOperand(1)) {
370 MatchOp = TI->getOperand(0);
371 OtherOpT = TI->getOperand(1);
372 OtherOpF = FI->getOperand(0);
373 MatchIsOpZero = true;
374 } else if (TI->getOperand(1) == FI->getOperand(0)) {
375 MatchOp = TI->getOperand(1);
376 OtherOpT = TI->getOperand(0);
377 OtherOpF = FI->getOperand(1);
378 MatchIsOpZero = true;
383 // If the select condition is a vector, the operands of the original select's
384 // operands also must be vectors. This may not be the case for getelementptr
386 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
387 !OtherOpF->getType()->isVectorTy()))
390 // If we reach here, they do have operations in common.
391 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
392 SI.getName() + ".v", &SI);
393 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
394 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
395 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
396 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
397 NewBO->copyIRFlags(TI);
398 NewBO->andIRFlags(FI);
401 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
402 auto *FGEP = cast<GetElementPtrInst>(FI);
403 Type *ElementType = TGEP->getResultElementType();
404 return TGEP->isInBounds() && FGEP->isInBounds()
405 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
406 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
408 llvm_unreachable("Expected BinaryOperator or GEP");
412 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
413 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
415 return C1I.isOneValue() || C1I.isAllOnesValue() ||
416 C2I.isOneValue() || C2I.isAllOnesValue();
419 /// Try to fold the select into one of the operands to allow further
421 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
423 // See the comment above GetSelectFoldableOperands for a description of the
424 // transformation we are doing here.
425 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
426 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
427 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
428 unsigned OpToFold = 0;
429 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
431 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
436 APInt CI = getSelectFoldableConstant(TVI);
437 Value *OOp = TVI->getOperand(2-OpToFold);
438 // Avoid creating select between 2 constants unless it's selecting
439 // between 0, 1 and -1.
441 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
442 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
443 Value *C = ConstantInt::get(OOp->getType(), CI);
444 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
445 NewSel->takeName(TVI);
446 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
448 BO->copyIRFlags(TVI);
456 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
457 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
458 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
459 unsigned OpToFold = 0;
460 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
462 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
467 APInt CI = getSelectFoldableConstant(FVI);
468 Value *OOp = FVI->getOperand(2-OpToFold);
469 // Avoid creating select between 2 constants unless it's selecting
470 // between 0, 1 and -1.
472 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
473 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
474 Value *C = ConstantInt::get(OOp->getType(), CI);
475 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
476 NewSel->takeName(FVI);
477 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
479 BO->copyIRFlags(FVI);
491 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
493 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
495 /// Z may be 0 if lshr is missing.
496 /// Worst-case scenario is that we will replace 5 instructions with 5 different
497 /// instructions, but we got rid of select.
498 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
499 Value *TVal, Value *FVal,
500 InstCombiner::BuilderTy &Builder) {
501 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
502 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
503 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
506 // The TrueVal has general form of: and %B, 1
508 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
511 // Where %B may be optionally shifted: lshr %X, %Z.
513 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
518 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
521 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
522 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
523 Constant *One = ConstantInt::get(SelType, 1);
524 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
525 Value *FullMask = Builder.CreateOr(Y, MaskB);
526 Value *MaskedX = Builder.CreateAnd(X, FullMask);
527 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
528 return new ZExtInst(ICmpNeZero, SelType);
532 /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
533 /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
536 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
538 InstCombiner::BuilderTy &Builder) {
539 ICmpInst::Predicate Pred = IC->getPredicate();
540 Value *CmpLHS = IC->getOperand(0);
541 Value *CmpRHS = IC->getOperand(1);
542 if (!CmpRHS->getType()->isIntOrIntVectorTy())
546 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
547 if ((Pred != ICmpInst::ICMP_SGT ||
549 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
550 (Pred != ICmpInst::ICMP_SLT ||
552 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
555 // Canonicalize so that ashr is in FalseVal.
556 if (Pred == ICmpInst::ICMP_SLT)
557 std::swap(TrueVal, FalseVal);
559 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
560 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
561 match(CmpLHS, m_Specific(X))) {
562 const auto *Ashr = cast<Instruction>(FalseVal);
563 // if lshr is not exact and ashr is, this new ashr must not be exact.
564 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
565 return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
572 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
574 /// (or (shl (and X, C1), C3), Y)
576 /// C1 and C2 are both powers of 2
578 /// C3 = Log(C2) - Log(C1)
580 /// This transform handles cases where:
581 /// 1. The icmp predicate is inverted
582 /// 2. The select operands are reversed
583 /// 3. The magnitude of C2 and C1 are flipped
584 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
586 InstCombiner::BuilderTy &Builder) {
587 // Only handle integer compares. Also, if this is a vector select, we need a
589 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
590 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
593 Value *CmpLHS = IC->getOperand(0);
594 Value *CmpRHS = IC->getOperand(1);
599 bool NeedAnd = false;
600 if (IC->isEquality()) {
601 if (!match(CmpRHS, m_Zero()))
605 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
609 C1Log = C1->logBase2();
610 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
611 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
612 IC->getPredicate() == ICmpInst::ICMP_SGT) {
613 // We also need to recognize (icmp slt (trunc (X)), 0) and
614 // (icmp sgt (trunc (X)), -1).
615 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
616 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
617 (!IsEqualZero && !match(CmpRHS, m_Zero())))
620 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
623 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
630 bool OrOnTrueVal = false;
631 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
633 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
635 if (!OrOnFalseVal && !OrOnTrueVal)
638 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
640 unsigned C2Log = C2->logBase2();
642 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
643 bool NeedShift = C1Log != C2Log;
644 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
645 V->getType()->getScalarSizeInBits();
647 // Make sure we don't create more instructions than we save.
648 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
649 if ((NeedShift + NeedXor + NeedZExtTrunc) >
650 (IC->hasOneUse() + Or->hasOneUse()))
654 // Insert the AND instruction on the input to the truncate.
655 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
656 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
660 V = Builder.CreateZExtOrTrunc(V, Y->getType());
661 V = Builder.CreateShl(V, C2Log - C1Log);
662 } else if (C1Log > C2Log) {
663 V = Builder.CreateLShr(V, C1Log - C2Log);
664 V = Builder.CreateZExtOrTrunc(V, Y->getType());
666 V = Builder.CreateZExtOrTrunc(V, Y->getType());
669 V = Builder.CreateXor(V, *C2);
671 return Builder.CreateOr(V, Y);
674 /// Canonicalize a set or clear of a masked set of constant bits to
675 /// select-of-constants form.
676 static Instruction *foldSetClearBits(SelectInst &Sel,
677 InstCombiner::BuilderTy &Builder) {
678 Value *Cond = Sel.getCondition();
679 Value *T = Sel.getTrueValue();
680 Value *F = Sel.getFalseValue();
681 Type *Ty = Sel.getType();
683 const APInt *NotC, *C;
685 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
686 if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
687 match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
688 Constant *Zero = ConstantInt::getNullValue(Ty);
689 Constant *OrC = ConstantInt::get(Ty, *C);
690 Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
691 return BinaryOperator::CreateOr(T, NewSel);
694 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
695 if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
696 match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
697 Constant *Zero = ConstantInt::getNullValue(Ty);
698 Constant *OrC = ConstantInt::get(Ty, *C);
699 Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
700 return BinaryOperator::CreateOr(F, NewSel);
706 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
707 /// There are 8 commuted/swapped variants of this pattern.
708 /// TODO: Also support a - UMIN(a,b) patterns.
709 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
710 const Value *TrueVal,
711 const Value *FalseVal,
712 InstCombiner::BuilderTy &Builder) {
713 ICmpInst::Predicate Pred = ICI->getPredicate();
714 if (!ICmpInst::isUnsigned(Pred))
717 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
718 if (match(TrueVal, m_Zero())) {
719 Pred = ICmpInst::getInversePredicate(Pred);
720 std::swap(TrueVal, FalseVal);
722 if (!match(FalseVal, m_Zero()))
725 Value *A = ICI->getOperand(0);
726 Value *B = ICI->getOperand(1);
727 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
728 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
730 Pred = ICmpInst::getSwappedPredicate(Pred);
733 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
734 "Unexpected isUnsigned predicate!");
736 // Ensure the sub is of the form:
737 // (a > b) ? a - b : 0 -> usub.sat(a, b)
738 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
739 // Checking for both a-b and a+(-b) as a constant.
740 bool IsNegative = false;
742 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
743 (match(A, m_APInt(C)) &&
744 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
746 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
747 !(match(B, m_APInt(C)) &&
748 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
751 // If we are adding a negate and the sub and icmp are used anywhere else, we
752 // would end up with more instructions.
753 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
756 // (a > b) ? a - b : 0 -> usub.sat(a, b)
757 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
758 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
760 Result = Builder.CreateNeg(Result);
764 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
765 InstCombiner::BuilderTy &Builder) {
766 if (!Cmp->hasOneUse())
769 // Match unsigned saturated add with constant.
770 Value *Cmp0 = Cmp->getOperand(0);
771 Value *Cmp1 = Cmp->getOperand(1);
772 ICmpInst::Predicate Pred = Cmp->getPredicate();
774 const APInt *C, *CmpC;
775 if (Pred == ICmpInst::ICMP_ULT &&
776 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
777 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
778 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
779 return Builder.CreateBinaryIntrinsic(
780 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
783 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
784 // There are 8 commuted variants.
785 // Canonicalize -1 (saturated result) to true value of the select.
786 if (match(FVal, m_AllOnes())) {
787 std::swap(TVal, FVal);
788 Pred = CmpInst::getInversePredicate(Pred);
790 if (!match(TVal, m_AllOnes()))
793 // Canonicalize predicate to less-than or less-or-equal-than.
794 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
795 std::swap(Cmp0, Cmp1);
796 Pred = CmpInst::getSwappedPredicate(Pred);
798 if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
801 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
802 // Strictness of the comparison is irrelevant.
804 if (match(Cmp0, m_Not(m_Value(X))) &&
805 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
806 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
807 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
808 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
810 // The 'not' op may be included in the sum but not the compare.
811 // Strictness of the comparison is irrelevant.
814 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
815 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
816 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
817 BinaryOperator *BO = cast<BinaryOperator>(FVal);
818 return Builder.CreateBinaryIntrinsic(
819 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
821 // The overflow may be detected via the add wrapping round.
822 // This is only valid for strict comparison!
823 if (Pred == ICmpInst::ICMP_ULT &&
824 match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
825 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
826 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
827 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
828 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
834 /// Fold the following code sequence:
836 /// int a = ctlz(x & -x);
842 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
844 InstCombiner::BuilderTy &Builder) {
845 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
846 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
849 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
850 std::swap(TrueVal, FalseVal);
853 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
856 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
859 Value *X = ICI->getOperand(0);
860 auto *II = cast<IntrinsicInst>(TrueVal);
861 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
864 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
866 return CallInst::Create(F, {X, II->getArgOperand(1)});
869 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
870 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
872 /// For example, we can fold the following code sequence:
874 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
875 /// %1 = icmp ne i32 %x, 0
876 /// %2 = select i1 %1, i32 %0, i32 32
880 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
881 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
882 InstCombiner::BuilderTy &Builder) {
883 ICmpInst::Predicate Pred = ICI->getPredicate();
884 Value *CmpLHS = ICI->getOperand(0);
885 Value *CmpRHS = ICI->getOperand(1);
887 // Check if the condition value compares a value for equality against zero.
888 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
891 Value *SelectArg = FalseVal;
892 Value *ValueOnZero = TrueVal;
893 if (Pred == ICmpInst::ICMP_NE)
894 std::swap(SelectArg, ValueOnZero);
896 // Skip zero extend/truncate.
897 Value *Count = nullptr;
898 if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
899 !match(SelectArg, m_Trunc(m_Value(Count))))
902 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
903 // input to the cttz/ctlz is used as LHS for the compare instruction.
904 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
905 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
908 IntrinsicInst *II = cast<IntrinsicInst>(Count);
910 // Check if the value propagated on zero is a constant number equal to the
911 // sizeof in bits of 'Count'.
912 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
913 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
914 // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
915 // true to false on this flag, so we can replace it for all users.
916 II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
920 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
921 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
922 // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
923 if (II->hasOneUse() && SelectArg->hasOneUse() &&
924 !match(II->getArgOperand(1), m_One()))
925 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
930 /// Return true if we find and adjust an icmp+select pattern where the compare
931 /// is with a constant that can be incremented or decremented to match the
932 /// minimum or maximum idiom.
933 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
934 ICmpInst::Predicate Pred = Cmp.getPredicate();
935 Value *CmpLHS = Cmp.getOperand(0);
936 Value *CmpRHS = Cmp.getOperand(1);
937 Value *TrueVal = Sel.getTrueValue();
938 Value *FalseVal = Sel.getFalseValue();
940 // We may move or edit the compare, so make sure the select is the only user.
942 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
945 // These transforms only work for selects of integers or vector selects of
947 Type *SelTy = Sel.getType();
948 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
949 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
952 Constant *AdjustedRHS;
953 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
954 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
955 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
956 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
960 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
961 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
962 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
963 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
964 ; // Nothing to do here. Values match without any sign/zero extension.
966 // Types do not match. Instead of calculating this with mixed types, promote
967 // all to the larger type. This enables scalar evolution to analyze this
969 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
970 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
972 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
973 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
974 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
975 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
976 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
978 AdjustedRHS = SextRHS;
979 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
980 SextRHS == TrueVal) {
982 AdjustedRHS = SextRHS;
983 } else if (Cmp.isUnsigned()) {
984 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
985 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
986 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
987 // zext + signed compare cannot be changed:
988 // 0xff <s 0x00, but 0x00ff >s 0x0000
989 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
991 AdjustedRHS = ZextRHS;
992 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
993 ZextRHS == TrueVal) {
995 AdjustedRHS = ZextRHS;
1006 Pred = ICmpInst::getSwappedPredicate(Pred);
1007 CmpRHS = AdjustedRHS;
1008 std::swap(FalseVal, TrueVal);
1009 Cmp.setPredicate(Pred);
1010 Cmp.setOperand(0, CmpLHS);
1011 Cmp.setOperand(1, CmpRHS);
1012 Sel.setOperand(1, TrueVal);
1013 Sel.setOperand(2, FalseVal);
1014 Sel.swapProfMetadata();
1016 // Move the compare instruction right before the select instruction. Otherwise
1017 // the sext/zext value may be defined after the compare instruction uses it.
1018 Cmp.moveBefore(&Sel);
1023 /// If this is an integer min/max (icmp + select) with a constant operand,
1024 /// create the canonical icmp for the min/max operation and canonicalize the
1025 /// constant to the 'false' operand of the select:
1026 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1027 /// Note: if C1 != C2, this will change the icmp constant to the existing
1028 /// constant operand of the select.
1029 static Instruction *
1030 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
1032 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1035 // Canonicalize the compare predicate based on whether we have min or max.
1037 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1038 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1041 // Is this already canonical?
1042 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1043 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1044 Cmp.getPredicate() == CanonicalPred)
1047 // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1048 // as this may cause an infinite combine loop. Let the sub be folded first.
1049 if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1050 match(RHS, m_Sub(m_Value(), m_Zero())))
1053 // Create the canonical compare and plug it into the select.
1054 IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1056 // If the select operands did not change, we're done.
1057 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1060 // If we are swapping the select operands, swap the metadata too.
1061 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1062 "Unexpected results from matchSelectPattern");
1064 Sel.swapProfMetadata();
1068 /// There are many select variants for each of ABS/NABS.
1069 /// In matchSelectPattern(), there are different compare constants, compare
1070 /// predicates/operands and select operands.
1071 /// In isKnownNegation(), there are different formats of negated operands.
1072 /// Canonicalize all these variants to 1 pattern.
1073 /// This makes CSE more likely.
1074 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1076 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1079 // Choose a sign-bit check for the compare (likely simpler for codegen).
1080 // ABS: (X <s 0) ? -X : X
1081 // NABS: (X <s 0) ? X : -X
1083 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1084 if (SPF != SelectPatternFlavor::SPF_ABS &&
1085 SPF != SelectPatternFlavor::SPF_NABS)
1088 Value *TVal = Sel.getTrueValue();
1089 Value *FVal = Sel.getFalseValue();
1090 assert(isKnownNegation(TVal, FVal) &&
1091 "Unexpected result from matchSelectPattern");
1093 // The compare may use the negated abs()/nabs() operand, or it may use
1094 // negation in non-canonical form such as: sub A, B.
1095 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1096 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1098 bool CmpCanonicalized = !CmpUsesNegatedOp &&
1099 match(Cmp.getOperand(1), m_ZeroInt()) &&
1100 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1101 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1103 // Is this already canonical?
1104 if (CmpCanonicalized && RHSCanonicalized)
1107 // If RHS is not canonical but is used by other instructions, don't
1108 // canonicalize it and potentially increase the instruction count.
1109 if (!RHSCanonicalized)
1110 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1113 // Create the canonical compare: icmp slt LHS 0.
1114 if (!CmpCanonicalized) {
1115 Cmp.setPredicate(ICmpInst::ICMP_SLT);
1116 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1117 if (CmpUsesNegatedOp)
1118 Cmp.setOperand(0, LHS);
1121 // Create the canonical RHS: RHS = sub (0, LHS).
1122 if (!RHSCanonicalized) {
1123 assert(RHS->hasOneUse() && "RHS use number is not right");
1124 RHS = IC.Builder.CreateNeg(LHS);
1126 // Replace false value.
1127 IC.replaceOperand(Sel, 2, RHS);
1130 // Replace true value.
1131 IC.replaceOperand(Sel, 1, RHS);
1136 // If the select operands do not change, we're done.
1137 if (SPF == SelectPatternFlavor::SPF_NABS) {
1140 assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1144 assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1147 // We are swapping the select operands, so swap the metadata too.
1149 Sel.swapProfMetadata();
1153 /// If we have a select with an equality comparison, then we know the value in
1154 /// one of the arms of the select. See if substituting this value into an arm
1155 /// and simplifying the result yields the same value as the other arm.
1157 /// To make this transform safe, we must drop poison-generating flags
1158 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1159 /// that poison from propagating. If the existing binop already had no
1160 /// poison-generating flags, then this transform can be done by instsimplify.
1163 /// %cmp = icmp eq i32 %x, 2147483647
1164 /// %add = add nsw i32 %x, 1
1165 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1167 /// We can't replace %sel with %add unless we strip away the flags.
1168 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1169 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
1170 const SimplifyQuery &Q) {
1171 if (!Cmp.isEquality())
1174 // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1175 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1176 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1177 std::swap(TrueVal, FalseVal);
1179 auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1183 // InstSimplify already performed this fold if it was possible subject to
1184 // current poison-generating flags. Try the transform again with
1185 // poison-generating flags temporarily dropped.
1186 bool WasNUW = false, WasNSW = false, WasExact = false;
1187 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
1188 WasNUW = OBO->hasNoUnsignedWrap();
1189 WasNSW = OBO->hasNoSignedWrap();
1190 FalseInst->setHasNoUnsignedWrap(false);
1191 FalseInst->setHasNoSignedWrap(false);
1193 if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
1194 WasExact = PEO->isExact();
1195 FalseInst->setIsExact(false);
1198 // Try each equivalence substitution possibility.
1199 // We have an 'EQ' comparison, so the select's false value will propagate.
1201 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1202 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1203 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
1204 /* AllowRefinement */ false) == TrueVal ||
1205 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
1206 /* AllowRefinement */ false) == TrueVal) {
1210 // Restore poison-generating flags if the transform did not apply.
1212 FalseInst->setHasNoUnsignedWrap();
1214 FalseInst->setHasNoSignedWrap();
1216 FalseInst->setIsExact();
1221 // See if this is a pattern like:
1222 // %old_cmp1 = icmp slt i32 %x, C2
1223 // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1224 // %old_x_offseted = add i32 %x, C1
1225 // %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1226 // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1227 // This can be rewritten as more canonical pattern:
1228 // %new_cmp1 = icmp slt i32 %x, -C1
1229 // %new_cmp2 = icmp sge i32 %x, C0-C1
1230 // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1231 // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1232 // Iff -C1 s<= C2 s<= C0-C1
1233 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1234 // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1235 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1236 InstCombiner::BuilderTy &Builder) {
1237 Value *X = Sel0.getTrueValue();
1238 Value *Sel1 = Sel0.getFalseValue();
1240 // First match the condition of the outermost select.
1241 // Said condition must be one-use.
1242 if (!Cmp0.hasOneUse())
1244 Value *Cmp00 = Cmp0.getOperand(0);
1246 if (!match(Cmp0.getOperand(1),
1247 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1249 // Canonicalize Cmp0 into the form we expect.
1250 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1251 switch (Cmp0.getPredicate()) {
1252 case ICmpInst::Predicate::ICMP_ULT:
1254 case ICmpInst::Predicate::ICMP_ULE:
1255 // We'd have to increment C0 by one, and for that it must not have all-ones
1256 // element, but then it would have been canonicalized to 'ult' before
1257 // we get here. So we can't do anything useful with 'ule'.
1259 case ICmpInst::Predicate::ICMP_UGT:
1260 // We want to canonicalize it to 'ult', so we'll need to increment C0,
1261 // which again means it must not have any all-ones elements.
1263 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1264 APInt::getAllOnesValue(
1265 C0->getType()->getScalarSizeInBits()))))
1266 return nullptr; // Can't do, have all-ones element[s].
1270 case ICmpInst::Predicate::ICMP_UGE:
1271 // The only way we'd get this predicate if this `icmp` has extra uses,
1272 // but then we won't be able to do this fold.
1275 return nullptr; // Unknown predicate.
1278 // Now that we've canonicalized the ICmp, we know the X we expect;
1279 // the select in other hand should be one-use.
1280 if (!Sel1->hasOneUse())
1283 // We now can finish matching the condition of the outermost select:
1284 // it should either be the X itself, or an addition of some constant to X.
1287 C1 = ConstantInt::getNullValue(Sel0.getType());
1288 else if (!match(Cmp00,
1289 m_Add(m_Specific(X),
1290 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1294 ICmpInst::Predicate Pred1;
1296 Value *ReplacementLow, *ReplacementHigh;
1297 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1298 m_Value(ReplacementHigh))) ||
1300 m_ICmp(Pred1, m_Specific(X),
1301 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1304 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1305 return nullptr; // Not enough one-use instructions for the fold.
1306 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1307 // two comparisons we'll need to build.
1309 // Canonicalize Cmp1 into the form we expect.
1310 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1312 case ICmpInst::Predicate::ICMP_SLT:
1314 case ICmpInst::Predicate::ICMP_SLE:
1315 // We'd have to increment C2 by one, and for that it must not have signed
1316 // max element, but then it would have been canonicalized to 'slt' before
1317 // we get here. So we can't do anything useful with 'sle'.
1319 case ICmpInst::Predicate::ICMP_SGT:
1320 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1321 // which again means it must not have any signed max elements.
1323 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1324 APInt::getSignedMaxValue(
1325 C2->getType()->getScalarSizeInBits()))))
1326 return nullptr; // Can't do, have signed max element[s].
1329 case ICmpInst::Predicate::ICMP_SGE:
1330 // Also non-canonical, but here we don't need to change C2,
1331 // so we don't have any restrictions on C2, so we can just handle it.
1332 std::swap(ReplacementLow, ReplacementHigh);
1335 return nullptr; // Unknown predicate.
1338 // The thresholds of this clamp-like pattern.
1339 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1340 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1342 // The fold has a precondition 1: C2 s>= ThresholdLow
1343 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1345 if (!match(Precond1, m_One()))
1347 // The fold has a precondition 2: C2 s<= ThresholdHigh
1348 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1350 if (!match(Precond2, m_One()))
1353 // All good, finally emit the new pattern.
1354 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1355 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1356 Value *MaybeReplacedLow =
1357 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1358 Instruction *MaybeReplacedHigh =
1359 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1361 return MaybeReplacedHigh;
1365 // %cmp = icmp [canonical predicate] i32 %x, C0
1366 // %r = select i1 %cmp, i32 %y, i32 C1
1367 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1368 // will have if we flip the strictness of the predicate (i.e. without changing
1369 // the result) is identical to the C1 in select. If it matches we can change
1370 // original comparison to one with swapped predicate, reuse the constant,
1371 // and swap the hands of select.
1372 static Instruction *
1373 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1375 ICmpInst::Predicate Pred;
1378 if (!match(&Cmp, m_OneUse(m_ICmp(
1380 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1383 // If comparison predicate is non-relational, we won't be able to do anything.
1384 if (ICmpInst::isEquality(Pred))
1387 // If comparison predicate is non-canonical, then we certainly won't be able
1388 // to make it canonical; canonicalizeCmpWithConstant() already tried.
1389 if (!isCanonicalPredicate(Pred))
1392 // If the [input] type of comparison and select type are different, lets abort
1393 // for now. We could try to compare constants with trunc/[zs]ext though.
1394 if (C0->getType() != Sel.getType())
1397 // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1399 Value *SelVal0, *SelVal1; // We do not care which one is from where.
1400 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1401 // At least one of these values we are selecting between must be a constant
1402 // else we'll never succeed.
1403 if (!match(SelVal0, m_AnyIntegralConstant()) &&
1404 !match(SelVal1, m_AnyIntegralConstant()))
1407 // Does this constant C match any of the `select` values?
1408 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1409 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1412 // If C0 *already* matches true/false value of select, we are done.
1413 if (MatchesSelectValue(C0))
1416 // Check the constant we'd have with flipped-strictness predicate.
1417 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
1418 if (!FlippedStrictness)
1421 // If said constant doesn't match either, then there is no hope,
1422 if (!MatchesSelectValue(FlippedStrictness->second))
1425 // It matched! Lets insert the new comparison just before select.
1426 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1427 IC.Builder.SetInsertPoint(&Sel);
1429 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1430 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1431 Cmp.getName() + ".inv");
1432 IC.replaceOperand(Sel, 0, NewCmp);
1434 Sel.swapProfMetadata();
1439 /// Visit a SelectInst that has an ICmpInst as its first operand.
1440 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1442 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
1443 return replaceInstUsesWith(SI, V);
1445 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1448 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1451 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1454 if (Instruction *NewSel =
1455 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1458 bool Changed = adjustMinMax(SI, *ICI);
1460 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1461 return replaceInstUsesWith(SI, V);
1463 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1464 Value *TrueVal = SI.getTrueValue();
1465 Value *FalseVal = SI.getFalseValue();
1466 ICmpInst::Predicate Pred = ICI->getPredicate();
1467 Value *CmpLHS = ICI->getOperand(0);
1468 Value *CmpRHS = ICI->getOperand(1);
1469 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1470 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1471 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1472 SI.setOperand(1, CmpRHS);
1474 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1475 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1476 SI.setOperand(2, CmpRHS);
1481 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1482 // decomposeBitTestICmp() might help.
1485 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1486 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1490 bool IsBitTest = false;
1491 if (ICmpInst::isEquality(Pred) &&
1492 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1493 match(CmpRHS, m_Zero())) {
1495 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1496 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1498 Y = &MinSignedValue;
1500 TrueWhenUnset = false;
1501 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1503 Y = &MinSignedValue;
1505 TrueWhenUnset = true;
1509 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1510 if (TrueWhenUnset && TrueVal == X &&
1511 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1512 V = Builder.CreateAnd(X, ~(*Y));
1513 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1514 else if (!TrueWhenUnset && FalseVal == X &&
1515 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1516 V = Builder.CreateAnd(X, ~(*Y));
1517 // (X & Y) == 0 ? X ^ Y : X --> X | Y
1518 else if (TrueWhenUnset && FalseVal == X &&
1519 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1520 V = Builder.CreateOr(X, *Y);
1521 // (X & Y) != 0 ? X : X ^ Y --> X | Y
1522 else if (!TrueWhenUnset && TrueVal == X &&
1523 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1524 V = Builder.CreateOr(X, *Y);
1527 return replaceInstUsesWith(SI, V);
1531 if (Instruction *V =
1532 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1535 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1538 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1539 return replaceInstUsesWith(SI, V);
1541 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1542 return replaceInstUsesWith(SI, V);
1544 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1545 return replaceInstUsesWith(SI, V);
1547 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1548 return replaceInstUsesWith(SI, V);
1550 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1551 return replaceInstUsesWith(SI, V);
1553 return Changed ? &SI : nullptr;
1556 /// SI is a select whose condition is a PHI node (but the two may be in
1557 /// different blocks). See if the true/false values (V) are live in all of the
1558 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1560 /// X = phi [ C1, BB1], [C2, BB2]
1562 /// Z = select X, Y, 0
1564 /// because Y is not live in BB1/BB2.
1565 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1566 const SelectInst &SI) {
1567 // If the value is a non-instruction value like a constant or argument, it
1568 // can always be mapped.
1569 const Instruction *I = dyn_cast<Instruction>(V);
1570 if (!I) return true;
1572 // If V is a PHI node defined in the same block as the condition PHI, we can
1573 // map the arguments.
1574 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1576 if (const PHINode *VP = dyn_cast<PHINode>(I))
1577 if (VP->getParent() == CondPHI->getParent())
1580 // Otherwise, if the PHI and select are defined in the same block and if V is
1581 // defined in a different block, then we can transform it.
1582 if (SI.getParent() == CondPHI->getParent() &&
1583 I->getParent() != CondPHI->getParent())
1586 // Otherwise we have a 'hard' case and we can't tell without doing more
1587 // detailed dominator based analysis, punt.
1591 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1592 /// SPF2(SPF1(A, B), C)
1593 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1594 SelectPatternFlavor SPF1,
1597 SelectPatternFlavor SPF2, Value *C) {
1598 if (Outer.getType() != Inner->getType())
1601 if (C == A || C == B) {
1602 // MAX(MAX(A, B), B) -> MAX(A, B)
1603 // MIN(MIN(a, b), a) -> MIN(a, b)
1604 // TODO: This could be done in instsimplify.
1605 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1606 return replaceInstUsesWith(Outer, Inner);
1608 // MAX(MIN(a, b), a) -> a
1609 // MIN(MAX(a, b), a) -> a
1610 // TODO: This could be done in instsimplify.
1611 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1612 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1613 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1614 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1615 return replaceInstUsesWith(Outer, C);
1619 const APInt *CB, *CC;
1620 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1621 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1622 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1623 // TODO: This could be done in instsimplify.
1624 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1625 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1626 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1627 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1628 return replaceInstUsesWith(Outer, Inner);
1630 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1631 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1632 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1633 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1634 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1635 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1636 Outer.replaceUsesOfWith(Inner, A);
1642 // max(max(A, B), min(A, B)) --> max(A, B)
1643 // min(min(A, B), max(A, B)) --> min(A, B)
1644 // TODO: This could be done in instsimplify.
1646 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1647 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1648 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1649 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1650 return replaceInstUsesWith(Outer, Inner);
1652 // ABS(ABS(X)) -> ABS(X)
1653 // NABS(NABS(X)) -> NABS(X)
1654 // TODO: This could be done in instsimplify.
1655 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1656 return replaceInstUsesWith(Outer, Inner);
1659 // ABS(NABS(X)) -> ABS(X)
1660 // NABS(ABS(X)) -> NABS(X)
1661 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1662 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1663 SelectInst *SI = cast<SelectInst>(Inner);
1665 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1666 SI->getTrueValue(), SI->getName(), SI);
1667 return replaceInstUsesWith(Outer, NewSI);
1670 auto IsFreeOrProfitableToInvert =
1671 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1672 if (match(V, m_Not(m_Value(NotV)))) {
1673 // If V has at most 2 uses then we can get rid of the xor operation
1675 ElidesXor |= !V->hasNUsesOrMore(3);
1679 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1687 Value *NotA, *NotB, *NotC;
1688 bool ElidesXor = false;
1690 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1691 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1692 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1693 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1695 // This transform is performance neutral if we can elide at least one xor from
1696 // the set of three operands, since we'll be tacking on an xor at the very
1698 if (SelectPatternResult::isMinOrMax(SPF1) &&
1699 SelectPatternResult::isMinOrMax(SPF2) &&
1700 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1701 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1702 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1704 NotA = Builder.CreateNot(A);
1706 NotB = Builder.CreateNot(B);
1708 NotC = Builder.CreateNot(C);
1710 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1712 Value *NewOuter = Builder.CreateNot(
1713 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1714 return replaceInstUsesWith(Outer, NewOuter);
1720 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1721 /// This is even legal for FP.
1722 static Instruction *foldAddSubSelect(SelectInst &SI,
1723 InstCombiner::BuilderTy &Builder) {
1724 Value *CondVal = SI.getCondition();
1725 Value *TrueVal = SI.getTrueValue();
1726 Value *FalseVal = SI.getFalseValue();
1727 auto *TI = dyn_cast<Instruction>(TrueVal);
1728 auto *FI = dyn_cast<Instruction>(FalseVal);
1729 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1732 Instruction *AddOp = nullptr, *SubOp = nullptr;
1733 if ((TI->getOpcode() == Instruction::Sub &&
1734 FI->getOpcode() == Instruction::Add) ||
1735 (TI->getOpcode() == Instruction::FSub &&
1736 FI->getOpcode() == Instruction::FAdd)) {
1739 } else if ((FI->getOpcode() == Instruction::Sub &&
1740 TI->getOpcode() == Instruction::Add) ||
1741 (FI->getOpcode() == Instruction::FSub &&
1742 TI->getOpcode() == Instruction::FAdd)) {
1748 Value *OtherAddOp = nullptr;
1749 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1750 OtherAddOp = AddOp->getOperand(1);
1751 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1752 OtherAddOp = AddOp->getOperand(0);
1756 // So at this point we know we have (Y -> OtherAddOp):
1757 // select C, (add X, Y), (sub X, Z)
1758 Value *NegVal; // Compute -Z
1759 if (SI.getType()->isFPOrFPVectorTy()) {
1760 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1761 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1762 FastMathFlags Flags = AddOp->getFastMathFlags();
1763 Flags &= SubOp->getFastMathFlags();
1764 NegInst->setFastMathFlags(Flags);
1767 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1770 Value *NewTrueOp = OtherAddOp;
1771 Value *NewFalseOp = NegVal;
1773 std::swap(NewTrueOp, NewFalseOp);
1774 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1775 SI.getName() + ".p", &SI);
1777 if (SI.getType()->isFPOrFPVectorTy()) {
1779 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1781 FastMathFlags Flags = AddOp->getFastMathFlags();
1782 Flags &= SubOp->getFastMathFlags();
1783 RI->setFastMathFlags(Flags);
1786 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1792 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1793 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1794 /// Along with a number of patterns similar to:
1795 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1796 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1797 static Instruction *
1798 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1799 Value *CondVal = SI.getCondition();
1800 Value *TrueVal = SI.getTrueValue();
1801 Value *FalseVal = SI.getFalseValue();
1803 WithOverflowInst *II;
1804 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1805 !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1808 Value *X = II->getLHS();
1809 Value *Y = II->getRHS();
1811 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1812 Type *Ty = Limit->getType();
1814 ICmpInst::Predicate Pred;
1815 Value *TrueVal, *FalseVal, *Op;
1817 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1818 m_Value(TrueVal), m_Value(FalseVal))))
1821 auto IsZeroOrOne = [](const APInt &C) {
1822 return C.isNullValue() || C.isOneValue();
1824 auto IsMinMax = [&](Value *Min, Value *Max) {
1825 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1826 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1827 return match(Min, m_SpecificInt(MinVal)) &&
1828 match(Max, m_SpecificInt(MaxVal));
1831 if (Op != X && Op != Y)
1835 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1836 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1837 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1838 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1839 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1840 IsMinMax(TrueVal, FalseVal))
1842 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1843 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1844 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1845 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1846 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1847 IsMinMax(FalseVal, TrueVal))
1850 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1851 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1852 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1853 IsMinMax(TrueVal, FalseVal))
1855 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1856 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1857 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1858 IsMinMax(FalseVal, TrueVal))
1860 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1861 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1862 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1863 IsMinMax(FalseVal, TrueVal))
1865 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1866 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1867 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1868 IsMinMax(TrueVal, FalseVal))
1875 Intrinsic::ID NewIntrinsicID;
1876 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1877 match(TrueVal, m_AllOnes()))
1878 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1879 NewIntrinsicID = Intrinsic::uadd_sat;
1880 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1881 match(TrueVal, m_Zero()))
1882 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1883 NewIntrinsicID = Intrinsic::usub_sat;
1884 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1885 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1886 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1887 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1888 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1889 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1890 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1891 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1892 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1893 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1894 NewIntrinsicID = Intrinsic::sadd_sat;
1895 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1896 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1897 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1898 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1899 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1900 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1901 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1902 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1903 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1904 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1905 NewIntrinsicID = Intrinsic::ssub_sat;
1910 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1911 return CallInst::Create(F, {X, Y});
1914 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1916 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1917 !match(Sel.getFalseValue(), m_Constant(C)))
1920 Instruction *ExtInst;
1921 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1922 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1925 auto ExtOpcode = ExtInst->getOpcode();
1926 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1929 // If we are extending from a boolean type or if we can create a select that
1930 // has the same size operands as its condition, try to narrow the select.
1931 Value *X = ExtInst->getOperand(0);
1932 Type *SmallType = X->getType();
1933 Value *Cond = Sel.getCondition();
1934 auto *Cmp = dyn_cast<CmpInst>(Cond);
1935 if (!SmallType->isIntOrIntVectorTy(1) &&
1936 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1939 // If the constant is the same after truncation to the smaller type and
1940 // extension to the original type, we can narrow the select.
1941 Type *SelType = Sel.getType();
1942 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1943 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1944 if (ExtC == C && ExtInst->hasOneUse()) {
1945 Value *TruncCVal = cast<Value>(TruncC);
1946 if (ExtInst == Sel.getFalseValue())
1947 std::swap(X, TruncCVal);
1949 // select Cond, (ext X), C --> ext(select Cond, X, C')
1950 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1951 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1952 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1955 // If one arm of the select is the extend of the condition, replace that arm
1956 // with the extension of the appropriate known bool value.
1958 if (ExtInst == Sel.getTrueValue()) {
1959 // select X, (sext X), C --> select X, -1, C
1960 // select X, (zext X), C --> select X, 1, C
1961 Constant *One = ConstantInt::getTrue(SmallType);
1962 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1963 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1965 // select X, C, (sext X) --> select X, C, 0
1966 // select X, C, (zext X) --> select X, C, 0
1967 Constant *Zero = ConstantInt::getNullValue(SelType);
1968 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1975 /// Try to transform a vector select with a constant condition vector into a
1976 /// shuffle for easier combining with other shuffles and insert/extract.
1977 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1978 Value *CondVal = SI.getCondition();
1980 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1983 unsigned NumElts = cast<VectorType>(CondVal->getType())->getNumElements();
1984 SmallVector<int, 16> Mask;
1985 Mask.reserve(NumElts);
1986 for (unsigned i = 0; i != NumElts; ++i) {
1987 Constant *Elt = CondC->getAggregateElement(i);
1991 if (Elt->isOneValue()) {
1992 // If the select condition element is true, choose from the 1st vector.
1994 } else if (Elt->isNullValue()) {
1995 // If the select condition element is false, choose from the 2nd vector.
1996 Mask.push_back(i + NumElts);
1997 } else if (isa<UndefValue>(Elt)) {
1998 // Undef in a select condition (choose one of the operands) does not mean
1999 // the same thing as undef in a shuffle mask (any value is acceptable), so
2003 // Bail out on a constant expression.
2008 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2011 /// If we have a select of vectors with a scalar condition, try to convert that
2012 /// to a vector select by splatting the condition. A splat may get folded with
2013 /// other operations in IR and having all operands of a select be vector types
2014 /// is likely better for vector codegen.
2015 static Instruction *canonicalizeScalarSelectOfVecs(
2016 SelectInst &Sel, InstCombiner &IC) {
2017 auto *Ty = dyn_cast<VectorType>(Sel.getType());
2021 // We can replace a single-use extract with constant index.
2022 Value *Cond = Sel.getCondition();
2023 if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2026 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2027 // Splatting the extracted condition reduces code (we could directly create a
2028 // splat shuffle of the source vector to eliminate the intermediate step).
2029 unsigned NumElts = Ty->getNumElements();
2030 return IC.replaceOperand(Sel, 0, IC.Builder.CreateVectorSplat(NumElts, Cond));
2033 /// Reuse bitcasted operands between a compare and select:
2034 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2035 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2036 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2037 InstCombiner::BuilderTy &Builder) {
2038 Value *Cond = Sel.getCondition();
2039 Value *TVal = Sel.getTrueValue();
2040 Value *FVal = Sel.getFalseValue();
2042 CmpInst::Predicate Pred;
2044 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2047 // The select condition is a compare instruction. If the select's true/false
2048 // values are already the same as the compare operands, there's nothing to do.
2049 if (TVal == A || TVal == B || FVal == A || FVal == B)
2053 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2056 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2058 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2059 !match(FVal, m_BitCast(m_Value(FSrc))))
2062 // If the select true/false values are *different bitcasts* of the same source
2063 // operands, make the select operands the same as the compare operands and
2064 // cast the result. This is the canonical select form for min/max.
2066 if (TSrc == C && FSrc == D) {
2067 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2068 // bitcast (select (cmp A, B), A, B)
2069 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2070 } else if (TSrc == D && FSrc == C) {
2071 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2072 // bitcast (select (cmp A, B), B, A)
2073 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2077 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2080 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2083 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2084 /// selects between the returned value of the cmpxchg instruction its compare
2085 /// operand, the result of the select will always be equal to its false value.
2088 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2089 /// %1 = extractvalue { i64, i1 } %0, 1
2090 /// %2 = extractvalue { i64, i1 } %0, 0
2091 /// %3 = select i1 %1, i64 %compare, i64 %2
2094 /// The returned value of the cmpxchg instruction (%2) is the original value
2095 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2096 /// must have been equal to %compare. Thus, the result of the select is always
2097 /// equal to %2, and the code can be simplified to:
2099 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2100 /// %1 = extractvalue { i64, i1 } %0, 0
2103 static Value *foldSelectCmpXchg(SelectInst &SI) {
2104 // A helper that determines if V is an extractvalue instruction whose
2105 // aggregate operand is a cmpxchg instruction and whose single index is equal
2106 // to I. If such conditions are true, the helper returns the cmpxchg
2107 // instruction; otherwise, a nullptr is returned.
2108 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2109 auto *Extract = dyn_cast<ExtractValueInst>(V);
2112 if (Extract->getIndices()[0] != I)
2114 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2117 // If the select has a single user, and this user is a select instruction that
2118 // we can simplify, skip the cmpxchg simplification for now.
2120 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2121 if (Select->getCondition() == SI.getCondition())
2122 if (Select->getFalseValue() == SI.getTrueValue() ||
2123 Select->getTrueValue() == SI.getFalseValue())
2126 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2127 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2131 // Check the true value case: The true value of the select is the returned
2132 // value of the same cmpxchg used by the condition, and the false value is the
2133 // cmpxchg instruction's compare operand.
2134 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2135 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2136 return SI.getFalseValue();
2138 // Check the false value case: The false value of the select is the returned
2139 // value of the same cmpxchg used by the condition, and the true value is the
2140 // cmpxchg instruction's compare operand.
2141 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2142 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2143 return SI.getFalseValue();
2148 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2150 InstCombiner::BuilderTy &Builder) {
2151 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2152 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2153 SPF == SelectPatternFlavor::SPF_UMAX;
2154 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2155 // the constant value check to an assert.
2157 const APInt *C1, *C2;
2158 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2159 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2160 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2161 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2162 Value *NewMinMax = createMinMax(Builder, SPF, A,
2163 ConstantInt::get(X->getType(), *C2 - *C1));
2164 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2165 ConstantInt::get(X->getType(), *C1));
2168 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2169 match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2171 APInt Diff = C2->ssub_ov(*C1, Overflow);
2173 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2174 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2175 Value *NewMinMax = createMinMax(Builder, SPF, A,
2176 ConstantInt::get(X->getType(), Diff));
2177 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2178 ConstantInt::get(X->getType(), *C1));
2185 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2186 Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) {
2187 Type *Ty = MinMax1.getType();
2189 // We are looking for a tree of:
2190 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2191 // Where the min and max could be reversed
2192 Instruction *MinMax2;
2193 BinaryOperator *AddSub;
2194 const APInt *MinValue, *MaxValue;
2195 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2196 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2198 } else if (match(&MinMax1,
2199 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2200 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2205 // Check that the constants clamp a saturate, and that the new type would be
2206 // sensible to convert to.
2207 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2209 // In what bitwidth can this be treated as saturating arithmetics?
2210 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2211 // FIXME: This isn't quite right for vectors, but using the scalar type is a
2212 // good first approximation for what should be done there.
2213 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2216 // Also make sure that the number of uses is as expected. The "3"s are for the
2217 // the two items of min/max (the compare and the select).
2218 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2221 // Create the new type (which can be a vector type)
2222 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2223 // Match the two extends from the add/sub
2225 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2227 // And check the incoming values are of a type smaller than or equal to the
2228 // size of the saturation. Otherwise the higher bits can cause different
2230 if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2231 B->getType()->getScalarSizeInBits() > NewBitWidth)
2234 Intrinsic::ID IntrinsicID;
2235 if (AddSub->getOpcode() == Instruction::Add)
2236 IntrinsicID = Intrinsic::sadd_sat;
2237 else if (AddSub->getOpcode() == Instruction::Sub)
2238 IntrinsicID = Intrinsic::ssub_sat;
2242 // Finally create and return the sat intrinsic, truncated to the new type
2243 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2244 Value *AT = Builder.CreateSExt(A, NewTy);
2245 Value *BT = Builder.CreateSExt(B, NewTy);
2246 Value *Sat = Builder.CreateCall(F, {AT, BT});
2247 return CastInst::Create(Instruction::SExt, Sat, Ty);
2250 /// Reduce a sequence of min/max with a common operand.
2251 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2253 InstCombiner::BuilderTy &Builder) {
2254 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2255 // TODO: Allow FP min/max with nnan/nsz.
2256 if (!LHS->getType()->isIntOrIntVectorTy())
2259 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2260 Value *A, *B, *C, *D;
2261 SelectPatternResult L = matchSelectPattern(LHS, A, B);
2262 SelectPatternResult R = matchSelectPattern(RHS, C, D);
2263 if (SPF != L.Flavor || L.Flavor != R.Flavor)
2266 // Look for a common operand. The use checks are different than usual because
2267 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2269 Value *MinMaxOp = nullptr;
2270 Value *ThirdOp = nullptr;
2271 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2272 // If the LHS is only used in this chain and the RHS is used outside of it,
2273 // reuse the RHS min/max because that will eliminate the LHS.
2274 if (D == A || C == A) {
2275 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2276 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2279 } else if (D == B || C == B) {
2280 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2281 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2285 } else if (!RHS->hasNUsesOrMore(3)) {
2286 // Reuse the LHS. This will eliminate the RHS.
2287 if (D == A || D == B) {
2288 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2289 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2292 } else if (C == A || C == B) {
2293 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2294 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2299 if (!MinMaxOp || !ThirdOp)
2302 CmpInst::Predicate P = getMinMaxPred(SPF);
2303 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2304 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2307 /// Try to reduce a rotate pattern that includes a compare and select into a
2308 /// funnel shift intrinsic. Example:
2309 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2310 /// --> call llvm.fshl.i32(a, a, b)
2311 static Instruction *foldSelectRotate(SelectInst &Sel) {
2312 // The false value of the select must be a rotate of the true value.
2314 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
2317 Value *TVal = Sel.getTrueValue();
2319 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
2320 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
2323 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
2324 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
2325 if (ShiftOpcode0 == ShiftOpcode1)
2328 // We have one of these patterns so far:
2329 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
2330 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2331 // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2332 unsigned Width = Sel.getType()->getScalarSizeInBits();
2333 if (!isPowerOf2_32(Width))
2336 // Check the shift amounts to see if they are an opposite pair.
2338 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2340 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2345 // Finally, see if the select is filtering out a shift-by-zero.
2346 Value *Cond = Sel.getCondition();
2347 ICmpInst::Predicate Pred;
2348 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2349 Pred != ICmpInst::ICMP_EQ)
2352 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2353 // Convert to funnel shift intrinsic.
2354 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
2355 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
2356 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2357 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2358 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
2361 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2362 InstCombiner::BuilderTy &Builder) {
2363 Value *Cond = Sel.getCondition();
2364 Value *TVal = Sel.getTrueValue();
2365 Value *FVal = Sel.getFalseValue();
2366 Type *SelType = Sel.getType();
2368 // Match select ?, TC, FC where the constants are equal but negated.
2369 // TODO: Generalize to handle a negated variable operand?
2370 const APFloat *TC, *FC;
2371 if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2372 !abs(*TC).bitwiseIsEqual(abs(*FC)))
2375 assert(TC != FC && "Expected equal select arms to simplify");
2379 bool IsTrueIfSignSet;
2380 ICmpInst::Predicate Pred;
2381 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2382 !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType)
2385 // If needed, negate the value that will be the sign argument of the copysign:
2386 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
2387 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
2388 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
2389 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
2390 if (IsTrueIfSignSet ^ TC->isNegative())
2391 X = Builder.CreateFNegFMF(X, &Sel);
2393 // Canonicalize the magnitude argument as the positive constant since we do
2394 // not care about its sign.
2395 Value *MagArg = TC->isNegative() ? FVal : TVal;
2396 Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2398 Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X });
2399 CopySign->setFastMathFlags(Sel.getFastMathFlags());
2403 Instruction *InstCombiner::foldVectorSelect(SelectInst &Sel) {
2404 auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2408 unsigned NumElts = VecTy->getNumElements();
2409 APInt UndefElts(NumElts, 0);
2410 APInt AllOnesEltMask(APInt::getAllOnesValue(NumElts));
2411 if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2413 return replaceInstUsesWith(Sel, V);
2417 // A select of a "select shuffle" with a common operand can be rearranged
2418 // to select followed by "select shuffle". Because of poison, this only works
2419 // in the case of a shuffle with no undefined mask elements.
2420 Value *Cond = Sel.getCondition();
2421 Value *TVal = Sel.getTrueValue();
2422 Value *FVal = Sel.getFalseValue();
2425 if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2426 !is_contained(Mask, UndefMaskElem) &&
2427 cast<ShuffleVectorInst>(TVal)->isSelect()) {
2429 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2430 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2431 return new ShuffleVectorInst(X, NewSel, Mask);
2434 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2435 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2436 return new ShuffleVectorInst(NewSel, Y, Mask);
2439 if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2440 !is_contained(Mask, UndefMaskElem) &&
2441 cast<ShuffleVectorInst>(FVal)->isSelect()) {
2443 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2444 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2445 return new ShuffleVectorInst(X, NewSel, Mask);
2448 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2449 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2450 return new ShuffleVectorInst(NewSel, Y, Mask);
2457 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2458 const DominatorTree &DT,
2459 InstCombiner::BuilderTy &Builder) {
2460 // Find the block's immediate dominator that ends with a conditional branch
2461 // that matches select's condition (maybe inverted).
2462 auto *IDomNode = DT[BB]->getIDom();
2465 BasicBlock *IDom = IDomNode->getBlock();
2467 Value *Cond = Sel.getCondition();
2468 Value *IfTrue, *IfFalse;
2469 BasicBlock *TrueSucc, *FalseSucc;
2470 if (match(IDom->getTerminator(),
2471 m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2472 m_BasicBlock(FalseSucc)))) {
2473 IfTrue = Sel.getTrueValue();
2474 IfFalse = Sel.getFalseValue();
2475 } else if (match(IDom->getTerminator(),
2476 m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2477 m_BasicBlock(FalseSucc)))) {
2478 IfTrue = Sel.getFalseValue();
2479 IfFalse = Sel.getTrueValue();
2483 // Make sure the branches are actually different.
2484 if (TrueSucc == FalseSucc)
2487 // We want to replace select %cond, %a, %b with a phi that takes value %a
2488 // for all incoming edges that are dominated by condition `%cond == true`,
2489 // and value %b for edges dominated by condition `%cond == false`. If %a
2490 // or %b are also phis from the same basic block, we can go further and take
2491 // their incoming values from the corresponding blocks.
2492 BasicBlockEdge TrueEdge(IDom, TrueSucc);
2493 BasicBlockEdge FalseEdge(IDom, FalseSucc);
2494 DenseMap<BasicBlock *, Value *> Inputs;
2495 for (auto *Pred : predecessors(BB)) {
2496 // Check implication.
2497 BasicBlockEdge Incoming(Pred, BB);
2498 if (DT.dominates(TrueEdge, Incoming))
2499 Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2500 else if (DT.dominates(FalseEdge, Incoming))
2501 Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2504 // Check availability.
2505 if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2506 if (!DT.dominates(Insn, Pred->getTerminator()))
2510 Builder.SetInsertPoint(&*BB->begin());
2511 auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2512 for (auto *Pred : predecessors(BB))
2513 PN->addIncoming(Inputs[Pred], Pred);
2518 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2519 InstCombiner::BuilderTy &Builder) {
2520 // Try to replace this select with Phi in one of these blocks.
2521 SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2522 CandidateBlocks.insert(Sel.getParent());
2523 for (Value *V : Sel.operands())
2524 if (auto *I = dyn_cast<Instruction>(V))
2525 CandidateBlocks.insert(I->getParent());
2527 for (BasicBlock *BB : CandidateBlocks)
2528 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2533 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2534 Value *CondVal = SI.getCondition();
2535 Value *TrueVal = SI.getTrueValue();
2536 Value *FalseVal = SI.getFalseValue();
2537 Type *SelType = SI.getType();
2539 // FIXME: Remove this workaround when freeze related patches are done.
2540 // For select with undef operand which feeds into an equality comparison,
2541 // don't simplify it so loop unswitch can know the equality comparison
2542 // may have an undef operand. This is a workaround for PR31652 caused by
2543 // descrepancy about branch on undef between LoopUnswitch and GVN.
2544 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
2545 if (llvm::any_of(SI.users(), [&](User *U) {
2546 ICmpInst *CI = dyn_cast<ICmpInst>(U);
2547 if (CI && CI->isEquality())
2555 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
2556 SQ.getWithInstruction(&SI)))
2557 return replaceInstUsesWith(SI, V);
2559 if (Instruction *I = canonicalizeSelectToShuffle(SI))
2562 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
2565 CmpInst::Predicate Pred;
2567 if (SelType->isIntOrIntVectorTy(1) &&
2568 TrueVal->getType() == CondVal->getType()) {
2569 if (match(TrueVal, m_One())) {
2570 // Change: A = select B, true, C --> A = or B, C
2571 return BinaryOperator::CreateOr(CondVal, FalseVal);
2573 if (match(TrueVal, m_Zero())) {
2574 // Change: A = select B, false, C --> A = and !B, C
2575 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2576 return BinaryOperator::CreateAnd(NotCond, FalseVal);
2578 if (match(FalseVal, m_Zero())) {
2579 // Change: A = select B, C, false --> A = and B, C
2580 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2582 if (match(FalseVal, m_One())) {
2583 // Change: A = select B, C, true --> A = or !B, C
2584 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2585 return BinaryOperator::CreateOr(NotCond, TrueVal);
2588 // select a, a, b -> a | b
2589 // select a, b, a -> a & b
2590 if (CondVal == TrueVal)
2591 return BinaryOperator::CreateOr(CondVal, FalseVal);
2592 if (CondVal == FalseVal)
2593 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2595 // select a, ~a, b -> (~a) & b
2596 // select a, b, ~a -> (~a) | b
2597 if (match(TrueVal, m_Not(m_Specific(CondVal))))
2598 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2599 if (match(FalseVal, m_Not(m_Specific(CondVal))))
2600 return BinaryOperator::CreateOr(TrueVal, FalseVal);
2603 // Selecting between two integer or vector splat integer constants?
2605 // Note that we don't handle a scalar select of vectors:
2606 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2607 // because that may need 3 instructions to splat the condition value:
2608 // extend, insertelement, shufflevector.
2609 if (SelType->isIntOrIntVectorTy() &&
2610 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2611 // select C, 1, 0 -> zext C to int
2612 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2613 return new ZExtInst(CondVal, SelType);
2615 // select C, -1, 0 -> sext C to int
2616 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2617 return new SExtInst(CondVal, SelType);
2619 // select C, 0, 1 -> zext !C to int
2620 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2621 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2622 return new ZExtInst(NotCond, SelType);
2625 // select C, 0, -1 -> sext !C to int
2626 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2627 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2628 return new SExtInst(NotCond, SelType);
2632 // See if we are selecting two values based on a comparison of the two values.
2633 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
2634 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2635 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
2636 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2637 // Canonicalize to use ordered comparisons by swapping the select
2641 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2642 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
2643 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2644 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2645 // FIXME: The FMF should propagate from the select, not the fcmp.
2646 Builder.setFastMathFlags(FCI->getFastMathFlags());
2647 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2648 FCI->getName() + ".inv");
2649 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
2650 return replaceInstUsesWith(SI, NewSel);
2653 // NOTE: if we wanted to, this is where to detect MIN/MAX
2657 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2658 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2659 // also require nnan because we do not want to unintentionally change the
2660 // sign of a NaN value.
2661 // FIXME: These folds should test/propagate FMF from the select, not the
2663 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2665 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2666 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2667 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2668 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2669 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2670 return replaceInstUsesWith(SI, Fabs);
2672 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
2673 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2674 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2675 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2676 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2677 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2678 return replaceInstUsesWith(SI, Fabs);
2680 // With nnan and nsz:
2681 // (X < +/-0.0) ? -X : X --> fabs(X)
2682 // (X <= +/-0.0) ? -X : X --> fabs(X)
2684 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2685 match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2686 match(TrueVal, m_Instruction(FNeg)) &&
2687 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2688 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2689 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2690 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2691 return replaceInstUsesWith(SI, Fabs);
2693 // With nnan and nsz:
2694 // (X > +/-0.0) ? X : -X --> fabs(X)
2695 // (X >= +/-0.0) ? X : -X --> fabs(X)
2696 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2697 match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2698 match(FalseVal, m_Instruction(FNeg)) &&
2699 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2700 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2701 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2702 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2703 return replaceInstUsesWith(SI, Fabs);
2706 // See if we are selecting two values based on a comparison of the two values.
2707 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2708 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2711 if (Instruction *Add = foldAddSubSelect(SI, Builder))
2713 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2715 if (Instruction *Or = foldSetClearBits(SI, Builder))
2718 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2719 auto *TI = dyn_cast<Instruction>(TrueVal);
2720 auto *FI = dyn_cast<Instruction>(FalseVal);
2721 if (TI && FI && TI->getOpcode() == FI->getOpcode())
2722 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2725 if (Instruction *I = foldSelectExtConst(SI))
2728 // See if we can fold the select into one of our operands.
2729 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2730 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2734 Instruction::CastOps CastOp;
2735 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2736 auto SPF = SPR.Flavor;
2739 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2740 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2741 RHS2, SI, SPF, RHS))
2743 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2744 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2745 RHS2, SI, SPF, LHS))
2748 // ABS(-X) -> ABS(X)
2751 if (SelectPatternResult::isMinOrMax(SPF)) {
2752 // Canonicalize so that
2753 // - type casts are outside select patterns.
2754 // - float clamp is transformed to min/max pattern
2756 bool IsCastNeeded = LHS->getType() != SelType;
2757 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2758 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2760 (LHS->getType()->isFPOrFPVectorTy() &&
2761 ((CmpLHS != LHS && CmpLHS != RHS) ||
2762 (CmpRHS != LHS && CmpRHS != RHS)))) {
2763 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2766 if (CmpInst::isIntPredicate(MinMaxPred)) {
2767 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2769 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2771 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2772 Builder.setFastMathFlags(FMF);
2773 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2776 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2778 return replaceInstUsesWith(SI, NewSI);
2780 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2781 return replaceInstUsesWith(SI, NewCast);
2784 // MAX(~a, ~b) -> ~MIN(a, b)
2785 // MAX(~a, C) -> ~MIN(a, ~C)
2786 // MIN(~a, ~b) -> ~MAX(a, b)
2787 // MIN(~a, C) -> ~MAX(a, ~C)
2788 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2790 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2791 !isFreeToInvert(A, A->hasOneUse()) &&
2792 // Passing false to only consider m_Not and constants.
2793 isFreeToInvert(Y, false)) {
2794 Value *B = Builder.CreateNot(Y);
2795 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2797 // Copy the profile metadata.
2798 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2799 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2800 // Swap the metadata if the operands are swapped.
2801 if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2802 cast<SelectInst>(NewMinMax)->swapProfMetadata();
2805 return BinaryOperator::CreateNot(NewMinMax);
2811 if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2813 if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2816 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2819 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2821 if (Instruction *I = matchSAddSubSat(SI))
2826 // Canonicalize select of FP values where NaN and -0.0 are not valid as
2827 // minnum/maxnum intrinsics.
2828 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2830 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2831 return replaceInstUsesWith(
2832 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2834 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2835 return replaceInstUsesWith(
2836 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2839 // See if we can fold the select into a phi node if the condition is a select.
2840 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2841 // The true/false values have to be live in the PHI predecessor's blocks.
2842 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2843 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2844 if (Instruction *NV = foldOpIntoPhi(SI, PN))
2847 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2848 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2849 // select(C, select(C, a, b), c) -> select(C, a, c)
2850 if (TrueSI->getCondition() == CondVal) {
2851 if (SI.getTrueValue() == TrueSI->getTrueValue())
2853 return replaceOperand(SI, 1, TrueSI->getTrueValue());
2855 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2856 // We choose this as normal form to enable folding on the And and shortening
2857 // paths for the values (this helps GetUnderlyingObjects() for example).
2858 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2859 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2860 replaceOperand(SI, 0, And);
2861 replaceOperand(SI, 1, TrueSI->getTrueValue());
2866 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2867 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2868 // select(C, a, select(C, b, c)) -> select(C, a, c)
2869 if (FalseSI->getCondition() == CondVal) {
2870 if (SI.getFalseValue() == FalseSI->getFalseValue())
2872 return replaceOperand(SI, 2, FalseSI->getFalseValue());
2874 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2875 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2876 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2877 replaceOperand(SI, 0, Or);
2878 replaceOperand(SI, 2, FalseSI->getFalseValue());
2884 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2885 // The select might be preventing a division by 0.
2886 switch (BO->getOpcode()) {
2889 case Instruction::SRem:
2890 case Instruction::URem:
2891 case Instruction::SDiv:
2892 case Instruction::UDiv:
2897 // Try to simplify a binop sandwiched between 2 selects with the same
2899 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2900 BinaryOperator *TrueBO;
2901 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2902 canMergeSelectThroughBinop(TrueBO)) {
2903 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2904 if (TrueBOSI->getCondition() == CondVal) {
2905 replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
2906 Worklist.push(TrueBO);
2910 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2911 if (TrueBOSI->getCondition() == CondVal) {
2912 replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
2913 Worklist.push(TrueBO);
2919 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2920 BinaryOperator *FalseBO;
2921 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2922 canMergeSelectThroughBinop(FalseBO)) {
2923 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2924 if (FalseBOSI->getCondition() == CondVal) {
2925 replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
2926 Worklist.push(FalseBO);
2930 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2931 if (FalseBOSI->getCondition() == CondVal) {
2932 replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
2933 Worklist.push(FalseBO);
2940 if (match(CondVal, m_Not(m_Value(NotCond)))) {
2941 replaceOperand(SI, 0, NotCond);
2943 SI.swapProfMetadata();
2947 if (Instruction *I = foldVectorSelect(SI))
2950 // If we can compute the condition, there's no need for a select.
2951 // Like the above fold, we are attempting to reduce compile-time cost by
2952 // putting this fold here with limitations rather than in InstSimplify.
2953 // The motivation for this call into value tracking is to take advantage of
2954 // the assumption cache, so make sure that is populated.
2955 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2957 computeKnownBits(CondVal, Known, 0, &SI);
2958 if (Known.One.isOneValue())
2959 return replaceInstUsesWith(SI, TrueVal);
2960 if (Known.Zero.isOneValue())
2961 return replaceInstUsesWith(SI, FalseVal);
2964 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2967 // Simplify selects that test the returned flag of cmpxchg instructions.
2968 if (Value *V = foldSelectCmpXchg(SI))
2969 return replaceInstUsesWith(SI, V);
2971 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
2974 if (Instruction *Rot = foldSelectRotate(SI))
2977 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
2980 if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
2981 return replaceInstUsesWith(SI, PN);