1//===- InstCombineSelect.cpp ----------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitSelect function.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/AssumptionCache.h"
18#include "llvm/Analysis/CmpInstAnalysis.h"
19#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/Loads.h"
21#include "llvm/Analysis/OverflowInstAnalysis.h"
22#include "llvm/Analysis/ValueTracking.h"
23#include "llvm/Analysis/VectorUtils.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/FMF.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Operator.h"
37#include "llvm/IR/PatternMatch.h"
38#include "llvm/IR/ProfDataUtils.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/User.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/KnownBits.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Transforms/InstCombine/InstCombiner.h"
47#include <cassert>
48#include <optional>
49#include <utility>
50
51#define DEBUG_TYPE "instcombine"
52#include "llvm/Transforms/Utils/InstructionWorklist.h"
53
54using namespace llvm;
55using namespace PatternMatch;
56
57namespace llvm {
58extern cl::opt<bool> ProfcheckDisableMetadataFixes;
59}
60
61/// Replace a select operand based on an equality comparison with the identity
62/// constant of a binop.
63static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
64 const TargetLibraryInfo &TLI,
65 InstCombinerImpl &IC) {
66 // The select condition must be an equality compare with a constant operand.
67 Value *X;
68 Constant *C;
69 CmpPredicate Pred;
70 if (!match(V: Sel.getCondition(), P: m_Cmp(Pred, L: m_Value(V&: X), R: m_Constant(C))))
71 return nullptr;
72
73 bool IsEq;
74 if (ICmpInst::isEquality(P: Pred))
75 IsEq = Pred == ICmpInst::ICMP_EQ;
76 else if (Pred == FCmpInst::FCMP_OEQ)
77 IsEq = true;
78 else if (Pred == FCmpInst::FCMP_UNE)
79 IsEq = false;
80 else
81 return nullptr;
82
83 // A select operand must be a binop.
84 BinaryOperator *BO;
85 if (!match(V: Sel.getOperand(i_nocapture: IsEq ? 1 : 2), P: m_BinOp(I&: BO)))
86 return nullptr;
87
88 // For absorbing values, we can fold to the compared value.
89 bool IsAbsorbingValue = false;
90
91 // Last, match the compare variable operand with a binop operand.
92 Value *Y;
93 if (BO->isCommutative()) {
94 // Recognized 0 as an absorbing value for fmul, but we need to be careful
95 // about the sign. This could be more aggressive, by handling arbitrary sign
96 // bit operations as long as we know the fmul sign matches (and handling
97 // arbitrary opcodes).
98 if (match(V: BO, P: m_c_FMul(L: m_FAbs(Op0: m_Specific(V: X)), R: m_Value(V&: Y))) &&
99 match(V: C, P: m_AnyZeroFP()) &&
100 IC.fmulByZeroIsZero(MulVal: Y, FMF: BO->getFastMathFlags(), CtxI: &Sel))
101 IsAbsorbingValue = true;
102 else if (!match(V: BO, P: m_c_BinOp(L: m_Value(V&: Y), R: m_Specific(V: X))))
103 return nullptr;
104 } else {
105 if (!match(V: BO, P: m_BinOp(L: m_Value(V&: Y), R: m_Specific(V: X))))
106 return nullptr;
107 }
108
109 // The compare constant must be the identity constant for that binop.
110 // If this a floating-point compare with 0.0, any zero constant will do.
111 Type *Ty = BO->getType();
112
113 Value *FoldedVal;
114 if (IsAbsorbingValue) {
115 FoldedVal = C;
116 } else {
117 Constant *IdC = ConstantExpr::getBinOpIdentity(Opcode: BO->getOpcode(), Ty, AllowRHSConstant: true);
118 if (IdC != C) {
119 if (!IdC || !CmpInst::isFPPredicate(P: Pred))
120 return nullptr;
121
122 if (!match(V: IdC, P: m_AnyZeroFP()) || !match(V: C, P: m_AnyZeroFP()))
123 return nullptr;
124 }
125
126 // +0.0 compares equal to -0.0, and so it does not behave as required for
127 // this transform. Bail out if we can not exclude that possibility.
128 if (const auto *FPO = dyn_cast<FPMathOperator>(Val: BO))
129 if (!FPO->hasNoSignedZeros() &&
130 !cannotBeNegativeZero(V: Y,
131 SQ: IC.getSimplifyQuery().getWithInstruction(I: &Sel)))
132 return nullptr;
133
134 FoldedVal = Y;
135 }
136
137 // BO = binop Y, X
138 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
139 // =>
140 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
141 return IC.replaceOperand(I&: Sel, OpNum: IsEq ? 1 : 2, V: FoldedVal);
142}
143
144/// This folds:
145/// select (icmp eq (and X, C1)), TC, FC
146/// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
147/// To something like:
148/// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
149/// Or:
150/// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
151/// With some variations depending if FC is larger than TC, or the shift
152/// isn't needed, or the bit widths don't match.
153static Value *foldSelectICmpAnd(SelectInst &Sel, Value *CondVal, Value *TrueVal,
154 Value *FalseVal, Value *V, const APInt &AndMask,
155 bool CreateAnd,
156 InstCombiner::BuilderTy &Builder) {
157 const APInt *SelTC, *SelFC;
158 if (!match(V: TrueVal, P: m_APInt(Res&: SelTC)) || !match(V: FalseVal, P: m_APInt(Res&: SelFC)))
159 return nullptr;
160
161 Type *SelType = Sel.getType();
162 // In general, when both constants are non-zero, we would need an offset to
163 // replace the select. This would require more instructions than we started
164 // with. But there's one special-case that we handle here because it can
165 // simplify/reduce the instructions.
166 const APInt &TC = *SelTC;
167 const APInt &FC = *SelFC;
168 if (!TC.isZero() && !FC.isZero()) {
169 if (TC.getBitWidth() != AndMask.getBitWidth())
170 return nullptr;
171 // If we have to create an 'and', then we must kill the cmp to not
172 // increase the instruction count.
173 if (CreateAnd && !CondVal->hasOneUse())
174 return nullptr;
175
176 // (V & AndMaskC) == 0 ? TC : FC --> TC | (V & AndMaskC)
177 // (V & AndMaskC) == 0 ? TC : FC --> TC ^ (V & AndMaskC)
178 // (V & AndMaskC) == 0 ? TC : FC --> TC + (V & AndMaskC)
179 // (V & AndMaskC) == 0 ? TC : FC --> TC - (V & AndMaskC)
180 Constant *TCC = ConstantInt::get(Ty: SelType, V: TC);
181 Constant *FCC = ConstantInt::get(Ty: SelType, V: FC);
182 Constant *MaskC = ConstantInt::get(Ty: SelType, V: AndMask);
183 for (auto Opc : {Instruction::Or, Instruction::Xor, Instruction::Add,
184 Instruction::Sub}) {
185 if (ConstantFoldBinaryOpOperands(Opcode: Opc, LHS: TCC, RHS: MaskC, DL: Sel.getDataLayout()) ==
186 FCC) {
187 if (CreateAnd)
188 V = Builder.CreateAnd(LHS: V, RHS: MaskC);
189 return Builder.CreateBinOp(Opc, LHS: TCC, RHS: V);
190 }
191 }
192
193 return nullptr;
194 }
195
196 // Make sure one of the select arms is a power-of-2.
197 if (!TC.isPowerOf2() && !FC.isPowerOf2())
198 return nullptr;
199
200 // Determine which shift is needed to transform result of the 'and' into the
201 // desired result.
202 const APInt &ValC = !TC.isZero() ? TC : FC;
203 unsigned ValZeros = ValC.logBase2();
204 unsigned AndZeros = AndMask.logBase2();
205 bool ShouldNotVal = !TC.isZero();
206 bool NeedShift = ValZeros != AndZeros;
207 bool NeedZExtTrunc =
208 SelType->getScalarSizeInBits() != V->getType()->getScalarSizeInBits();
209
210 // If we would need to create an 'and' + 'shift' + 'xor' + cast to replace
211 // a 'select' + 'icmp', then this transformation would result in more
212 // instructions and potentially interfere with other folding.
213 if (CreateAnd + ShouldNotVal + NeedShift + NeedZExtTrunc >
214 1 + CondVal->hasOneUse())
215 return nullptr;
216
217 // Insert the 'and' instruction on the input to the truncate.
218 if (CreateAnd)
219 V = Builder.CreateAnd(LHS: V, RHS: ConstantInt::get(Ty: V->getType(), V: AndMask));
220
221 // If types don't match, we can still convert the select by introducing a zext
222 // or a trunc of the 'and'.
223 if (ValZeros > AndZeros) {
224 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
225 V = Builder.CreateShl(LHS: V, RHS: ValZeros - AndZeros);
226 } else if (ValZeros < AndZeros) {
227 V = Builder.CreateLShr(LHS: V, RHS: AndZeros - ValZeros);
228 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
229 } else {
230 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
231 }
232
233 // Okay, now we know that everything is set up, we just don't know whether we
234 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
235 if (ShouldNotVal)
236 V = Builder.CreateXor(LHS: V, RHS: ValC);
237
238 return V;
239}
240
241/// We want to turn code that looks like this:
242/// %C = or %A, %B
243/// %D = select %cond, %C, %A
244/// into:
245/// %C = select %cond, %B, 0
246/// %D = or %A, %C
247///
248/// Assuming that the specified instruction is an operand to the select, return
249/// a bitmask indicating which operands of this instruction are foldable if they
250/// equal the other incoming value of the select.
251static unsigned getSelectFoldableOperands(BinaryOperator *I) {
252 switch (I->getOpcode()) {
253 case Instruction::Add:
254 case Instruction::FAdd:
255 case Instruction::Mul:
256 case Instruction::FMul:
257 case Instruction::And:
258 case Instruction::Or:
259 case Instruction::Xor:
260 return 3; // Can fold through either operand.
261 case Instruction::Sub: // Can only fold on the amount subtracted.
262 case Instruction::FSub:
263 case Instruction::FDiv: // Can only fold on the divisor amount.
264 case Instruction::Shl: // Can only fold on the shift amount.
265 case Instruction::LShr:
266 case Instruction::AShr:
267 return 1;
268 default:
269 return 0; // Cannot fold
270 }
271}
272
273/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
274Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
275 Instruction *FI) {
276 // If this is a cast from the same type, merge.
277 Value *Cond = SI.getCondition();
278 Type *CondTy = Cond->getType();
279 if (TI->getNumOperands() == 1 && TI->isCast()) {
280 Type *FIOpndTy = FI->getOperand(i: 0)->getType();
281 if (TI->getOperand(i: 0)->getType() != FIOpndTy)
282 return nullptr;
283
284 // The select condition may be a vector. We may only change the operand
285 // type if the vector width remains the same (and matches the condition).
286 if (auto *CondVTy = dyn_cast<VectorType>(Val: CondTy)) {
287 if (!FIOpndTy->isVectorTy() ||
288 CondVTy->getElementCount() !=
289 cast<VectorType>(Val: FIOpndTy)->getElementCount())
290 return nullptr;
291
292 // TODO: If the backend knew how to deal with casts better, we could
293 // remove this limitation. For now, there's too much potential to create
294 // worse codegen by promoting the select ahead of size-altering casts
295 // (PR28160).
296 //
297 // Note that ValueTracking's matchSelectPattern() looks through casts
298 // without checking 'hasOneUse' when it matches min/max patterns, so this
299 // transform may end up happening anyway.
300 if (TI->getOpcode() != Instruction::BitCast &&
301 (!TI->hasOneUse() || !FI->hasOneUse()))
302 return nullptr;
303 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
304 // TODO: The one-use restrictions for a scalar select could be eased if
305 // the fold of a select in visitLoadInst() was enhanced to match a pattern
306 // that includes a cast.
307 return nullptr;
308 }
309
310 // Fold this by inserting a select from the input values.
311 Value *NewSI =
312 Builder.CreateSelect(C: Cond, True: TI->getOperand(i: 0), False: FI->getOperand(i: 0),
313 Name: SI.getName() + ".v", MDFrom: &SI);
314 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), S: NewSI,
315 Ty: TI->getType());
316 }
317
318 Value *OtherOpT, *OtherOpF;
319 bool MatchIsOpZero;
320 auto getCommonOp = [&](Instruction *TI, Instruction *FI, bool Commute,
321 bool Swapped = false) -> Value * {
322 assert(!(Commute && Swapped) &&
323 "Commute and Swapped can't set at the same time");
324 if (!Swapped) {
325 if (TI->getOperand(i: 0) == FI->getOperand(i: 0)) {
326 OtherOpT = TI->getOperand(i: 1);
327 OtherOpF = FI->getOperand(i: 1);
328 MatchIsOpZero = true;
329 return TI->getOperand(i: 0);
330 } else if (TI->getOperand(i: 1) == FI->getOperand(i: 1)) {
331 OtherOpT = TI->getOperand(i: 0);
332 OtherOpF = FI->getOperand(i: 0);
333 MatchIsOpZero = false;
334 return TI->getOperand(i: 1);
335 }
336 }
337
338 if (!Commute && !Swapped)
339 return nullptr;
340
341 // If we are allowing commute or swap of operands, then
342 // allow a cross-operand match. In that case, MatchIsOpZero
343 // means that TI's operand 0 (FI's operand 1) is the common op.
344 if (TI->getOperand(i: 0) == FI->getOperand(i: 1)) {
345 OtherOpT = TI->getOperand(i: 1);
346 OtherOpF = FI->getOperand(i: 0);
347 MatchIsOpZero = true;
348 return TI->getOperand(i: 0);
349 } else if (TI->getOperand(i: 1) == FI->getOperand(i: 0)) {
350 OtherOpT = TI->getOperand(i: 0);
351 OtherOpF = FI->getOperand(i: 1);
352 MatchIsOpZero = false;
353 return TI->getOperand(i: 1);
354 }
355 return nullptr;
356 };
357
358 if (TI->hasOneUse() || FI->hasOneUse()) {
359 // Cond ? -X : -Y --> -(Cond ? X : Y)
360 Value *X, *Y;
361 if (match(V: TI, P: m_FNeg(X: m_Value(V&: X))) && match(V: FI, P: m_FNeg(X: m_Value(V&: Y)))) {
362 // Intersect FMF from the fneg instructions and union those with the
363 // select.
364 FastMathFlags FMF = TI->getFastMathFlags();
365 FMF &= FI->getFastMathFlags();
366 FMF |= SI.getFastMathFlags();
367 Value *NewSel =
368 Builder.CreateSelect(C: Cond, True: X, False: Y, Name: SI.getName() + ".v", MDFrom: &SI);
369 if (auto *NewSelI = dyn_cast<Instruction>(Val: NewSel))
370 NewSelI->setFastMathFlags(FMF);
371 Instruction *NewFNeg = UnaryOperator::CreateFNeg(V: NewSel);
372 NewFNeg->setFastMathFlags(FMF);
373 return NewFNeg;
374 }
375
376 // Min/max intrinsic with a common operand can have the common operand
377 // pulled after the select. This is the same transform as below for binops,
378 // but specialized for intrinsic matching and without the restrictive uses
379 // clause.
380 auto *TII = dyn_cast<IntrinsicInst>(Val: TI);
381 auto *FII = dyn_cast<IntrinsicInst>(Val: FI);
382 if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID()) {
383 if (match(V: TII, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()))) {
384 if (Value *MatchOp = getCommonOp(TI, FI, true)) {
385 Value *NewSel =
386 Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF, Name: "minmaxop", MDFrom: &SI);
387 return CallInst::Create(Func: TII->getCalledFunction(), Args: {NewSel, MatchOp});
388 }
389 }
390
391 // select c, (ldexp v, e0), (ldexp v, e1) -> ldexp v, (select c, e0, e1)
392 // select c, (ldexp v0, e), (ldexp v1, e) -> ldexp (select c, v0, v1), e
393 //
394 // select c, (ldexp v0, e0), (ldexp v1, e1) ->
395 // ldexp (select c, v0, v1), (select c, e0, e1)
396 if (TII->getIntrinsicID() == Intrinsic::ldexp) {
397 Value *LdexpVal0 = TII->getArgOperand(i: 0);
398 Value *LdexpExp0 = TII->getArgOperand(i: 1);
399 Value *LdexpVal1 = FII->getArgOperand(i: 0);
400 Value *LdexpExp1 = FII->getArgOperand(i: 1);
401 if (LdexpExp0->getType() == LdexpExp1->getType()) {
402 FPMathOperator *SelectFPOp = cast<FPMathOperator>(Val: &SI);
403 FastMathFlags FMF = cast<FPMathOperator>(Val: TII)->getFastMathFlags();
404 FMF &= cast<FPMathOperator>(Val: FII)->getFastMathFlags();
405 FMF |= SelectFPOp->getFastMathFlags();
406
407 Value *SelectVal = Builder.CreateSelect(C: Cond, True: LdexpVal0, False: LdexpVal1);
408 Value *SelectExp = Builder.CreateSelect(C: Cond, True: LdexpExp0, False: LdexpExp1);
409
410 Value *NewLdexp = Builder.CreateIntrinsic(
411 RetTy: TII->getType(), ID: Intrinsic::ldexp, Args: {SelectVal, SelectExp}, FMFSource: FMF);
412 return replaceInstUsesWith(I&: SI, V: NewLdexp);
413 }
414 }
415 }
416
417 auto CreateCmpSel = [&](std::optional<CmpPredicate> P,
418 bool Swapped) -> CmpInst * {
419 if (!P)
420 return nullptr;
421 auto *MatchOp = getCommonOp(TI, FI, ICmpInst::isEquality(P: *P),
422 ICmpInst::isRelational(P: *P) && Swapped);
423 if (!MatchOp)
424 return nullptr;
425 Value *NewSel = Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF,
426 Name: SI.getName() + ".v", MDFrom: &SI);
427 return new ICmpInst(MatchIsOpZero ? *P
428 : ICmpInst::getSwappedCmpPredicate(Pred: *P),
429 MatchOp, NewSel);
430 };
431
432 // icmp with a common operand also can have the common operand
433 // pulled after the select.
434 CmpPredicate TPred, FPred;
435 if (match(V: TI, P: m_ICmp(Pred&: TPred, L: m_Value(), R: m_Value())) &&
436 match(V: FI, P: m_ICmp(Pred&: FPred, L: m_Value(), R: m_Value()))) {
437 if (auto *R =
438 CreateCmpSel(CmpPredicate::getMatching(A: TPred, B: FPred), false))
439 return R;
440 if (auto *R =
441 CreateCmpSel(CmpPredicate::getMatching(
442 A: TPred, B: ICmpInst::getSwappedCmpPredicate(Pred: FPred)),
443 true))
444 return R;
445 }
446 }
447
448 // Only handle binary operators (including two-operand getelementptr) with
449 // one-use here. As with the cast case above, it may be possible to relax the
450 // one-use constraint, but that needs be examined carefully since it may not
451 // reduce the total number of instructions.
452 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
453 !TI->isSameOperationAs(I: FI) ||
454 (!isa<BinaryOperator>(Val: TI) && !isa<GetElementPtrInst>(Val: TI)) ||
455 !TI->hasOneUse() || !FI->hasOneUse())
456 return nullptr;
457
458 // Figure out if the operations have any operands in common.
459 Value *MatchOp = getCommonOp(TI, FI, TI->isCommutative());
460 if (!MatchOp)
461 return nullptr;
462
463 // If the select condition is a vector, the operands of the original select's
464 // operands also must be vectors. This may not be the case for getelementptr
465 // for example.
466 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
467 !OtherOpF->getType()->isVectorTy()))
468 return nullptr;
469
470 // If we are sinking div/rem after a select, we may need to freeze the
471 // condition because div/rem may induce immediate UB with a poison operand.
472 // For example, the following transform is not safe if Cond can ever be poison
473 // because we can replace poison with zero and then we have div-by-zero that
474 // didn't exist in the original code:
475 // Cond ? x/y : x/z --> x / (Cond ? y : z)
476 auto *BO = dyn_cast<BinaryOperator>(Val: TI);
477 if (BO && BO->isIntDivRem() && !isGuaranteedNotToBePoison(V: Cond)) {
478 // A udiv/urem with a common divisor is safe because UB can only occur with
479 // div-by-zero, and that would be present in the original code.
480 if (BO->getOpcode() == Instruction::SDiv ||
481 BO->getOpcode() == Instruction::SRem || MatchIsOpZero)
482 Cond = Builder.CreateFreeze(V: Cond);
483 }
484
485 // If we reach here, they do have operations in common.
486 Value *NewSI = Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF,
487 Name: SI.getName() + ".v", MDFrom: &SI);
488 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
489 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
490 if (auto *BO = dyn_cast<BinaryOperator>(Val: TI)) {
491 BinaryOperator *NewBO = BinaryOperator::Create(Op: BO->getOpcode(), S1: Op0, S2: Op1);
492 NewBO->copyIRFlags(V: TI);
493 NewBO->andIRFlags(V: FI);
494 return NewBO;
495 }
496 if (auto *TGEP = dyn_cast<GetElementPtrInst>(Val: TI)) {
497 auto *FGEP = cast<GetElementPtrInst>(Val: FI);
498 Type *ElementType = TGEP->getSourceElementType();
499 return GetElementPtrInst::Create(
500 PointeeType: ElementType, Ptr: Op0, IdxList: Op1, NW: TGEP->getNoWrapFlags() & FGEP->getNoWrapFlags());
501 }
502 llvm_unreachable("Expected BinaryOperator or GEP");
503 return nullptr;
504}
505
506/// This transforms patterns of the form:
507/// select cond, intrinsic(x, ...), intrinsic(y, ...)
508/// into:
509/// intrinsic(select cond, x, y, ...)
510Instruction *InstCombinerImpl::foldSelectIntrinsic(SelectInst &SI) {
511 auto *LHSIntrinsic = dyn_cast<IntrinsicInst>(Val: SI.getTrueValue());
512 if (!LHSIntrinsic)
513 return nullptr;
514 auto *RHSIntrinsic = dyn_cast<IntrinsicInst>(Val: SI.getFalseValue());
515 if (!RHSIntrinsic ||
516 LHSIntrinsic->getIntrinsicID() != RHSIntrinsic->getIntrinsicID() ||
517 !LHSIntrinsic->hasOneUse() || !RHSIntrinsic->hasOneUse())
518 return nullptr;
519
520 const Intrinsic::ID IID = LHSIntrinsic->getIntrinsicID();
521 switch (IID) {
522 case Intrinsic::abs:
523 case Intrinsic::cttz:
524 case Intrinsic::ctlz: {
525 auto *TZ = cast<ConstantInt>(Val: LHSIntrinsic->getArgOperand(i: 1));
526 auto *FZ = cast<ConstantInt>(Val: RHSIntrinsic->getArgOperand(i: 1));
527
528 Value *TV = LHSIntrinsic->getArgOperand(i: 0);
529 Value *FV = RHSIntrinsic->getArgOperand(i: 0);
530
531 Value *NewSel = Builder.CreateSelect(C: SI.getCondition(), True: TV, False: FV, Name: "", MDFrom: &SI);
532 Value *NewPoisonFlag = Builder.CreateAnd(LHS: TZ, RHS: FZ);
533 Value *NewCall = Builder.CreateBinaryIntrinsic(ID: IID, LHS: NewSel, RHS: NewPoisonFlag);
534
535 return replaceInstUsesWith(I&: SI, V: NewCall);
536 }
537 case Intrinsic::ctpop: {
538 Value *TV = LHSIntrinsic->getArgOperand(i: 0);
539 Value *FV = RHSIntrinsic->getArgOperand(i: 0);
540
541 Value *NewSel = Builder.CreateSelect(C: SI.getCondition(), True: TV, False: FV, Name: "", MDFrom: &SI);
542 Value *NewCall = Builder.CreateUnaryIntrinsic(ID: IID, Op: NewSel);
543
544 return replaceInstUsesWith(I&: SI, V: NewCall);
545 }
546 default:
547 return nullptr;
548 }
549}
550
551static bool isSelect01(const APInt &C1I, const APInt &C2I) {
552 if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
553 return false;
554 return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
555}
556
557/// Try to fold the select into one of the operands to allow further
558/// optimization.
559Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
560 Value *FalseVal) {
561 // See the comment above getSelectFoldableOperands for a description of the
562 // transformation we are doing here.
563 auto TryFoldSelectIntoOp = [&](SelectInst &SI, Value *TrueVal,
564 Value *FalseVal,
565 bool Swapped) -> Instruction * {
566 auto *TVI = dyn_cast<BinaryOperator>(Val: TrueVal);
567 if (!TVI || !TVI->hasOneUse() || isa<Constant>(Val: FalseVal))
568 return nullptr;
569
570 unsigned SFO = getSelectFoldableOperands(I: TVI);
571 unsigned OpToFold = 0;
572 if ((SFO & 1) && FalseVal == TVI->getOperand(i_nocapture: 0))
573 OpToFold = 1;
574 else if ((SFO & 2) && FalseVal == TVI->getOperand(i_nocapture: 1))
575 OpToFold = 2;
576
577 if (!OpToFold)
578 return nullptr;
579
580 FastMathFlags FMF;
581 if (const auto *FPO = dyn_cast<FPMathOperator>(Val: &SI))
582 FMF = FPO->getFastMathFlags();
583 Constant *C = ConstantExpr::getBinOpIdentity(
584 Opcode: TVI->getOpcode(), Ty: TVI->getType(), AllowRHSConstant: true, NSZ: FMF.noSignedZeros());
585 Value *OOp = TVI->getOperand(i_nocapture: 2 - OpToFold);
586 // Avoid creating select between 2 constants unless it's selecting
587 // between 0, 1 and -1.
588 const APInt *OOpC;
589 bool OOpIsAPInt = match(V: OOp, P: m_APInt(Res&: OOpC));
590 if (isa<Constant>(Val: OOp) &&
591 (!OOpIsAPInt || !isSelect01(C1I: C->getUniqueInteger(), C2I: *OOpC)))
592 return nullptr;
593
594 // If the false value is a NaN then we have that the floating point math
595 // operation in the transformed code may not preserve the exact NaN
596 // bit-pattern -- e.g. `fadd sNaN, 0.0 -> qNaN`.
597 // This makes the transformation incorrect since the original program would
598 // have preserved the exact NaN bit-pattern.
599 // Avoid the folding if the false value might be a NaN.
600 if (isa<FPMathOperator>(Val: &SI) &&
601 !computeKnownFPClass(V: FalseVal, FMF, InterestedClasses: fcNan, SQ: SQ.getWithInstruction(I: &SI))
602 .isKnownNeverNaN())
603 return nullptr;
604
605 Value *NewSel = Builder.CreateSelect(C: SI.getCondition(), True: Swapped ? C : OOp,
606 False: Swapped ? OOp : C, Name: "", MDFrom: &SI);
607 if (isa<FPMathOperator>(Val: &SI)) {
608 FastMathFlags NewSelFMF = FMF;
609 // We cannot propagate ninf from the original select, because OOp may be
610 // inf and the flag only guarantees that FalseVal (op OOp) is never
611 // infinity.
612 // Examples: -inf + +inf = NaN, -inf - -inf = NaN, 0 * inf = NaN
613 // Specifically, if the original select has both ninf and nnan, we can
614 // safely propagate the flag.
615 // Note: This property holds for fadd, fsub, and fmul, but does not
616 // hold for fdiv (e.g. A / Inf == 0.0).
617 bool CanInferFiniteOperandsFromResult =
618 TVI->getOpcode() == Instruction::FAdd ||
619 TVI->getOpcode() == Instruction::FSub ||
620 TVI->getOpcode() == Instruction::FMul;
621 NewSelFMF.setNoInfs(TVI->hasNoInfs() ||
622 (CanInferFiniteOperandsFromResult &&
623 NewSelFMF.noInfs() && NewSelFMF.noNaNs()));
624 cast<Instruction>(Val: NewSel)->setFastMathFlags(NewSelFMF);
625 }
626 NewSel->takeName(V: TVI);
627 BinaryOperator *BO =
628 BinaryOperator::Create(Op: TVI->getOpcode(), S1: FalseVal, S2: NewSel);
629 BO->copyIRFlags(V: TVI);
630 if (isa<FPMathOperator>(Val: &SI)) {
631 // Merge poison generating flags from the select.
632 BO->setHasNoNaNs(BO->hasNoNaNs() && FMF.noNaNs());
633 BO->setHasNoInfs(BO->hasNoInfs() && FMF.noInfs());
634 // Merge no-signed-zeros flag from the select.
635 // Otherwise we may produce zeros with different sign.
636 BO->setHasNoSignedZeros(BO->hasNoSignedZeros() && FMF.noSignedZeros());
637 }
638 return BO;
639 };
640
641 if (Instruction *R = TryFoldSelectIntoOp(SI, TrueVal, FalseVal, false))
642 return R;
643
644 if (Instruction *R = TryFoldSelectIntoOp(SI, FalseVal, TrueVal, true))
645 return R;
646
647 return nullptr;
648}
649
650static Value *canoncalizeSelectICmpMinMax(const ICmpInst *Cmp, Value *TVal,
651 Value *FVal,
652 InstCombiner::BuilderTy &Builder,
653 const SimplifyQuery &SQ) {
654 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0);
655 Value *CmpRHS = Cmp->getOperand(i_nocapture: 1);
656 ICmpInst::Predicate Pred = Cmp->getPredicate();
657 if (match(V: FVal, P: m_Zero())) {
658 std::swap(a&: TVal, b&: FVal);
659 Pred = ICmpInst::getInversePredicate(pred: Pred);
660 }
661 if (!match(V: TVal, P: m_Zero()))
662 return nullptr;
663
664 if (Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE) {
665 std::swap(a&: CmpLHS, b&: CmpRHS);
666 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
667 }
668
669 // Handles:
670 // (X <= Y) ? 0 : (X - Y)
671 // (X <= Y) ? (Y - X) : 0
672 // (X >= Y) ? 0 : (Y - X)
673 // (X >= Y) ? (X - Y) : 0
674 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE) &&
675 match(V: FVal, P: m_NSWSub(L: m_Specific(V: CmpLHS), R: m_Specific(V: CmpRHS))) &&
676 isGuaranteedNotToBeUndef(V: CmpLHS, AC: SQ.AC, CtxI: SQ.CxtI, DT: SQ.DT)) {
677 Value *SMin =
678 Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: CmpRHS, RHS: CmpLHS);
679 return Builder.CreateNSWSub(LHS: CmpLHS, RHS: SMin);
680 }
681
682 return nullptr;
683}
684
685/// Try to fold a select to a min/max intrinsic. Many cases are already handled
686/// by matchDecomposedSelectPattern but here we handle the cases where more
687/// extensive modification of the IR is required.
688static Value *foldSelectICmpMinMax(const ICmpInst *Cmp, Value *TVal,
689 Value *FVal,
690 InstCombiner::BuilderTy &Builder,
691 const SimplifyQuery &SQ) {
692 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0);
693 Value *CmpRHS = Cmp->getOperand(i_nocapture: 1);
694 ICmpInst::Predicate Pred = Cmp->getPredicate();
695
696 if (Value *V = canoncalizeSelectICmpMinMax(Cmp, TVal, FVal, Builder, SQ))
697 return V;
698
699 // (X > Y) ? X : (Y - 1) ==> MIN(X, Y - 1)
700 // (X < Y) ? X : (Y + 1) ==> MAX(X, Y + 1)
701 // This transformation is valid when overflow corresponding to the sign of
702 // the comparison is poison and we must drop the non-matching overflow flag.
703 if (CmpRHS == TVal) {
704 std::swap(a&: CmpLHS, b&: CmpRHS);
705 Pred = CmpInst::getSwappedPredicate(pred: Pred);
706 }
707
708 // TODO: consider handling 'or disjoint' as well, though these would need to
709 // be converted to 'add' instructions.
710 if (!(CmpLHS == TVal && isa<Instruction>(Val: FVal)))
711 return nullptr;
712
713 if (Pred == CmpInst::ICMP_SGT &&
714 match(V: FVal, P: m_NSWAdd(L: m_Specific(V: CmpRHS), R: m_One()))) {
715 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
716 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smax, LHS: TVal, RHS: FVal);
717 }
718
719 if (Pred == CmpInst::ICMP_SLT &&
720 match(V: FVal, P: m_NSWAdd(L: m_Specific(V: CmpRHS), R: m_AllOnes()))) {
721 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
722 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: TVal, RHS: FVal);
723 }
724
725 if (Pred == CmpInst::ICMP_UGT &&
726 match(V: FVal, P: m_NUWAdd(L: m_Specific(V: CmpRHS), R: m_One()))) {
727 cast<Instruction>(Val: FVal)->setHasNoSignedWrap(false);
728 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: TVal, RHS: FVal);
729 }
730
731 // Note: We must use isKnownNonZero here because "sub nuw %x, 1" will be
732 // canonicalized to "add %x, -1" discarding the nuw flag.
733 if (Pred == CmpInst::ICMP_ULT &&
734 match(V: FVal, P: m_Add(L: m_Specific(V: CmpRHS), R: m_AllOnes())) &&
735 isKnownNonZero(V: CmpRHS, Q: SQ)) {
736 cast<Instruction>(Val: FVal)->setHasNoSignedWrap(false);
737 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
738 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: TVal, RHS: FVal);
739 }
740
741 return nullptr;
742}
743
744/// We want to turn:
745/// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
746/// into:
747/// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
748/// Note:
749/// Z may be 0 if lshr is missing.
750/// Worst-case scenario is that we will replace 5 instructions with 5 different
751/// instructions, but we got rid of select.
752static Instruction *foldSelectICmpAndAnd(Type *SelType, const Value *Cond,
753 Value *TVal, Value *FVal,
754 InstCombiner::BuilderTy &Builder) {
755 Value *A, *X, *Y, *Z;
756 CmpPredicate Pred;
757 unsigned NumReplaced = 1 + Cond->hasOneUse();
758 if (match(V: Cond, P: m_Trunc(Op: m_Value(V&: X)))) {
759 Y = ConstantInt::get(Ty: X->getType(), V: 1);
760 Pred = ICmpInst::ICMP_NE;
761 } else if (match(V: Cond,
762 P: m_ICmp(Pred, L: m_And(L: m_Value(V&: X), R: m_Value(V&: Y)), R: m_Zero())) &&
763 ICmpInst::isEquality(P: Pred)) {
764 NumReplaced +=
765 Cond->hasOneUse() && cast<ICmpInst>(Val: Cond)->getOperand(i_nocapture: 0)->hasOneUse();
766 } else
767 return nullptr;
768
769 if (Pred == ICmpInst::ICMP_NE)
770 std::swap(a&: TVal, b&: FVal);
771
772 if (!match(V: FVal, P: m_One()))
773 return nullptr;
774
775 // The TrueVal has general form of: and %B, 1
776 if (!match(V: TVal, P: m_And(L: m_Value(V&: A), R: m_One())))
777 return nullptr;
778
779 APInt BitWidth(SelType->getScalarSizeInBits(),
780 SelType->getScalarSizeInBits());
781 auto TValPattern = m_CombineOr(
782 Ps: m_Deferred(V: X),
783 Ps: m_LShr(L: m_Deferred(V: X), R: m_Value(V&: Z, P: m_SpecificInt_ICMP_ForbidPoison(
784 Predicate: CmpInst::ICMP_ULT, Threshold: BitWidth))));
785
786 if (!match(V: A, P: TValPattern)) {
787 std::swap(a&: X, b&: Y);
788 if (!match(V: A, P: TValPattern))
789 return nullptr;
790 }
791
792 bool HasShift = A != X;
793 if (TVal->hasOneUse())
794 NumReplaced += 1 + (HasShift && A->hasOneUse());
795
796 if (NumReplaced < (4u - isa<Constant>(Val: Y)))
797 return nullptr;
798
799 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
800 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
801 Constant *One = ConstantInt::get(Ty: SelType, V: 1);
802 Value *MaskB = HasShift ? Builder.CreateShl(LHS: One, RHS: Z) : One;
803 Value *FullMask = Builder.CreateOr(LHS: Y, RHS: MaskB);
804 Value *MaskedX = Builder.CreateAnd(LHS: X, RHS: FullMask);
805 Value *ICmpNeZero = Builder.CreateIsNotNull(Arg: MaskedX);
806 return new ZExtInst(ICmpNeZero, SelType);
807}
808
809/// We want to turn:
810/// (select (icmp eq (and X, C1), 0), 0, (shl [nsw/nuw] X, C2));
811/// iff C1 is a mask and the number of its leading zeros is equal to C2
812/// into:
813/// shl X, C2
814static Value *foldSelectICmpAndZeroShl(const ICmpInst *Cmp, Value *TVal,
815 Value *FVal,
816 InstCombiner::BuilderTy &Builder) {
817 CmpPredicate Pred;
818 Value *AndVal;
819 if (!match(V: Cmp, P: m_ICmp(Pred, L: m_Value(V&: AndVal), R: m_Zero())))
820 return nullptr;
821
822 if (Pred == ICmpInst::ICMP_NE) {
823 Pred = ICmpInst::ICMP_EQ;
824 std::swap(a&: TVal, b&: FVal);
825 }
826
827 Value *X;
828 const APInt *C2, *C1;
829 if (Pred != ICmpInst::ICMP_EQ ||
830 !match(V: AndVal, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C1))) ||
831 !match(V: TVal, P: m_Zero()) || !match(V: FVal, P: m_Shl(L: m_Specific(V: X), R: m_APInt(Res&: C2))))
832 return nullptr;
833
834 if (!C1->isMask() ||
835 C1->countLeadingZeros() != static_cast<unsigned>(C2->getZExtValue()))
836 return nullptr;
837
838 auto *FI = dyn_cast<Instruction>(Val: FVal);
839 if (!FI)
840 return nullptr;
841
842 FI->setHasNoSignedWrap(false);
843 FI->setHasNoUnsignedWrap(false);
844 return FVal;
845}
846
847/// We want to turn:
848/// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
849/// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
850/// into:
851/// ashr (X, Y)
852static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
853 Value *FalseVal,
854 InstCombiner::BuilderTy &Builder) {
855 ICmpInst::Predicate Pred = IC->getPredicate();
856 Value *CmpLHS = IC->getOperand(i_nocapture: 0);
857 Value *CmpRHS = IC->getOperand(i_nocapture: 1);
858 if (!CmpRHS->getType()->isIntOrIntVectorTy())
859 return nullptr;
860
861 Value *X, *Y;
862 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
863 if ((Pred != ICmpInst::ICMP_SGT ||
864 !match(V: CmpRHS, P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_SGE,
865 Threshold: APInt::getAllOnes(numBits: Bitwidth)))) &&
866 (Pred != ICmpInst::ICMP_SLT ||
867 !match(V: CmpRHS, P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_SGE,
868 Threshold: APInt::getZero(numBits: Bitwidth)))))
869 return nullptr;
870
871 // Canonicalize so that ashr is in FalseVal.
872 if (Pred == ICmpInst::ICMP_SLT)
873 std::swap(a&: TrueVal, b&: FalseVal);
874
875 if (match(V: TrueVal, P: m_LShr(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
876 match(V: FalseVal, P: m_AShr(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
877 match(V: CmpLHS, P: m_Specific(V: X))) {
878 const auto *Ashr = cast<Instruction>(Val: FalseVal);
879 // if lshr is not exact and ashr is, this new ashr must not be exact.
880 bool IsExact = Ashr->isExact() && cast<Instruction>(Val: TrueVal)->isExact();
881 return Builder.CreateAShr(LHS: X, RHS: Y, Name: IC->getName(), isExact: IsExact);
882 }
883
884 return nullptr;
885}
886
887/// We want to turn:
888/// (select (icmp eq (and X, C1), 0), Y, (BinOp Y, C2))
889/// into:
890/// IF C2 u>= C1
891/// (BinOp Y, (shl (and X, C1), C3))
892/// ELSE
893/// (BinOp Y, (lshr (and X, C1), C3))
894/// iff:
895/// 0 on the RHS is the identity value (i.e add, xor, shl, etc...)
896/// C1 and C2 are both powers of 2
897/// where:
898/// IF C2 u>= C1
899/// C3 = Log(C2) - Log(C1)
900/// ELSE
901/// C3 = Log(C1) - Log(C2)
902///
903/// This transform handles cases where:
904/// 1. The icmp predicate is inverted
905/// 2. The select operands are reversed
906/// 3. The magnitude of C2 and C1 are flipped
907static Value *foldSelectICmpAndBinOp(Value *CondVal, Value *TrueVal,
908 Value *FalseVal, Value *V,
909 const APInt &AndMask, bool CreateAnd,
910 InstCombiner::BuilderTy &Builder) {
911 // Only handle integer compares.
912 if (!TrueVal->getType()->isIntOrIntVectorTy())
913 return nullptr;
914
915 unsigned C1Log = AndMask.logBase2();
916 Value *Y;
917 BinaryOperator *BinOp;
918 const APInt *C2;
919 bool NeedXor;
920 if (match(V: FalseVal, P: m_BinOp(L: m_Specific(V: TrueVal), R: m_Power2(V&: C2)))) {
921 Y = TrueVal;
922 BinOp = cast<BinaryOperator>(Val: FalseVal);
923 NeedXor = false;
924 } else if (match(V: TrueVal, P: m_BinOp(L: m_Specific(V: FalseVal), R: m_Power2(V&: C2)))) {
925 Y = FalseVal;
926 BinOp = cast<BinaryOperator>(Val: TrueVal);
927 NeedXor = true;
928 } else {
929 return nullptr;
930 }
931
932 // Check that 0 on RHS is identity value for this binop.
933 auto *IdentityC =
934 ConstantExpr::getBinOpIdentity(Opcode: BinOp->getOpcode(), Ty: BinOp->getType(),
935 /*AllowRHSConstant*/ true);
936 if (IdentityC == nullptr || !IdentityC->isNullValue())
937 return nullptr;
938
939 unsigned C2Log = C2->logBase2();
940
941 bool NeedShift = C1Log != C2Log;
942 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
943 V->getType()->getScalarSizeInBits();
944
945 // the demanded bits for the created shl make the and redundant
946 if (AndMask.isOne() && C2->isSignBitSet())
947 CreateAnd = false;
948
949 // Make sure we don't create more instructions than we save.
950 if ((NeedShift + NeedXor + NeedZExtTrunc + CreateAnd) >
951 (CondVal->hasOneUse() + BinOp->hasOneUse()))
952 return nullptr;
953
954 if (CreateAnd) {
955 // Insert the AND instruction on the input to the truncate.
956 V = Builder.CreateAnd(LHS: V, RHS: ConstantInt::get(Ty: V->getType(), V: AndMask));
957 }
958
959 if (C2Log > C1Log) {
960 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
961 V = Builder.CreateShl(LHS: V, RHS: C2Log - C1Log);
962 } else if (C1Log > C2Log) {
963 V = Builder.CreateLShr(LHS: V, RHS: C1Log - C2Log);
964 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
965 } else
966 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
967
968 if (NeedXor)
969 V = Builder.CreateXor(LHS: V, RHS: *C2);
970
971 auto *Res = Builder.CreateBinOp(Opc: BinOp->getOpcode(), LHS: Y, RHS: V);
972 if (auto *BO = dyn_cast<BinaryOperator>(Val: Res))
973 BO->copyIRFlags(V: BinOp);
974 return Res;
975}
976
977/// Canonicalize a set or clear of a masked set of constant bits to
978/// select-of-constants form.
979static Instruction *foldSetClearBits(SelectInst &Sel,
980 InstCombiner::BuilderTy &Builder) {
981 Value *Cond = Sel.getCondition();
982 Value *T = Sel.getTrueValue();
983 Value *F = Sel.getFalseValue();
984 Type *Ty = Sel.getType();
985 Value *X;
986 const APInt *NotC, *C;
987
988 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
989 if (match(V: T, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: NotC))) &&
990 match(V: F, P: m_OneUse(SubPattern: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C)))) && *NotC == ~(*C)) {
991 Constant *Zero = ConstantInt::getNullValue(Ty);
992 Constant *OrC = ConstantInt::get(Ty, V: *C);
993 Value *NewSel = Builder.CreateSelect(C: Cond, True: Zero, False: OrC, Name: "masksel", MDFrom: &Sel);
994 return BinaryOperator::CreateOr(V1: T, V2: NewSel);
995 }
996
997 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
998 if (match(V: F, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: NotC))) &&
999 match(V: T, P: m_OneUse(SubPattern: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C)))) && *NotC == ~(*C)) {
1000 Constant *Zero = ConstantInt::getNullValue(Ty);
1001 Constant *OrC = ConstantInt::get(Ty, V: *C);
1002 Value *NewSel = Builder.CreateSelect(C: Cond, True: OrC, False: Zero, Name: "masksel", MDFrom: &Sel);
1003 return BinaryOperator::CreateOr(V1: F, V2: NewSel);
1004 }
1005
1006 return nullptr;
1007}
1008
1009// select (x == 0), 0, x * y --> freeze(y) * x
1010// select (y == 0), 0, x * y --> freeze(x) * y
1011// select (x == 0), undef, x * y --> freeze(y) * x
1012// select (x == undef), 0, x * y --> freeze(y) * x
1013// Usage of mul instead of 0 will make the result more poisonous,
1014// so the operand that was not checked in the condition should be frozen.
1015// The latter folding is applied only when a constant compared with x is
1016// is a vector consisting of 0 and undefs. If a constant compared with x
1017// is a scalar undefined value or undefined vector then an expression
1018// should be already folded into a constant.
1019//
1020// This also holds all operations such that Op(0) == 0
1021// e.g. Shl, Umin, etc
1022static Instruction *foldSelectZeroOrFixedOp(SelectInst &SI,
1023 InstCombinerImpl &IC) {
1024 auto *CondVal = SI.getCondition();
1025 auto *TrueVal = SI.getTrueValue();
1026 auto *FalseVal = SI.getFalseValue();
1027 Value *X, *Y;
1028 CmpPredicate Predicate;
1029
1030 // Assuming that constant compared with zero is not undef (but it may be
1031 // a vector with some undef elements). Otherwise (when a constant is undef)
1032 // the select expression should be already simplified.
1033 if (!match(V: CondVal, P: m_ICmp(Pred&: Predicate, L: m_Value(V&: X), R: m_Zero())) ||
1034 !ICmpInst::isEquality(P: Predicate))
1035 return nullptr;
1036
1037 if (Predicate == ICmpInst::ICMP_NE)
1038 std::swap(a&: TrueVal, b&: FalseVal);
1039
1040 // Check that TrueVal is a constant instead of matching it with m_Zero()
1041 // to handle the case when it is a scalar undef value or a vector containing
1042 // non-zero elements that are masked by undef elements in the compare
1043 // constant.
1044 auto *TrueValC = dyn_cast<Constant>(Val: TrueVal);
1045 if (TrueValC == nullptr || !isa<Instruction>(Val: FalseVal))
1046 return nullptr;
1047
1048 bool FreezeY;
1049 if (match(V: FalseVal, P: m_c_Mul(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1050 match(V: FalseVal, P: m_c_And(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1051 match(V: FalseVal, P: m_FShl(Op0: m_Specific(V: X), Op1: m_Specific(V: X), Op2: m_Value(V&: Y))) ||
1052 match(V: FalseVal, P: m_FShr(Op0: m_Specific(V: X), Op1: m_Specific(V: X), Op2: m_Value(V&: Y))) ||
1053 match(V: FalseVal,
1054 P: m_c_Intrinsic<Intrinsic::umin>(Op0: m_Specific(V: X), Op1: m_Value(V&: Y)))) {
1055 FreezeY = true;
1056 } else if (match(V: FalseVal, P: m_IDiv(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1057 match(V: FalseVal, P: m_IRem(L: m_Specific(V: X), R: m_Value(V&: Y)))) {
1058 FreezeY = false;
1059 } else {
1060 return nullptr;
1061 }
1062
1063 auto *ZeroC = cast<Constant>(Val: cast<Instruction>(Val: CondVal)->getOperand(i: 1));
1064 auto *MergedC = Constant::mergeUndefsWith(C: TrueValC, Other: ZeroC);
1065 // If X is compared with 0 then TrueVal could be either zero or undef.
1066 // m_Zero match vectors containing some undef elements, but for scalars
1067 // m_Undef should be used explicitly.
1068 if (!match(V: MergedC, P: m_Zero()) && !match(V: MergedC, P: m_Undef()))
1069 return nullptr;
1070
1071 auto *FalseValI = cast<Instruction>(Val: FalseVal);
1072 if (FreezeY) {
1073 auto *FrY = IC.InsertNewInstBefore(New: new FreezeInst(Y, Y->getName() + ".fr"),
1074 Old: FalseValI->getIterator());
1075 IC.replaceOperand(I&: *FalseValI,
1076 OpNum: FalseValI->getOperand(i: 0) == Y
1077 ? 0
1078 : (FalseValI->getOperand(i: 1) == Y ? 1 : 2),
1079 V: FrY);
1080 }
1081 return IC.replaceInstUsesWith(I&: SI, V: FalseValI);
1082}
1083
1084/// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
1085/// There are 8 commuted/swapped variants of this pattern.
1086static Value *
1087canonicalizeSaturatedSubtractUnsigned(const ICmpInst *ICI, const Value *TrueVal,
1088 const Value *FalseVal,
1089 InstCombiner::BuilderTy &Builder) {
1090 ICmpInst::Predicate Pred = ICI->getPredicate();
1091 Value *A = ICI->getOperand(i_nocapture: 0);
1092 Value *B = ICI->getOperand(i_nocapture: 1);
1093
1094 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
1095 // (a == 0) ? 0 : a - 1 -> (a != 0) ? a - 1 : 0
1096 if (match(V: TrueVal, P: m_Zero())) {
1097 Pred = ICmpInst::getInversePredicate(pred: Pred);
1098 std::swap(a&: TrueVal, b&: FalseVal);
1099 }
1100
1101 if (!match(V: FalseVal, P: m_Zero()))
1102 return nullptr;
1103
1104 // ugt 0 is canonicalized to ne 0 and requires special handling
1105 // (a != 0) ? a + -1 : 0 -> usub.sat(a, 1)
1106 if (Pred == ICmpInst::ICMP_NE) {
1107 if (match(V: B, P: m_Zero()) && match(V: TrueVal, P: m_Add(L: m_Specific(V: A), R: m_AllOnes())))
1108 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A,
1109 RHS: ConstantInt::get(Ty: A->getType(), V: 1));
1110 return nullptr;
1111 }
1112
1113 if (!ICmpInst::isUnsigned(Pred))
1114 return nullptr;
1115
1116 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
1117 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
1118 std::swap(a&: A, b&: B);
1119 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
1120 }
1121
1122 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
1123 "Unexpected isUnsigned predicate!");
1124
1125 // Ensure the sub is of the form:
1126 // (a > b) ? a - b : 0 -> usub.sat(a, b)
1127 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
1128 // Checking for both a-b and a+(-b) as a constant.
1129 bool IsNegative = false;
1130 const APInt *C;
1131 if (match(V: TrueVal, P: m_Sub(L: m_Specific(V: B), R: m_Specific(V: A))) ||
1132 (match(V: A, P: m_APInt(Res&: C)) &&
1133 match(V: TrueVal, P: m_Add(L: m_Specific(V: B), R: m_SpecificInt(V: -*C)))))
1134 IsNegative = true;
1135 else if (!match(V: TrueVal, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1136 !(match(V: B, P: m_APInt(Res&: C)) &&
1137 match(V: TrueVal, P: m_Add(L: m_Specific(V: A), R: m_SpecificInt(V: -*C)))))
1138 return nullptr;
1139
1140 // If we are adding a negate and the sub and icmp are used anywhere else, we
1141 // would end up with more instructions.
1142 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
1143 return nullptr;
1144
1145 // (a > b) ? a - b : 0 -> usub.sat(a, b)
1146 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
1147 Value *Result = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A, RHS: B);
1148 if (IsNegative)
1149 Result = Builder.CreateNeg(V: Result);
1150 return Result;
1151}
1152
1153static Value *
1154canonicalizeSaturatedSubtractSigned(const ICmpInst *ICI, const Value *TrueVal,
1155 const Value *FalseVal,
1156 InstCombiner::BuilderTy &Builder) {
1157 ICmpInst::Predicate Pred = ICI->getPredicate();
1158 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
1159 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
1160
1161 // `A != B ? X : Y` --> `A == B ? Y : X`
1162 // This canonicalization allows us to handle more patterns with fewer checks.
1163 if (Pred == ICmpInst::ICMP_NE) {
1164 Pred = ICmpInst::ICMP_EQ;
1165 std::swap(a&: TrueVal, b&: FalseVal);
1166 }
1167
1168 // `A == MIN_INT ? MAX_INT : 0 - A` --> `ssub_sat 0, A`
1169 if (Pred == ICmpInst::ICMP_EQ && match(V: CmpRHS, P: m_SignMask()) &&
1170 match(V: TrueVal, P: m_MaxSignedValue()) &&
1171 match(V: FalseVal, P: m_Neg(V: m_Specific(V: CmpLHS)))) {
1172 return Builder.CreateBinaryIntrinsic(
1173 ID: Intrinsic::ssub_sat, LHS: ConstantInt::getNullValue(Ty: CmpLHS->getType()),
1174 RHS: CmpLHS);
1175 }
1176
1177 return nullptr;
1178}
1179
1180static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
1181 const Value *TrueVal,
1182 const Value *FalseVal,
1183 InstCombiner::BuilderTy &Builder) {
1184 if (Value *V = canonicalizeSaturatedSubtractUnsigned(ICI, TrueVal, FalseVal,
1185 Builder))
1186 return V;
1187
1188 if (Value *V =
1189 canonicalizeSaturatedSubtractSigned(ICI, TrueVal, FalseVal, Builder))
1190 return V;
1191
1192 return nullptr;
1193}
1194
1195static Value *
1196canonicalizeSaturatedAddUnsigned(ICmpInst *Cmp, Value *TVal, Value *FVal,
1197 InstCombiner::BuilderTy &Builder) {
1198
1199 // Match unsigned saturated add with constant.
1200 Value *Cmp0 = Cmp->getOperand(i_nocapture: 0);
1201 Value *Cmp1 = Cmp->getOperand(i_nocapture: 1);
1202 ICmpInst::Predicate Pred = Cmp->getPredicate();
1203 Value *X;
1204 const APInt *C;
1205
1206 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
1207 // There are 8 commuted variants.
1208 // Canonicalize -1 (saturated result) to true value of the select.
1209 if (match(V: FVal, P: m_AllOnes())) {
1210 std::swap(a&: TVal, b&: FVal);
1211 Pred = CmpInst::getInversePredicate(pred: Pred);
1212 }
1213 if (!match(V: TVal, P: m_AllOnes()))
1214 return nullptr;
1215
1216 // uge -1 is canonicalized to eq -1 and requires special handling
1217 // (a == -1) ? -1 : a + 1 -> uadd.sat(a, 1)
1218 if (Pred == ICmpInst::ICMP_EQ) {
1219 if (match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_One())) &&
1220 match(V: Cmp1, P: m_AllOnes())) {
1221 return Builder.CreateBinaryIntrinsic(
1222 ID: Intrinsic::uadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: 1));
1223 }
1224 return nullptr;
1225 }
1226
1227 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
1228 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1229 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: ~*C))) {
1230 // (X u> ~C) ? -1 : (X + C) --> uadd.sat(X, C)
1231 // (X u>= ~C)? -1 : (X + C) --> uadd.sat(X, C)
1232 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1233 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1234 }
1235
1236 // Negative one does not work here because X u> -1 ? -1, X + -1 is not a
1237 // saturated add.
1238 if (Pred == ICmpInst::ICMP_UGT &&
1239 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1240 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: ~*C - 1)) && !C->isAllOnes()) {
1241 // (X u> ~C - 1) ? -1 : (X + C) --> uadd.sat(X, C)
1242 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1243 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1244 }
1245
1246 // Zero does not work here because X u>= 0 ? -1 : X -> is always -1, which is
1247 // not a saturated add.
1248 if (Pred == ICmpInst::ICMP_UGE &&
1249 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1250 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: -*C)) && !C->isZero()) {
1251 // (X u >= -C) ? -1 : (X + C) --> uadd.sat(X, C)
1252 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1253 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1254 }
1255
1256 // Canonicalize predicate to less-than or less-or-equal-than.
1257 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
1258 std::swap(a&: Cmp0, b&: Cmp1);
1259 Pred = CmpInst::getSwappedPredicate(pred: Pred);
1260 }
1261 if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
1262 return nullptr;
1263
1264 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
1265 // Strictness of the comparison is irrelevant.
1266 Value *Y;
1267 if (match(V: Cmp0, P: m_Not(V: m_Value(V&: X))) &&
1268 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Value(V&: Y))) && Y == Cmp1) {
1269 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1270 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
1271 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: X, RHS: Y);
1272 }
1273 // The 'not' op may be included in the sum but not the compare.
1274 // Strictness of the comparison is irrelevant.
1275 X = Cmp0;
1276 Y = Cmp1;
1277 if (match(V: FVal, P: m_c_Add(L: m_NotForbidPoison(V: m_Specific(V: X)), R: m_Specific(V: Y)))) {
1278 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
1279 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
1280 BinaryOperator *BO = cast<BinaryOperator>(Val: FVal);
1281 return Builder.CreateBinaryIntrinsic(
1282 ID: Intrinsic::uadd_sat, LHS: BO->getOperand(i_nocapture: 0), RHS: BO->getOperand(i_nocapture: 1));
1283 }
1284 // The overflow may be detected via the add wrapping round.
1285 // This is only valid for strict comparison!
1286 if (Pred == ICmpInst::ICMP_ULT &&
1287 match(V: Cmp0, P: m_c_Add(L: m_Specific(V: Cmp1), R: m_Value(V&: Y))) &&
1288 match(V: FVal, P: m_c_Add(L: m_Specific(V: Cmp1), R: m_Specific(V: Y)))) {
1289 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
1290 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1291 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp1, RHS: Y);
1292 }
1293
1294 return nullptr;
1295}
1296
1297static Value *canonicalizeSaturatedAddSigned(ICmpInst *Cmp, Value *TVal,
1298 Value *FVal,
1299 InstCombiner::BuilderTy &Builder) {
1300 // Match saturated add with constant.
1301 Value *Cmp0 = Cmp->getOperand(i_nocapture: 0);
1302 Value *Cmp1 = Cmp->getOperand(i_nocapture: 1);
1303 ICmpInst::Predicate Pred = Cmp->getPredicate();
1304
1305 // Canonicalize TVal to be the saturation constant.
1306 if (match(V: FVal, P: m_MaxSignedValue()) || match(V: FVal, P: m_SignMask())) {
1307 std::swap(a&: TVal, b&: FVal);
1308 Pred = CmpInst::getInversePredicate(pred: Pred);
1309 }
1310
1311 const APInt *SatC;
1312 if (!match(V: TVal, P: m_APInt(Res&: SatC)) ||
1313 !(SatC->isMaxSignedValue() || SatC->isSignMask()))
1314 return nullptr;
1315
1316 bool IsMax = SatC->isMaxSignedValue();
1317
1318 // sge maximum signed value is canonicalized to eq maximum signed value and
1319 // requires special handling. sle minimum signed value is similarly
1320 // canonicalized to eq minimum signed value.
1321 if (Pred == ICmpInst::ICMP_EQ && Cmp1 == TVal) {
1322 // (a == INT_MAX) ? INT_MAX : a + 1 -> sadd.sat(a, 1)
1323 if (IsMax && match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_One()))) {
1324 return Builder.CreateBinaryIntrinsic(
1325 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: 1));
1326 }
1327
1328 // (a == INT_MIN) ? INT_MIN : a + -1 -> sadd.sat(a, -1)
1329 if (!IsMax && match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_AllOnes()))) {
1330 return Builder.CreateBinaryIntrinsic(
1331 ID: Intrinsic::sadd_sat, LHS: Cmp0,
1332 RHS: ConstantInt::getAllOnesValue(Ty: Cmp0->getType()));
1333 }
1334 return nullptr;
1335 }
1336
1337 const APInt *C;
1338
1339 // (X > Y) ? INT_MAX : (X + C) --> sadd.sat(X, C)
1340 // (X >= Y) ? INT_MAX : (X + C) --> sadd.sat(X, C)
1341 // where C > 0 and Y is INT_MAX - C or INT_MAX - C - 1
1342 if (IsMax && (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) &&
1343 isa<Constant>(Val: Cmp1) &&
1344 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_StrictlyPositive(V&: C)))) {
1345 // Normalize SGE to SGT for threshold comparison.
1346 if (Pred == ICmpInst::ICMP_SGE) {
1347 if (auto Flipped = getFlippedStrictnessPredicateAndConstant(
1348 Pred, C: cast<Constant>(Val: Cmp1))) {
1349 Pred = Flipped->first;
1350 Cmp1 = Flipped->second;
1351 }
1352 }
1353 // Check: X > INT_MAX - C or X > INT_MAX - C - 1
1354 APInt Threshold = *SatC - *C;
1355 if (Pred == ICmpInst::ICMP_SGT &&
1356 (match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold)) ||
1357 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold - 1))))
1358 return Builder.CreateBinaryIntrinsic(
1359 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1360 }
1361
1362 // (X < Y) ? INT_MIN : (X + C) --> sadd.sat(X, C)
1363 // (X <= Y) ? INT_MIN : (X + C) --> sadd.sat(X, C)
1364 // where C < 0 and Y is INT_MIN - C or INT_MIN - C + 1
1365 if (!IsMax && (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) &&
1366 isa<Constant>(Val: Cmp1) &&
1367 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_Negative(V&: C)))) {
1368 // Normalize SLE to SLT for threshold comparison.
1369 if (Pred == ICmpInst::ICMP_SLE) {
1370 if (auto Flipped = getFlippedStrictnessPredicateAndConstant(
1371 Pred, C: cast<Constant>(Val: Cmp1))) {
1372 Pred = Flipped->first;
1373 Cmp1 = Flipped->second;
1374 }
1375 }
1376 // Check: X < INT_MIN - C or X < INT_MIN - C + 1
1377 // INT_MIN - C for negative C is like INT_MIN + |C|
1378 APInt Threshold = *SatC - *C;
1379 if (Pred == ICmpInst::ICMP_SLT &&
1380 (match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold)) ||
1381 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold + 1))))
1382 return Builder.CreateBinaryIntrinsic(
1383 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1384 }
1385
1386 // Canonicalize predicate to less-than or less-or-equal-than.
1387 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
1388 std::swap(a&: Cmp0, b&: Cmp1);
1389 Pred = CmpInst::getSwappedPredicate(pred: Pred);
1390 }
1391
1392 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SLE)
1393 return nullptr;
1394
1395 Value *X;
1396
1397 // (INT_MAX - X s< Y) ? INT_MAX : (X + Y) --> sadd.sat(X, Y)
1398 // (INT_MAX - X s< Y) ? INT_MAX : (Y + X) --> sadd.sat(X, Y)
1399 if (IsMax && match(V: Cmp0, P: m_NSWSub(L: m_SpecificInt(V: *SatC), R: m_Value(V&: X))) &&
1400 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Cmp1)))) {
1401 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: X, RHS: Cmp1);
1402 }
1403
1404 // (INT_MIN - X s> Y) ? INT_MIN : (X + Y) --> sadd.sat(X, Y)
1405 // (INT_MIN - X s> Y) ? INT_MIN : (Y + X) --> sadd.sat(X, Y)
1406 // After swapping operands from the SGT/SGE canonicalization above,
1407 // this becomes (Y s< INT_MIN - X).
1408 if (!IsMax && match(V: Cmp1, P: m_NSWSub(L: m_SpecificInt(V: *SatC), R: m_Value(V&: X))) &&
1409 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Cmp0)))) {
1410 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: X, RHS: Cmp0);
1411 }
1412
1413 return nullptr;
1414}
1415
1416static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
1417 InstCombiner::BuilderTy &Builder) {
1418 if (!Cmp->hasOneUse())
1419 return nullptr;
1420
1421 if (Value *V = canonicalizeSaturatedAddUnsigned(Cmp, TVal, FVal, Builder))
1422 return V;
1423
1424 if (Value *V = canonicalizeSaturatedAddSigned(Cmp, TVal, FVal, Builder))
1425 return V;
1426
1427 return nullptr;
1428}
1429
1430/// Try to match patterns with select and subtract as absolute difference.
1431static Value *foldAbsDiff(ICmpInst *Cmp, Value *TVal, Value *FVal,
1432 InstCombiner::BuilderTy &Builder) {
1433 auto *TI = dyn_cast<Instruction>(Val: TVal);
1434 auto *FI = dyn_cast<Instruction>(Val: FVal);
1435 if (!TI || !FI)
1436 return nullptr;
1437
1438 // Normalize predicate to gt/lt rather than ge/le.
1439 ICmpInst::Predicate Pred = Cmp->getStrictPredicate();
1440 Value *A = Cmp->getOperand(i_nocapture: 0);
1441 Value *B = Cmp->getOperand(i_nocapture: 1);
1442
1443 // Normalize "A - B" as the true value of the select.
1444 if (match(V: FI, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1445 std::swap(a&: FI, b&: TI);
1446 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
1447 }
1448
1449 // With any pair of no-wrap subtracts:
1450 // (A > B) ? (A - B) : (B - A) --> abs(A - B)
1451 if (Pred == CmpInst::ICMP_SGT &&
1452 match(V: TI, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1453 match(V: FI, P: m_Sub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1454 (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap()) &&
1455 (FI->hasNoSignedWrap() || FI->hasNoUnsignedWrap())) {
1456 // The remaining subtract is not "nuw" any more.
1457 // If there's one use of the subtract (no other use than the use we are
1458 // about to replace), then we know that the sub is "nsw" in this context
1459 // even if it was only "nuw" before. If there's another use, then we can't
1460 // add "nsw" to the existing instruction because it may not be safe in the
1461 // other user's context.
1462 TI->setHasNoUnsignedWrap(false);
1463 if (!TI->hasNoSignedWrap())
1464 TI->setHasNoSignedWrap(TI->hasOneUse());
1465 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI, RHS: Builder.getTrue());
1466 }
1467
1468 // Match: (A > B) ? (A - B) : (0 - (A - B)) --> abs(A - B)
1469 if (Pred == CmpInst::ICMP_SGT &&
1470 match(V: TI, P: m_NSWSub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1471 match(V: FI, P: m_Neg(V: m_Specific(V: TI)))) {
1472 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI,
1473 RHS: Builder.getFalse());
1474 }
1475
1476 // Match: (A < B) ? (0 - (A - B)) : (A - B) --> abs(A - B)
1477 if (Pred == CmpInst::ICMP_SLT &&
1478 match(V: FI, P: m_NSWSub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1479 match(V: TI, P: m_Neg(V: m_Specific(V: FI)))) {
1480 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: FI,
1481 RHS: Builder.getFalse());
1482 }
1483
1484 // Match: (A > B) ? (0 - (B - A)) : (B - A) --> abs(B - A)
1485 if (Pred == CmpInst::ICMP_SGT &&
1486 match(V: FI, P: m_NSWSub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1487 match(V: TI, P: m_Neg(V: m_Specific(V: FI)))) {
1488 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: FI,
1489 RHS: Builder.getFalse());
1490 }
1491
1492 // Match: (A < B) ? (B - A) : (0 - (B - A)) --> abs(B - A)
1493 if (Pred == CmpInst::ICMP_SLT &&
1494 match(V: TI, P: m_NSWSub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1495 match(V: FI, P: m_Neg(V: m_Specific(V: TI)))) {
1496 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI,
1497 RHS: Builder.getFalse());
1498 }
1499
1500 return nullptr;
1501}
1502
1503/// Fold the following code sequence:
1504/// \code
1505/// int a = ctlz(x & -x);
1506// x ? 31 - a : 32;
1507/// \code
1508///
1509/// into:
1510/// cttz(x)
1511static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
1512 Value *FalseVal,
1513 InstCombiner::BuilderTy &Builder) {
1514 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
1515 if (!ICI->isEquality() || !match(V: ICI->getOperand(i_nocapture: 1), P: m_Zero()))
1516 return nullptr;
1517
1518 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
1519 std::swap(a&: TrueVal, b&: FalseVal);
1520
1521 Value *Ctlz;
1522 if (match(V: FalseVal,
1523 P: m_Xor(L: m_Value(V&: Ctlz), R: m_SpecificIntAllowPoison(V: BitWidth - 1)))) {
1524 if (!isPowerOf2_32(Value: BitWidth))
1525 return nullptr;
1526 } else if (!match(V: FalseVal, P: m_Sub(L: m_SpecificIntAllowPoison(V: BitWidth - 1),
1527 R: m_Value(V&: Ctlz)))) {
1528 return nullptr;
1529 }
1530
1531 if (!match(V: Ctlz, P: m_Ctlz(Op0: m_Value(), Op1: m_Value())))
1532 return nullptr;
1533
1534 if (!match(V: TrueVal, P: m_SpecificInt(V: BitWidth)))
1535 return nullptr;
1536
1537 Value *X = ICI->getOperand(i_nocapture: 0);
1538 auto *II = cast<IntrinsicInst>(Val: Ctlz);
1539 if (!match(V: II->getOperand(i_nocapture: 0), P: m_c_And(L: m_Specific(V: X), R: m_Neg(V: m_Specific(V: X)))))
1540 return nullptr;
1541
1542 // The original select returns the constant bitwidth when x == 0, so the
1543 // result is defined there; the cttz must use is_zero_poison = false.
1544 Function *F = Intrinsic::getOrInsertDeclaration(
1545 M: II->getModule(), id: Intrinsic::cttz, OverloadTys: II->getType());
1546 return CallInst::Create(Func: F, Args: {X, Builder.getFalse()});
1547}
1548
1549/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
1550/// call to cttz/ctlz with flag 'is_zero_poison' cleared.
1551///
1552/// For example, we can fold the following code sequence:
1553/// \code
1554/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
1555/// %1 = icmp ne i32 %x, 0
1556/// %2 = select i1 %1, i32 %0, i32 32
1557/// \code
1558///
1559/// into:
1560/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
1561static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
1562 InstCombinerImpl &IC) {
1563 ICmpInst::Predicate Pred = ICI->getPredicate();
1564 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
1565 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
1566
1567 // Check if the select condition compares a value for equality.
1568 if (!ICI->isEquality())
1569 return nullptr;
1570
1571 Value *SelectArg = FalseVal;
1572 Value *ValueOnZero = TrueVal;
1573 if (Pred == ICmpInst::ICMP_NE)
1574 std::swap(a&: SelectArg, b&: ValueOnZero);
1575
1576 // Skip zero extend/truncate.
1577 Value *Count = nullptr;
1578 if (!match(V: SelectArg, P: m_ZExt(Op: m_Value(V&: Count))) &&
1579 !match(V: SelectArg, P: m_Trunc(Op: m_Value(V&: Count))))
1580 Count = SelectArg;
1581
1582 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
1583 // input to the cttz/ctlz is used as LHS for the compare instruction.
1584 Value *X;
1585 if (!match(V: Count, P: m_Cttz(Op0: m_Value(V&: X), Op1: m_Value())) &&
1586 !match(V: Count, P: m_Ctlz(Op0: m_Value(V&: X), Op1: m_Value())))
1587 return nullptr;
1588
1589 // (X == 0) ? BitWidth : ctz(X)
1590 // (X == -1) ? BitWidth : ctz(~X)
1591 // (X == Y) ? BitWidth : ctz(X ^ Y)
1592 if ((X != CmpLHS || !match(V: CmpRHS, P: m_Zero())) &&
1593 (!match(V: X, P: m_Not(V: m_Specific(V: CmpLHS))) || !match(V: CmpRHS, P: m_AllOnes())) &&
1594 !match(V: X, P: m_c_Xor(L: m_Specific(V: CmpLHS), R: m_Specific(V: CmpRHS))))
1595 return nullptr;
1596
1597 IntrinsicInst *II = cast<IntrinsicInst>(Val: Count);
1598
1599 // Check if the value propagated on zero is a constant number equal to the
1600 // sizeof in bits of 'Count'.
1601 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
1602 if (match(V: ValueOnZero, P: m_SpecificInt(V: SizeOfInBits))) {
1603 // A range annotation on the intrinsic may no longer be valid.
1604 II->dropPoisonGeneratingAnnotations();
1605 IC.addToWorklist(I: II);
1606 return SelectArg;
1607 }
1608
1609 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
1610 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
1611 // not be used if the input is zero. Relax to 'zero is poison' for that case.
1612 if (II->hasOneUse() && SelectArg->hasOneUse() &&
1613 !match(V: II->getArgOperand(i: 1), P: m_One())) {
1614 II->setArgOperand(i: 1, v: ConstantInt::getTrue(Context&: II->getContext()));
1615 // noundef attribute on the intrinsic may no longer be valid.
1616 II->dropUBImplyingAttrsAndMetadata();
1617 IC.addToWorklist(I: II);
1618 }
1619
1620 return nullptr;
1621}
1622
1623static Value *canonicalizeSPF(ICmpInst &Cmp, Value *TrueVal, Value *FalseVal,
1624 InstCombinerImpl &IC) {
1625 Value *LHS, *RHS;
1626 // TODO: What to do with pointer min/max patterns?
1627 if (!TrueVal->getType()->isIntOrIntVectorTy())
1628 return nullptr;
1629
1630 SelectPatternFlavor SPF =
1631 matchDecomposedSelectPattern(CmpI: &Cmp, TrueVal, FalseVal, LHS, RHS).Flavor;
1632 if (SPF == SelectPatternFlavor::SPF_ABS ||
1633 SPF == SelectPatternFlavor::SPF_NABS) {
1634 if (!Cmp.hasOneUse() && !RHS->hasOneUse())
1635 return nullptr; // TODO: Relax this restriction.
1636
1637 // Note that NSW flag can only be propagated for normal, non-negated abs!
1638 bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
1639 match(V: RHS, P: m_NSWNeg(V: m_Specific(V: LHS)));
1640 Constant *IntMinIsPoisonC =
1641 ConstantInt::get(Ty: Type::getInt1Ty(C&: Cmp.getContext()), V: IntMinIsPoison);
1642 Value *Abs =
1643 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS, RHS: IntMinIsPoisonC);
1644
1645 if (SPF == SelectPatternFlavor::SPF_NABS)
1646 return IC.Builder.CreateNeg(V: Abs); // Always without NSW flag!
1647 return Abs;
1648 }
1649
1650 if (SelectPatternResult::isMinOrMax(SPF)) {
1651 Intrinsic::ID IntrinsicID = getMinMaxIntrinsic(SPF);
1652 return IC.Builder.CreateBinaryIntrinsic(ID: IntrinsicID, LHS, RHS);
1653 }
1654
1655 return nullptr;
1656}
1657
1658bool InstCombinerImpl::replaceInInstruction(Value *V, Value *Old, Value *New,
1659 unsigned Depth) {
1660 // Conservatively limit replacement to two instructions upwards.
1661 if (Depth == 2)
1662 return false;
1663
1664 assert(!isa<Constant>(Old) && "Only replace non-constant values");
1665
1666 auto *I = dyn_cast<Instruction>(Val: V);
1667 if (!I || !I->hasOneUse() ||
1668 !isSafeToSpeculativelyExecuteWithVariableReplaced(I))
1669 return false;
1670
1671 // Forbid potentially lane-crossing instructions.
1672 if (Old->getType()->isVectorTy() && !isNotCrossLaneOperation(I))
1673 return false;
1674
1675 bool Changed = false;
1676 for (Use &U : I->operands()) {
1677 if (U == Old) {
1678 replaceUse(U, NewValue: New);
1679 Worklist.add(I);
1680 Changed = true;
1681 } else {
1682 Changed |= replaceInInstruction(V: U, Old, New, Depth: Depth + 1);
1683 }
1684 }
1685 return Changed;
1686}
1687
1688/// If we have a select with an equality comparison, then we know the value in
1689/// one of the arms of the select. See if substituting this value into an arm
1690/// and simplifying the result yields the same value as the other arm.
1691///
1692/// To make this transform safe, we must drop poison-generating flags
1693/// (nsw, etc) if we simplified to a binop because the select may be guarding
1694/// that poison from propagating. If the existing binop already had no
1695/// poison-generating flags, then this transform can be done by instsimplify.
1696///
1697/// Consider:
1698/// %cmp = icmp eq i32 %x, 2147483647
1699/// %add = add nsw i32 %x, 1
1700/// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1701///
1702/// We can't replace %sel with %add unless we strip away the flags.
1703/// TODO: Wrapping flags could be preserved in some cases with better analysis.
1704Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1705 CmpInst &Cmp) {
1706 // Canonicalize the pattern to an equivalence on the predicate by swapping the
1707 // select operands.
1708 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1709 bool Swapped = false;
1710 if (Cmp.isEquivalence(/*Invert=*/true)) {
1711 std::swap(a&: TrueVal, b&: FalseVal);
1712 Swapped = true;
1713 } else if (!Cmp.isEquivalence()) {
1714 return nullptr;
1715 }
1716
1717 Value *CmpLHS = Cmp.getOperand(i_nocapture: 0), *CmpRHS = Cmp.getOperand(i_nocapture: 1);
1718 auto ReplaceOldOpWithNewOp = [&](Value *OldOp,
1719 Value *NewOp) -> Instruction * {
1720 // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1721 // Take care to avoid replacing X == Y ? X : Z with X == Y ? Y : Z, as that
1722 // would lead to an infinite replacement cycle.
1723 // If we will be able to evaluate f(Y) to a constant, we can allow undef,
1724 // otherwise Y cannot be undef as we might pick different values for undef
1725 // in the cmp and in f(Y).
1726 if (TrueVal == OldOp && (isa<Constant>(Val: OldOp) || !isa<Constant>(Val: NewOp)))
1727 return nullptr;
1728
1729 if (Value *V = simplifyWithOpReplaced(V: TrueVal, Op: OldOp, RepOp: NewOp, Q: SQ,
1730 /* AllowRefinement=*/true)) {
1731 // Need some guarantees about the new simplified op to ensure we don't inf
1732 // loop.
1733 // If we simplify to a constant, replace if we aren't creating new undef.
1734 if (match(V, P: m_ImmConstant()) &&
1735 isGuaranteedNotToBeUndef(V, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1736 return replaceOperand(I&: Sel, OpNum: Swapped ? 2 : 1, V);
1737
1738 // If NewOp is a constant and OldOp is not replace iff NewOp doesn't
1739 // contain and undef elements.
1740 // Make sure that V is always simpler than TrueVal, otherwise we might
1741 // end up in an infinite loop.
1742 if (match(V: NewOp, P: m_ImmConstant()) ||
1743 (isa<Instruction>(Val: TrueVal) &&
1744 is_contained(Range: cast<Instruction>(Val: TrueVal)->operands(), Element: V))) {
1745 if (isGuaranteedNotToBeUndef(V: NewOp, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1746 return replaceOperand(I&: Sel, OpNum: Swapped ? 2 : 1, V);
1747 return nullptr;
1748 }
1749 }
1750
1751 // Even if TrueVal does not simplify, we can directly replace a use of
1752 // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
1753 // else and is safe to speculatively execute (we may end up executing it
1754 // with different operands, which should not cause side-effects or trigger
1755 // undefined behavior). Only do this if CmpRHS is a constant, as
1756 // profitability is not clear for other cases.
1757 if (OldOp == CmpLHS && match(V: NewOp, P: m_ImmConstant()) &&
1758 !match(V: OldOp, P: m_Constant()) &&
1759 isGuaranteedNotToBeUndef(V: NewOp, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1760 if (replaceInInstruction(V: TrueVal, Old: OldOp, New: NewOp))
1761 return &Sel;
1762 return nullptr;
1763 };
1764
1765 bool CanReplaceCmpLHSWithRHS = canReplacePointersIfEqual(From: CmpLHS, To: CmpRHS, DL);
1766 if (CanReplaceCmpLHSWithRHS) {
1767 if (Instruction *R = ReplaceOldOpWithNewOp(CmpLHS, CmpRHS))
1768 return R;
1769 }
1770 bool CanReplaceCmpRHSWithLHS = canReplacePointersIfEqual(From: CmpRHS, To: CmpLHS, DL);
1771 if (CanReplaceCmpRHSWithLHS) {
1772 if (Instruction *R = ReplaceOldOpWithNewOp(CmpRHS, CmpLHS))
1773 return R;
1774 }
1775
1776 auto *FalseInst = dyn_cast<Instruction>(Val: FalseVal);
1777 if (!FalseInst)
1778 return nullptr;
1779
1780 // InstSimplify already performed this fold if it was possible subject to
1781 // current poison-generating flags. Check whether dropping poison-generating
1782 // flags enables the transform.
1783
1784 // Try each equivalence substitution possibility.
1785 // We have an 'EQ' comparison, so the select's false value will propagate.
1786 // Example:
1787 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1788 SmallVector<Instruction *> DropFlags;
1789 if ((CanReplaceCmpLHSWithRHS &&
1790 simplifyWithOpReplaced(V: FalseVal, Op: CmpLHS, RepOp: CmpRHS, Q: SQ,
1791 /* AllowRefinement */ false,
1792 DropFlags: &DropFlags) == TrueVal) ||
1793 (CanReplaceCmpRHSWithLHS &&
1794 simplifyWithOpReplaced(V: FalseVal, Op: CmpRHS, RepOp: CmpLHS, Q: SQ,
1795 /* AllowRefinement */ false,
1796 DropFlags: &DropFlags) == TrueVal)) {
1797 for (Instruction *I : DropFlags) {
1798 I->dropPoisonGeneratingAnnotations();
1799 Worklist.add(I);
1800 }
1801
1802 return replaceInstUsesWith(I&: Sel, V: FalseVal);
1803 }
1804
1805 Constant *CmpC;
1806 if (FalseVal->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
1807 match(V: FalseVal, P: m_NUWTrunc(Op: m_Specific(V: CmpLHS))) &&
1808 match(V: CmpRHS, P: m_ImmConstant(C&: CmpC)) &&
1809 ConstantFoldCompareInstOperands(
1810 Predicate: ICmpInst::Predicate::ICMP_NE, LHS: CmpC,
1811 RHS: ConstantInt::getNullValue(Ty: CmpLHS->getType()), DL) == TrueVal) {
1812 return new ICmpInst(CmpInst::Predicate::ICMP_NE, CmpLHS,
1813 ConstantInt::getNullValue(Ty: CmpLHS->getType()));
1814 }
1815
1816 return nullptr;
1817}
1818
1819/// Fold the following code sequence:
1820/// \code
1821/// %XeqZ = icmp eq i64 %X, %Z
1822/// %YeqZ = icmp eq i64 %Y, %Z
1823/// %XeqY = icmp eq i64 %X, %Y
1824/// %not.YeqZ = xor i1 %YeqZ, true
1825/// %and = select i1 %not.YeqZ, i1 %XeqY, i1 false
1826/// %equal = select i1 %XeqZ, i1 %YeqZ, i1 %and
1827/// \code
1828///
1829/// into:
1830/// %equal = icmp eq i64 %X, %Y
1831Instruction *InstCombinerImpl::foldSelectEqualityTest(SelectInst &Sel) {
1832 Value *X, *Y, *Z;
1833 Value *XeqY, *XeqZ = Sel.getCondition(), *YeqZ = Sel.getTrueValue();
1834
1835 if (!match(V: XeqZ, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: X), R: m_Value(V&: Z))))
1836 return nullptr;
1837
1838 if (!match(V: YeqZ,
1839 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: Y), R: m_Specific(V: Z))))
1840 std::swap(a&: X, b&: Z);
1841
1842 if (!match(V: YeqZ,
1843 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: Y), R: m_Specific(V: Z))))
1844 return nullptr;
1845
1846 if (!match(V: Sel.getFalseValue(),
1847 P: m_c_LogicalAnd(L: m_Not(V: m_Specific(V: YeqZ)), R: m_Value(V&: XeqY))))
1848 return nullptr;
1849
1850 if (!match(V: XeqY,
1851 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: X), R: m_Specific(V: Y))))
1852 return nullptr;
1853
1854 cast<ICmpInst>(Val: XeqY)->setSameSign(false);
1855 return replaceInstUsesWith(I&: Sel, V: XeqY);
1856}
1857
1858// See if this is a pattern like:
1859// %old_cmp1 = icmp slt i32 %x, C2
1860// %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1861// %old_x_offseted = add i32 %x, C1
1862// %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1863// %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1864// This can be rewritten as more canonical pattern:
1865// %new_cmp1 = icmp slt i32 %x, -C1
1866// %new_cmp2 = icmp sge i32 %x, C0-C1
1867// %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1868// %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1869// Iff -C1 s<= C2 s<= C0-C1
1870// Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1871// SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1872static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1873 InstCombiner::BuilderTy &Builder,
1874 InstCombiner &IC) {
1875 Value *X = Sel0.getTrueValue();
1876 Value *Sel1 = Sel0.getFalseValue();
1877
1878 // First match the condition of the outermost select.
1879 // Said condition must be one-use.
1880 if (!Cmp0.hasOneUse())
1881 return nullptr;
1882 ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
1883 Value *Cmp00 = Cmp0.getOperand(i_nocapture: 0);
1884 Constant *C0;
1885 if (!match(V: Cmp0.getOperand(i_nocapture: 1),
1886 P: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C0))))
1887 return nullptr;
1888
1889 if (!isa<SelectInst>(Val: Sel1)) {
1890 Pred0 = ICmpInst::getInversePredicate(pred: Pred0);
1891 std::swap(a&: X, b&: Sel1);
1892 }
1893
1894 // Canonicalize Cmp0 into ult or uge.
1895 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1896 switch (Pred0) {
1897 case ICmpInst::Predicate::ICMP_ULT:
1898 case ICmpInst::Predicate::ICMP_UGE:
1899 // Although icmp ult %x, 0 is an unusual thing to try and should generally
1900 // have been simplified, it does not verify with undef inputs so ensure we
1901 // are not in a strange state.
1902 if (!match(V: C0, P: m_SpecificInt_ICMP(
1903 Predicate: ICmpInst::Predicate::ICMP_NE,
1904 Threshold: APInt::getZero(numBits: C0->getType()->getScalarSizeInBits()))))
1905 return nullptr;
1906 break; // Great!
1907 case ICmpInst::Predicate::ICMP_ULE:
1908 case ICmpInst::Predicate::ICMP_UGT:
1909 // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
1910 // C0, which again means it must not have any all-ones elements.
1911 if (!match(V: C0,
1912 P: m_SpecificInt_ICMP(
1913 Predicate: ICmpInst::Predicate::ICMP_NE,
1914 Threshold: APInt::getAllOnes(numBits: C0->getType()->getScalarSizeInBits()))))
1915 return nullptr; // Can't do, have all-ones element[s].
1916 Pred0 = ICmpInst::getFlippedStrictnessPredicate(pred: Pred0);
1917 C0 = InstCombiner::AddOne(C: C0);
1918 break;
1919 default:
1920 return nullptr; // Unknown predicate.
1921 }
1922
1923 // Now that we've canonicalized the ICmp, we know the X we expect;
1924 // the select in other hand should be one-use.
1925 if (!Sel1->hasOneUse())
1926 return nullptr;
1927
1928 // If the types do not match, look through any truncs to the underlying
1929 // instruction.
1930 if (Cmp00->getType() != X->getType() && X->hasOneUse())
1931 match(V: X, P: m_TruncOrSelf(Op: m_Value(V&: X)));
1932
1933 // We now can finish matching the condition of the outermost select:
1934 // it should either be the X itself, or an addition of some constant to X.
1935 Constant *C1;
1936 if (Cmp00 == X)
1937 C1 = ConstantInt::getNullValue(Ty: X->getType());
1938 else if (!match(V: Cmp00,
1939 P: m_Add(L: m_Specific(V: X),
1940 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C1)))))
1941 return nullptr;
1942
1943 Value *Cmp1;
1944 CmpPredicate Pred1;
1945 Constant *C2;
1946 Value *ReplacementLow, *ReplacementHigh;
1947 if (!match(V: Sel1, P: m_Select(C: m_Value(V&: Cmp1), L: m_Value(V&: ReplacementLow),
1948 R: m_Value(V&: ReplacementHigh))) ||
1949 !match(V: Cmp1,
1950 P: m_ICmp(Pred&: Pred1, L: m_Specific(V: X),
1951 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C2)))))
1952 return nullptr;
1953
1954 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1955 return nullptr; // Not enough one-use instructions for the fold.
1956 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1957 // two comparisons we'll need to build.
1958
1959 // Canonicalize Cmp1 into the form we expect.
1960 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1961 switch (Pred1) {
1962 case ICmpInst::Predicate::ICMP_SLT:
1963 break;
1964 case ICmpInst::Predicate::ICMP_SLE:
1965 // We'd have to increment C2 by one, and for that it must not have signed
1966 // max element, but then it would have been canonicalized to 'slt' before
1967 // we get here. So we can't do anything useful with 'sle'.
1968 return nullptr;
1969 case ICmpInst::Predicate::ICMP_SGT:
1970 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1971 // which again means it must not have any signed max elements.
1972 if (!match(V: C2,
1973 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_NE,
1974 Threshold: APInt::getSignedMaxValue(
1975 numBits: C2->getType()->getScalarSizeInBits()))))
1976 return nullptr; // Can't do, have signed max element[s].
1977 C2 = InstCombiner::AddOne(C: C2);
1978 [[fallthrough]];
1979 case ICmpInst::Predicate::ICMP_SGE:
1980 // Also non-canonical, but here we don't need to change C2,
1981 // so we don't have any restrictions on C2, so we can just handle it.
1982 Pred1 = ICmpInst::Predicate::ICMP_SLT;
1983 std::swap(a&: ReplacementLow, b&: ReplacementHigh);
1984 break;
1985 default:
1986 return nullptr; // Unknown predicate.
1987 }
1988 assert(Pred1 == ICmpInst::Predicate::ICMP_SLT &&
1989 "Unexpected predicate type.");
1990
1991 // The thresholds of this clamp-like pattern.
1992 auto *ThresholdLowIncl = ConstantExpr::getNeg(C: C1);
1993 auto *ThresholdHighExcl = ConstantExpr::getSub(C1: C0, C2: C1);
1994
1995 assert((Pred0 == ICmpInst::Predicate::ICMP_ULT ||
1996 Pred0 == ICmpInst::Predicate::ICMP_UGE) &&
1997 "Unexpected predicate type.");
1998 if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
1999 std::swap(a&: ThresholdLowIncl, b&: ThresholdHighExcl);
2000
2001 // The fold has a precondition 1: C2 s>= ThresholdLow
2002 auto *Precond1 = ConstantFoldCompareInstOperands(
2003 Predicate: ICmpInst::Predicate::ICMP_SGE, LHS: C2, RHS: ThresholdLowIncl, DL: IC.getDataLayout());
2004 if (!Precond1 || !match(V: Precond1, P: m_One()))
2005 return nullptr;
2006 // The fold has a precondition 2: C2 s<= ThresholdHigh
2007 auto *Precond2 = ConstantFoldCompareInstOperands(
2008 Predicate: ICmpInst::Predicate::ICMP_SLE, LHS: C2, RHS: ThresholdHighExcl, DL: IC.getDataLayout());
2009 if (!Precond2 || !match(V: Precond2, P: m_One()))
2010 return nullptr;
2011
2012 // If we are matching from a truncated input, we need to sext the
2013 // ReplacementLow and ReplacementHigh values. Only do the transform if they
2014 // are free to extend due to being constants.
2015 if (X->getType() != Sel0.getType()) {
2016 Constant *LowC, *HighC;
2017 if (!match(V: ReplacementLow, P: m_ImmConstant(C&: LowC)) ||
2018 !match(V: ReplacementHigh, P: m_ImmConstant(C&: HighC)))
2019 return nullptr;
2020 const DataLayout &DL = Sel0.getDataLayout();
2021 ReplacementLow =
2022 ConstantFoldCastOperand(Opcode: Instruction::SExt, C: LowC, DestTy: X->getType(), DL);
2023 ReplacementHigh =
2024 ConstantFoldCastOperand(Opcode: Instruction::SExt, C: HighC, DestTy: X->getType(), DL);
2025 assert(ReplacementLow && ReplacementHigh &&
2026 "Constant folding of ImmConstant cannot fail");
2027 }
2028
2029 // All good, finally emit the new pattern.
2030 Value *ShouldReplaceLow = Builder.CreateICmpSLT(LHS: X, RHS: ThresholdLowIncl);
2031 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(LHS: X, RHS: ThresholdHighExcl);
2032 Value *MaybeReplacedLow =
2033 Builder.CreateSelect(C: ShouldReplaceLow, True: ReplacementLow, False: X);
2034
2035 // Create the final select. If we looked through a truncate above, we will
2036 // need to retruncate the result.
2037 Value *MaybeReplacedHigh = Builder.CreateSelect(
2038 C: ShouldReplaceHigh, True: ReplacementHigh, False: MaybeReplacedLow);
2039 return Builder.CreateTrunc(V: MaybeReplacedHigh, DestTy: Sel0.getType());
2040}
2041
2042// If we have
2043// %cmp = icmp [canonical predicate] i32 %x, C0
2044// %r = select i1 %cmp, i32 %y, i32 C1
2045// Where C0 != C1 and %x may be different from %y, see if the constant that we
2046// will have if we flip the strictness of the predicate (i.e. without changing
2047// the result) is identical to the C1 in select. If it matches we can change
2048// original comparison to one with swapped predicate, reuse the constant,
2049// and swap the hands of select.
2050static Instruction *
2051tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
2052 InstCombinerImpl &IC) {
2053 CmpPredicate Pred;
2054 Value *X;
2055 Constant *C0;
2056 if (!match(V: &Cmp, P: m_OneUse(SubPattern: m_ICmp(
2057 Pred, L: m_Value(V&: X),
2058 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C0))))))
2059 return nullptr;
2060
2061 // If comparison predicate is non-relational, we won't be able to do anything.
2062 if (ICmpInst::isEquality(P: Pred))
2063 return nullptr;
2064
2065 // If comparison predicate is non-canonical, then we certainly won't be able
2066 // to make it canonical; canonicalizeCmpWithConstant() already tried.
2067 if (!InstCombiner::isCanonicalPredicate(Pred))
2068 return nullptr;
2069
2070 // If the [input] type of comparison and select type are different, lets abort
2071 // for now. We could try to compare constants with trunc/[zs]ext though.
2072 if (C0->getType() != Sel.getType())
2073 return nullptr;
2074
2075 // ULT with 'add' of a constant is canonical. See foldICmpAddConstant().
2076 // FIXME: Are there more magic icmp predicate+constant pairs we must avoid?
2077 // Or should we just abandon this transform entirely?
2078 if (Pred == CmpInst::ICMP_ULT && match(V: X, P: m_Add(L: m_Value(), R: m_Constant())))
2079 return nullptr;
2080
2081
2082 Value *SelVal0, *SelVal1; // We do not care which one is from where.
2083 match(V: &Sel, P: m_Select(C: m_Value(), L: m_Value(V&: SelVal0), R: m_Value(V&: SelVal1)));
2084 // At least one of these values we are selecting between must be a constant
2085 // else we'll never succeed.
2086 if (!match(V: SelVal0, P: m_AnyIntegralConstant()) &&
2087 !match(V: SelVal1, P: m_AnyIntegralConstant()))
2088 return nullptr;
2089
2090 // Does this constant C match any of the `select` values?
2091 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
2092 return C->isElementWiseEqual(Y: SelVal0) || C->isElementWiseEqual(Y: SelVal1);
2093 };
2094
2095 // If C0 *already* matches true/false value of select, we are done.
2096 if (MatchesSelectValue(C0))
2097 return nullptr;
2098
2099 // Check the constant we'd have with flipped-strictness predicate.
2100 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: C0);
2101 if (!FlippedStrictness)
2102 return nullptr;
2103
2104 // If said constant doesn't match either, then there is no hope,
2105 if (!MatchesSelectValue(FlippedStrictness->second))
2106 return nullptr;
2107
2108 // It matched! Lets insert the new comparison just before select.
2109 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
2110 IC.Builder.SetInsertPoint(&Sel);
2111
2112 Pred = ICmpInst::getSwappedPredicate(pred: Pred); // Yes, swapped.
2113 Value *NewCmp = IC.Builder.CreateICmp(P: Pred, LHS: X, RHS: FlippedStrictness->second,
2114 Name: Cmp.getName() + ".inv");
2115 IC.replaceOperand(I&: Sel, OpNum: 0, V: NewCmp);
2116 Sel.swapValues();
2117 Sel.swapProfMetadata();
2118
2119 return &Sel;
2120}
2121
2122static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal,
2123 Value *FVal,
2124 InstCombiner::BuilderTy &Builder) {
2125 if (!Cmp->hasOneUse())
2126 return nullptr;
2127
2128 const APInt *CmpC;
2129 if (!match(V: Cmp->getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: CmpC)))
2130 return nullptr;
2131
2132 // (X u< 2) ? -X : -1 --> sext (X != 0)
2133 Value *X = Cmp->getOperand(i_nocapture: 0);
2134 if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 &&
2135 match(V: TVal, P: m_Neg(V: m_Specific(V: X))) && match(V: FVal, P: m_AllOnes()))
2136 return new SExtInst(Builder.CreateIsNotNull(Arg: X), TVal->getType());
2137
2138 // (X u> 1) ? -1 : -X --> sext (X != 0)
2139 if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 &&
2140 match(V: FVal, P: m_Neg(V: m_Specific(V: X))) && match(V: TVal, P: m_AllOnes()))
2141 return new SExtInst(Builder.CreateIsNotNull(Arg: X), TVal->getType());
2142
2143 return nullptr;
2144}
2145
2146static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI,
2147 InstCombiner::BuilderTy &Builder) {
2148 const APInt *CmpC;
2149 Value *V;
2150 CmpPredicate Pred;
2151 if (!match(V: ICI, P: m_ICmp(Pred, L: m_Value(V), R: m_APInt(Res&: CmpC))))
2152 return nullptr;
2153
2154 // Match clamp away from min/max value as a max/min operation.
2155 Value *TVal = SI.getTrueValue();
2156 Value *FVal = SI.getFalseValue();
2157 if (Pred == ICmpInst::ICMP_EQ && V == FVal) {
2158 // (V == UMIN) ? UMIN+1 : V --> umax(V, UMIN+1)
2159 if (CmpC->isMinValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC + 1)))
2160 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: V, RHS: TVal);
2161 // (V == UMAX) ? UMAX-1 : V --> umin(V, UMAX-1)
2162 if (CmpC->isMaxValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC - 1)))
2163 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: V, RHS: TVal);
2164 // (V == SMIN) ? SMIN+1 : V --> smax(V, SMIN+1)
2165 if (CmpC->isMinSignedValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC + 1)))
2166 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smax, LHS: V, RHS: TVal);
2167 // (V == SMAX) ? SMAX-1 : V --> smin(V, SMAX-1)
2168 if (CmpC->isMaxSignedValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC - 1)))
2169 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: V, RHS: TVal);
2170 }
2171
2172 // Fold icmp(X) ? f(X) : C to f(X) when f(X) is guaranteed to be equal to C
2173 // for all X in the exact range of the inverse predicate.
2174 Instruction *Op;
2175 const APInt *C;
2176 CmpInst::Predicate CPred;
2177 if (match(V: &SI, P: m_Select(C: m_Specific(V: ICI), L: m_APInt(Res&: C), R: m_Instruction(I&: Op))))
2178 CPred = ICI->getPredicate();
2179 else if (match(V: &SI, P: m_Select(C: m_Specific(V: ICI), L: m_Instruction(I&: Op), R: m_APInt(Res&: C))))
2180 CPred = ICI->getInversePredicate();
2181 else
2182 return nullptr;
2183
2184 ConstantRange InvDomCR = ConstantRange::makeExactICmpRegion(Pred: CPred, Other: *CmpC);
2185 const APInt *OpC;
2186 if (match(V: Op, P: m_BinOp(L: m_Specific(V), R: m_APInt(Res&: OpC)))) {
2187 ConstantRange R = InvDomCR.binaryOp(
2188 BinOp: static_cast<Instruction::BinaryOps>(Op->getOpcode()), Other: *OpC);
2189 if (R == *C) {
2190 Op->dropPoisonGeneratingFlags();
2191 return Op;
2192 }
2193 }
2194 if (auto *MMI = dyn_cast<MinMaxIntrinsic>(Val: Op);
2195 MMI && MMI->getLHS() == V && match(V: MMI->getRHS(), P: m_APInt(Res&: OpC))) {
2196 ConstantRange R = ConstantRange::intrinsic(IntrinsicID: MMI->getIntrinsicID(),
2197 Ops: {InvDomCR, ConstantRange(*OpC)});
2198 if (R == *C) {
2199 MMI->dropPoisonGeneratingAnnotations();
2200 return MMI;
2201 }
2202 }
2203
2204 return nullptr;
2205}
2206
2207/// `A == MIN_INT ? B != MIN_INT : A < B` --> `A < B`
2208/// `A == MAX_INT ? B != MAX_INT : A > B` --> `A > B`
2209static Instruction *foldSelectWithExtremeEqCond(Value *CmpLHS, Value *CmpRHS,
2210 Value *TrueVal,
2211 Value *FalseVal) {
2212 Type *Ty = CmpLHS->getType();
2213
2214 if (Ty->isPtrOrPtrVectorTy())
2215 return nullptr;
2216
2217 CmpPredicate Pred;
2218 Value *B;
2219
2220 if (!match(V: FalseVal, P: m_c_ICmp(Pred, L: m_Specific(V: CmpLHS), R: m_Value(V&: B))))
2221 return nullptr;
2222
2223 Value *TValRHS;
2224 if (!match(V: TrueVal, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: m_Specific(V: B),
2225 R: m_Value(V&: TValRHS))))
2226 return nullptr;
2227
2228 APInt C;
2229 unsigned BitWidth = Ty->getScalarSizeInBits();
2230
2231 if (ICmpInst::isLT(P: Pred)) {
2232 C = CmpInst::isSigned(Pred) ? APInt::getSignedMinValue(numBits: BitWidth)
2233 : APInt::getMinValue(numBits: BitWidth);
2234 } else if (ICmpInst::isGT(P: Pred)) {
2235 C = CmpInst::isSigned(Pred) ? APInt::getSignedMaxValue(numBits: BitWidth)
2236 : APInt::getMaxValue(numBits: BitWidth);
2237 } else {
2238 return nullptr;
2239 }
2240
2241 if (!match(V: CmpRHS, P: m_SpecificInt(V: C)) || !match(V: TValRHS, P: m_SpecificInt(V: C)))
2242 return nullptr;
2243
2244 return new ICmpInst(Pred, CmpLHS, B);
2245}
2246
2247static Instruction *foldSelectICmpEq(SelectInst &SI, ICmpInst *ICI,
2248 InstCombinerImpl &IC) {
2249 ICmpInst::Predicate Pred = ICI->getPredicate();
2250 if (!ICmpInst::isEquality(P: Pred))
2251 return nullptr;
2252
2253 Value *TrueVal = SI.getTrueValue();
2254 Value *FalseVal = SI.getFalseValue();
2255 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
2256 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
2257
2258 if (Pred == ICmpInst::ICMP_NE)
2259 std::swap(a&: TrueVal, b&: FalseVal);
2260
2261 if (Instruction *Res =
2262 foldSelectWithExtremeEqCond(CmpLHS, CmpRHS, TrueVal, FalseVal))
2263 return Res;
2264
2265 return nullptr;
2266}
2267
2268/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
2269/// This allows for better canonicalization.
2270Value *InstCombinerImpl::foldSelectWithConstOpToBinOp(ICmpInst *Cmp,
2271 Value *TrueVal,
2272 Value *FalseVal) {
2273 Constant *C1, *C2, *C3;
2274 Value *X;
2275 CmpPredicate Predicate;
2276
2277 if (!match(V: Cmp, P: m_ICmp(Pred&: Predicate, L: m_Value(V&: X), R: m_Constant(C&: C1))))
2278 return nullptr;
2279
2280 if (!ICmpInst::isRelational(P: Predicate))
2281 return nullptr;
2282
2283 if (match(V: TrueVal, P: m_Constant())) {
2284 std::swap(a&: FalseVal, b&: TrueVal);
2285 Predicate = ICmpInst::getInversePredicate(pred: Predicate);
2286 }
2287
2288 if (!match(V: FalseVal, P: m_Constant(C&: C3)) || !TrueVal->hasOneUse())
2289 return nullptr;
2290
2291 bool IsIntrinsic;
2292 unsigned Opcode;
2293 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: TrueVal)) {
2294 Opcode = BOp->getOpcode();
2295 IsIntrinsic = false;
2296
2297 // This fold causes some regressions and is primarily intended for
2298 // add and sub. So we early exit for div and rem to minimize the
2299 // regressions.
2300 if (Instruction::isIntDivRem(Opcode))
2301 return nullptr;
2302
2303 if (!match(V: BOp, P: m_BinOp(L: m_Specific(V: X), R: m_Constant(C&: C2))))
2304 return nullptr;
2305
2306 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: TrueVal)) {
2307 if (!match(V: II, P: m_MaxOrMin(Op0: m_Specific(V: X), Op1: m_Constant(C&: C2))))
2308 return nullptr;
2309 Opcode = II->getIntrinsicID();
2310 IsIntrinsic = true;
2311 } else {
2312 return nullptr;
2313 }
2314
2315 Value *RHS;
2316 SelectPatternFlavor SPF;
2317 const DataLayout &DL = Cmp->getDataLayout();
2318 auto Flipped = getFlippedStrictnessPredicateAndConstant(Pred: Predicate, C: C1);
2319
2320 auto FoldBinaryOpOrIntrinsic = [&](Constant *LHS, Constant *RHS) {
2321 return IsIntrinsic
2322 ? ConstantFoldIntrinsic(ID: Opcode, Ops: {LHS, RHS}, Ty: LHS->getType(), DL)
2323 : ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
2324 };
2325
2326 if (C3 == FoldBinaryOpOrIntrinsic(C1, C2)) {
2327 SPF = getSelectPattern(Pred: Predicate).Flavor;
2328 RHS = C1;
2329 } else if (Flipped && C3 == FoldBinaryOpOrIntrinsic(Flipped->second, C2)) {
2330 SPF = getSelectPattern(Pred: Flipped->first).Flavor;
2331 RHS = Flipped->second;
2332 } else {
2333 return nullptr;
2334 }
2335
2336 Intrinsic::ID MinMaxID = getMinMaxIntrinsic(SPF);
2337 Value *MinMax = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS);
2338 if (IsIntrinsic)
2339 return Builder.CreateBinaryIntrinsic(ID: Opcode, LHS: MinMax, RHS: C2);
2340
2341 const auto BinOpc = Instruction::BinaryOps(Opcode);
2342 Value *BinOp = Builder.CreateBinOp(Opc: BinOpc, LHS: MinMax, RHS: C2);
2343
2344 // If we can attach no-wrap flags to the new instruction, do so if the
2345 // old instruction had them and C1 BinOp C2 does not overflow.
2346 if (Instruction *BinOpInst = dyn_cast<Instruction>(Val: BinOp)) {
2347 if (BinOpc == Instruction::Add || BinOpc == Instruction::Sub ||
2348 BinOpc == Instruction::Mul) {
2349 Instruction *OldBinOp = cast<BinaryOperator>(Val: TrueVal);
2350 if (OldBinOp->hasNoSignedWrap() &&
2351 willNotOverflow(Opcode: BinOpc, LHS: RHS, RHS: C2, CxtI: *BinOpInst, /*IsSigned=*/true))
2352 BinOpInst->setHasNoSignedWrap();
2353 if (OldBinOp->hasNoUnsignedWrap() &&
2354 willNotOverflow(Opcode: BinOpc, LHS: RHS, RHS: C2, CxtI: *BinOpInst, /*IsSigned=*/false))
2355 BinOpInst->setHasNoUnsignedWrap();
2356 }
2357 }
2358 return BinOp;
2359}
2360
2361/// Folds:
2362/// %a_sub = call @llvm.usub.sat(x, IntConst1)
2363/// %b_sub = call @llvm.usub.sat(y, IntConst2)
2364/// %or = or %a_sub, %b_sub
2365/// %cmp = icmp eq %or, 0
2366/// %sel = select %cmp, 0, MostSignificantBit
2367/// into:
2368/// %a_sub' = usub.sat(x, IntConst1 - MostSignificantBit)
2369/// %b_sub' = usub.sat(y, IntConst2 - MostSignificantBit)
2370/// %or = or %a_sub', %b_sub'
2371/// %and = and %or, MostSignificantBit
2372/// Likewise, for vector arguments as well.
2373static Instruction *foldICmpUSubSatWithAndForMostSignificantBitCmp(
2374 SelectInst &SI, ICmpInst *ICI, InstCombiner::BuilderTy &Builder) {
2375 if (!SI.hasOneUse() || !ICI->hasOneUse())
2376 return nullptr;
2377 CmpPredicate Pred;
2378 Value *A, *B;
2379 const APInt *Constant1, *Constant2;
2380 if (!match(V: SI.getCondition(),
2381 P: m_ICmp(Pred,
2382 L: m_OneUse(SubPattern: m_Or(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(
2383 Ops: m_Value(V&: A), Ops: m_APInt(Res&: Constant1))),
2384 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(
2385 Ops: m_Value(V&: B), Ops: m_APInt(Res&: Constant2))))),
2386 R: m_Zero())))
2387 return nullptr;
2388
2389 Value *TrueVal = SI.getTrueValue();
2390 Value *FalseVal = SI.getFalseValue();
2391 if (!((Pred == ICmpInst::ICMP_EQ && match(V: TrueVal, P: m_Zero()) &&
2392 match(V: FalseVal, P: m_SignMask())) ||
2393 (Pred == ICmpInst::ICMP_NE && match(V: TrueVal, P: m_SignMask()) &&
2394 match(V: FalseVal, P: m_Zero()))))
2395 return nullptr;
2396
2397 auto *Ty = A->getType();
2398 unsigned BW = Constant1->getBitWidth();
2399 APInt MostSignificantBit = APInt::getSignMask(BitWidth: BW);
2400
2401 // Anything over MSB is negative
2402 if (Constant1->isNonNegative() || Constant2->isNonNegative())
2403 return nullptr;
2404
2405 APInt AdjAP1 = *Constant1 - MostSignificantBit + 1;
2406 APInt AdjAP2 = *Constant2 - MostSignificantBit + 1;
2407
2408 auto *Adj1 = ConstantInt::get(Ty, V: AdjAP1);
2409 auto *Adj2 = ConstantInt::get(Ty, V: AdjAP2);
2410
2411 Value *NewA = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A, RHS: Adj1);
2412 Value *NewB = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: B, RHS: Adj2);
2413 Value *Or = Builder.CreateOr(LHS: NewA, RHS: NewB);
2414 Constant *MSBConst = ConstantInt::get(Ty, V: MostSignificantBit);
2415 return BinaryOperator::CreateAnd(V1: Or, V2: MSBConst);
2416}
2417
2418/// Visit a SelectInst that has an ICmpInst as its first operand.
2419Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
2420 ICmpInst *ICI) {
2421 if (Value *V =
2422 canonicalizeSPF(Cmp&: *ICI, TrueVal: SI.getTrueValue(), FalseVal: SI.getFalseValue(), IC&: *this))
2423 return replaceInstUsesWith(I&: SI, V);
2424
2425 if (Value *V = foldSelectInstWithICmpConst(SI, ICI, Builder))
2426 return replaceInstUsesWith(I&: SI, V);
2427
2428 if (Value *V = canonicalizeClampLike(Sel0&: SI, Cmp0&: *ICI, Builder, IC&: *this))
2429 return replaceInstUsesWith(I&: SI, V);
2430
2431 if (Instruction *NewSel =
2432 tryToReuseConstantFromSelectInComparison(Sel&: SI, Cmp&: *ICI, IC&: *this))
2433 return NewSel;
2434 if (Instruction *Folded =
2435 foldICmpUSubSatWithAndForMostSignificantBitCmp(SI, ICI, Builder))
2436 return Folded;
2437
2438 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
2439 bool Changed = false;
2440 Value *TrueVal = SI.getTrueValue();
2441 Value *FalseVal = SI.getFalseValue();
2442 ICmpInst::Predicate Pred = ICI->getPredicate();
2443 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
2444 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
2445
2446 if (Instruction *NewSel = foldSelectICmpEq(SI, ICI, IC&: *this))
2447 return NewSel;
2448
2449 // Canonicalize a signbit condition to use zero constant by swapping:
2450 // (CmpLHS > -1) ? TV : FV --> (CmpLHS < 0) ? FV : TV
2451 // To avoid conflicts (infinite loops) with other canonicalizations, this is
2452 // not applied with any constant select arm.
2453 if (Pred == ICmpInst::ICMP_SGT && match(V: CmpRHS, P: m_AllOnes()) &&
2454 !match(V: TrueVal, P: m_Constant()) && !match(V: FalseVal, P: m_Constant()) &&
2455 ICI->hasOneUse()) {
2456 InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
2457 Builder.SetInsertPoint(&SI);
2458 Value *IsNeg = Builder.CreateIsNeg(Arg: CmpLHS, Name: ICI->getName());
2459 replaceOperand(I&: SI, OpNum: 0, V: IsNeg);
2460 SI.swapValues();
2461 SI.swapProfMetadata();
2462 return &SI;
2463 }
2464
2465 if (Value *V = foldSelectICmpMinMax(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder, SQ))
2466 return replaceInstUsesWith(I&: SI, V);
2467
2468 if (Value *V = foldSelectICmpAndZeroShl(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2469 return replaceInstUsesWith(I&: SI, V);
2470
2471 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
2472 return V;
2473
2474 if (Instruction *V = foldSelectZeroOrOnes(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2475 return V;
2476
2477 if (Value *V = foldSelectICmpLshrAshr(IC: ICI, TrueVal, FalseVal, Builder))
2478 return replaceInstUsesWith(I&: SI, V);
2479
2480 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, IC&: *this))
2481 return replaceInstUsesWith(I&: SI, V);
2482
2483 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
2484 return replaceInstUsesWith(I&: SI, V);
2485
2486 if (Value *V = canonicalizeSaturatedAdd(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2487 return replaceInstUsesWith(I&: SI, V);
2488
2489 if (Value *V = foldAbsDiff(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2490 return replaceInstUsesWith(I&: SI, V);
2491
2492 if (Value *V = foldSelectWithConstOpToBinOp(Cmp: ICI, TrueVal, FalseVal))
2493 return replaceInstUsesWith(I&: SI, V);
2494
2495 return Changed ? &SI : nullptr;
2496}
2497
2498/// We have an SPF (e.g. a min or max) of an SPF of the form:
2499/// SPF2(SPF1(A, B), C)
2500Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
2501 SelectPatternFlavor SPF1, Value *A,
2502 Value *B, Instruction &Outer,
2503 SelectPatternFlavor SPF2,
2504 Value *C) {
2505 if (Outer.getType() != Inner->getType())
2506 return nullptr;
2507
2508 if (C == A || C == B) {
2509 // MAX(MAX(A, B), B) -> MAX(A, B)
2510 // MIN(MIN(a, b), a) -> MIN(a, b)
2511 // TODO: This could be done in instsimplify.
2512 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF: SPF1))
2513 return replaceInstUsesWith(I&: Outer, V: Inner);
2514 }
2515
2516 return nullptr;
2517}
2518
2519/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
2520/// This is even legal for FP.
2521static Instruction *foldAddSubSelect(SelectInst &SI,
2522 InstCombiner::BuilderTy &Builder) {
2523 Value *CondVal = SI.getCondition();
2524 Value *TrueVal = SI.getTrueValue();
2525 Value *FalseVal = SI.getFalseValue();
2526 auto *TI = dyn_cast<Instruction>(Val: TrueVal);
2527 auto *FI = dyn_cast<Instruction>(Val: FalseVal);
2528 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
2529 return nullptr;
2530
2531 Instruction *AddOp = nullptr, *SubOp = nullptr;
2532 if ((TI->getOpcode() == Instruction::Sub &&
2533 FI->getOpcode() == Instruction::Add) ||
2534 (TI->getOpcode() == Instruction::FSub &&
2535 FI->getOpcode() == Instruction::FAdd)) {
2536 AddOp = FI;
2537 SubOp = TI;
2538 } else if ((FI->getOpcode() == Instruction::Sub &&
2539 TI->getOpcode() == Instruction::Add) ||
2540 (FI->getOpcode() == Instruction::FSub &&
2541 TI->getOpcode() == Instruction::FAdd)) {
2542 AddOp = TI;
2543 SubOp = FI;
2544 }
2545
2546 if (AddOp) {
2547 Value *OtherAddOp = nullptr;
2548 if (SubOp->getOperand(i: 0) == AddOp->getOperand(i: 0)) {
2549 OtherAddOp = AddOp->getOperand(i: 1);
2550 } else if (SubOp->getOperand(i: 0) == AddOp->getOperand(i: 1)) {
2551 OtherAddOp = AddOp->getOperand(i: 0);
2552 }
2553
2554 if (OtherAddOp) {
2555 // So at this point we know we have (Y -> OtherAddOp):
2556 // select C, (add X, Y), (sub X, Z)
2557 Value *NegVal; // Compute -Z
2558 if (SI.getType()->isFPOrFPVectorTy()) {
2559 NegVal = Builder.CreateFNeg(V: SubOp->getOperand(i: 1));
2560 if (Instruction *NegInst = dyn_cast<Instruction>(Val: NegVal)) {
2561 FastMathFlags Flags = AddOp->getFastMathFlags();
2562 Flags &= SubOp->getFastMathFlags();
2563 NegInst->setFastMathFlags(Flags);
2564 }
2565 } else {
2566 NegVal = Builder.CreateNeg(V: SubOp->getOperand(i: 1));
2567 }
2568
2569 Value *NewTrueOp = OtherAddOp;
2570 Value *NewFalseOp = NegVal;
2571 if (AddOp != TI)
2572 std::swap(a&: NewTrueOp, b&: NewFalseOp);
2573 Value *NewSel = Builder.CreateSelect(C: CondVal, True: NewTrueOp, False: NewFalseOp,
2574 Name: SI.getName() + ".p", MDFrom: &SI);
2575
2576 if (SI.getType()->isFPOrFPVectorTy()) {
2577 Instruction *RI =
2578 BinaryOperator::CreateFAdd(V1: SubOp->getOperand(i: 0), V2: NewSel);
2579
2580 FastMathFlags Flags = AddOp->getFastMathFlags();
2581 Flags &= SubOp->getFastMathFlags();
2582 RI->setFastMathFlags(Flags);
2583 return RI;
2584 } else
2585 return BinaryOperator::CreateAdd(V1: SubOp->getOperand(i: 0), V2: NewSel);
2586 }
2587 }
2588 return nullptr;
2589}
2590
2591/// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2592/// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2593/// Along with a number of patterns similar to:
2594/// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2595/// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2596static Instruction *
2597foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
2598 Value *CondVal = SI.getCondition();
2599 Value *TrueVal = SI.getTrueValue();
2600 Value *FalseVal = SI.getFalseValue();
2601
2602 WithOverflowInst *II;
2603 if (!match(V: CondVal, P: m_ExtractValue<1>(V: m_WithOverflowInst(I&: II))) ||
2604 !match(V: FalseVal, P: m_ExtractValue<0>(V: m_Specific(V: II))))
2605 return nullptr;
2606
2607 Value *X = II->getLHS();
2608 Value *Y = II->getRHS();
2609
2610 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
2611 Type *Ty = Limit->getType();
2612
2613 CmpPredicate Pred;
2614 Value *TrueVal, *FalseVal, *Op;
2615 const APInt *C;
2616 if (!match(V: Limit, P: m_Select(C: m_ICmp(Pred, L: m_Value(V&: Op), R: m_APInt(Res&: C)),
2617 L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal))))
2618 return false;
2619
2620 auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
2621 auto IsMinMax = [&](Value *Min, Value *Max) {
2622 APInt MinVal = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
2623 APInt MaxVal = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
2624 return match(V: Min, P: m_SpecificInt(V: MinVal)) &&
2625 match(V: Max, P: m_SpecificInt(V: MaxVal));
2626 };
2627
2628 if (Op != X && Op != Y)
2629 return false;
2630
2631 if (IsAdd) {
2632 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2633 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2634 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2635 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2636 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2637 IsMinMax(TrueVal, FalseVal))
2638 return true;
2639 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2640 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2641 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2642 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2643 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2644 IsMinMax(FalseVal, TrueVal))
2645 return true;
2646 } else {
2647 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2648 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2649 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
2650 IsMinMax(TrueVal, FalseVal))
2651 return true;
2652 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2653 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2654 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
2655 IsMinMax(FalseVal, TrueVal))
2656 return true;
2657 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2658 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2659 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2660 IsMinMax(FalseVal, TrueVal))
2661 return true;
2662 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2663 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2664 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2665 IsMinMax(TrueVal, FalseVal))
2666 return true;
2667 }
2668
2669 return false;
2670 };
2671
2672 Intrinsic::ID NewIntrinsicID;
2673 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
2674 match(V: TrueVal, P: m_AllOnes()))
2675 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2676 NewIntrinsicID = Intrinsic::uadd_sat;
2677 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
2678 match(V: TrueVal, P: m_Zero()))
2679 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2680 NewIntrinsicID = Intrinsic::usub_sat;
2681 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
2682 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
2683 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2684 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2685 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2686 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2687 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2688 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2689 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2690 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2691 NewIntrinsicID = Intrinsic::sadd_sat;
2692 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
2693 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
2694 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2695 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2696 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2697 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2698 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2699 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2700 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2701 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2702 NewIntrinsicID = Intrinsic::ssub_sat;
2703 else
2704 return nullptr;
2705
2706 Function *F = Intrinsic::getOrInsertDeclaration(M: SI.getModule(),
2707 id: NewIntrinsicID, OverloadTys: SI.getType());
2708 return CallInst::Create(Func: F, Args: {X, Y});
2709}
2710
2711Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
2712 Constant *C;
2713 if (!match(V: Sel.getTrueValue(), P: m_Constant(C)) &&
2714 !match(V: Sel.getFalseValue(), P: m_Constant(C)))
2715 return nullptr;
2716
2717 Instruction *ExtInst;
2718 if (!match(V: Sel.getTrueValue(), P: m_Instruction(I&: ExtInst)) &&
2719 !match(V: Sel.getFalseValue(), P: m_Instruction(I&: ExtInst)))
2720 return nullptr;
2721
2722 auto ExtOpcode = ExtInst->getOpcode();
2723 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
2724 return nullptr;
2725
2726 // If we are extending from a boolean type or if we can create a select that
2727 // has the same size operands as its condition, try to narrow the select.
2728 Value *X = ExtInst->getOperand(i: 0);
2729 Type *SmallType = X->getType();
2730 Value *Cond = Sel.getCondition();
2731 if (!SmallType->isIntOrIntVectorTy(BitWidth: 1) &&
2732 (!isa<CmpInst, TruncInst>(Val: Cond) ||
2733 cast<Instruction>(Val: Cond)->getOperand(i: 0)->getType() != SmallType))
2734 return nullptr;
2735
2736 // If the constant is the same after truncation to the smaller type and
2737 // extension to the original type, we can narrow the select.
2738 Type *SelType = Sel.getType();
2739 Constant *TruncC = getLosslessInvCast(C, InvCastTo: SmallType, CastOp: ExtOpcode, DL);
2740 if (TruncC && ExtInst->hasOneUse()) {
2741 Value *TruncCVal = cast<Value>(Val: TruncC);
2742 if (ExtInst == Sel.getFalseValue())
2743 std::swap(a&: X, b&: TruncCVal);
2744
2745 // select Cond, (ext X), C --> ext(select Cond, X, C')
2746 // select Cond, C, (ext X) --> ext(select Cond, C', X)
2747 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: TruncCVal, Name: "narrow", MDFrom: &Sel);
2748 return CastInst::Create(Instruction::CastOps(ExtOpcode), S: NewSel, Ty: SelType);
2749 }
2750
2751 return nullptr;
2752}
2753
2754/// Try to transform a vector select with a constant condition vector into a
2755/// shuffle for easier combining with other shuffles and insert/extract.
2756static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2757 Value *CondVal = SI.getCondition();
2758 Constant *CondC;
2759 auto *CondValTy = dyn_cast<FixedVectorType>(Val: CondVal->getType());
2760 if (!CondValTy || !match(V: CondVal, P: m_Constant(C&: CondC)))
2761 return nullptr;
2762
2763 unsigned NumElts = CondValTy->getNumElements();
2764 SmallVector<int, 16> Mask;
2765 Mask.reserve(N: NumElts);
2766 for (unsigned i = 0; i != NumElts; ++i) {
2767 Constant *Elt = CondC->getAggregateElement(Elt: i);
2768 if (!Elt)
2769 return nullptr;
2770
2771 if (Elt->isOneValue()) {
2772 // If the select condition element is true, choose from the 1st vector.
2773 Mask.push_back(Elt: i);
2774 } else if (Elt->isNullValue()) {
2775 // If the select condition element is false, choose from the 2nd vector.
2776 Mask.push_back(Elt: i + NumElts);
2777 } else if (isa<UndefValue>(Val: Elt)) {
2778 // Undef in a select condition (choose one of the operands) does not mean
2779 // the same thing as undef in a shuffle mask (any value is acceptable), so
2780 // give up.
2781 return nullptr;
2782 } else {
2783 // Bail out on a constant expression.
2784 return nullptr;
2785 }
2786 }
2787
2788 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2789}
2790
2791/// If we have a select of vectors with a scalar condition, try to convert that
2792/// to a vector select by splatting the condition. A splat may get folded with
2793/// other operations in IR and having all operands of a select be vector types
2794/// is likely better for vector codegen.
2795static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2796 InstCombinerImpl &IC) {
2797 auto *Ty = dyn_cast<VectorType>(Val: Sel.getType());
2798 if (!Ty)
2799 return nullptr;
2800
2801 // We can replace a single-use extract with constant index.
2802 Value *Cond = Sel.getCondition();
2803 if (!match(V: Cond, P: m_OneUse(SubPattern: m_ExtractElt(Val: m_Value(), Idx: m_ConstantInt()))))
2804 return nullptr;
2805
2806 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2807 // Splatting the extracted condition reduces code (we could directly create a
2808 // splat shuffle of the source vector to eliminate the intermediate step).
2809 return IC.replaceOperand(
2810 I&: Sel, OpNum: 0, V: IC.Builder.CreateVectorSplat(EC: Ty->getElementCount(), V: Cond));
2811}
2812
2813/// Reuse bitcasted operands between a compare and select:
2814/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2815/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2816static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2817 InstCombiner::BuilderTy &Builder) {
2818 Value *Cond = Sel.getCondition();
2819 Value *TVal = Sel.getTrueValue();
2820 Value *FVal = Sel.getFalseValue();
2821
2822 CmpPredicate Pred;
2823 Value *A, *B;
2824 if (!match(V: Cond, P: m_Cmp(Pred, L: m_Value(V&: A), R: m_Value(V&: B))))
2825 return nullptr;
2826
2827 // The select condition is a compare instruction. If the select's true/false
2828 // values are already the same as the compare operands, there's nothing to do.
2829 if (TVal == A || TVal == B || FVal == A || FVal == B)
2830 return nullptr;
2831
2832 Value *C, *D;
2833 if (!match(V: A, P: m_BitCast(Op: m_Value(V&: C))) || !match(V: B, P: m_BitCast(Op: m_Value(V&: D))))
2834 return nullptr;
2835
2836 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2837 Value *TSrc, *FSrc;
2838 if (!match(V: TVal, P: m_BitCast(Op: m_Value(V&: TSrc))) ||
2839 !match(V: FVal, P: m_BitCast(Op: m_Value(V&: FSrc))))
2840 return nullptr;
2841
2842 // If the select true/false values are *different bitcasts* of the same source
2843 // operands, make the select operands the same as the compare operands and
2844 // cast the result. This is the canonical select form for min/max.
2845 Value *NewSel;
2846 if (TSrc == C && FSrc == D) {
2847 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2848 // bitcast (select (cmp A, B), A, B)
2849 NewSel = Builder.CreateSelect(C: Cond, True: A, False: B, Name: "", MDFrom: &Sel);
2850 } else if (TSrc == D && FSrc == C) {
2851 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2852 // bitcast (select (cmp A, B), B, A)
2853 NewSel = Builder.CreateSelect(C: Cond, True: B, False: A, Name: "", MDFrom: &Sel);
2854 } else {
2855 return nullptr;
2856 }
2857 return new BitCastInst(NewSel, Sel.getType());
2858}
2859
2860/// Try to eliminate select instructions that test the returned flag of cmpxchg
2861/// instructions.
2862///
2863/// If a select instruction tests the returned flag of a cmpxchg instruction and
2864/// selects between the returned value of the cmpxchg instruction its compare
2865/// operand, the result of the select will always be equal to its false value.
2866/// For example:
2867///
2868/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2869/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2870/// %success = extractvalue { i64, i1 } %cmpxchg, 1
2871/// %sel = select i1 %success, i64 %compare, i64 %val
2872/// ret i64 %sel
2873///
2874/// The returned value of the cmpxchg instruction (%val) is the original value
2875/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %val
2876/// must have been equal to %compare. Thus, the result of the select is always
2877/// equal to %val, and the code can be simplified to:
2878///
2879/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2880/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2881/// ret i64 %val
2882///
2883static Value *foldSelectCmpXchg(SelectInst &SI) {
2884 // A helper that determines if V is an extractvalue instruction whose
2885 // aggregate operand is a cmpxchg instruction and whose single index is equal
2886 // to I. If such conditions are true, the helper returns the cmpxchg
2887 // instruction; otherwise, a nullptr is returned.
2888 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2889 // When extracting the value loaded by a cmpxchg, allow peeking through a
2890 // bitcast. These are inserted for floating-point cmpxchg, for example:
2891 // %bc = bitcast float %compare to i32
2892 // %cmpxchg = cmpxchg ptr %ptr, i32 %bc, i32 %new_value seq_cst seq_cst
2893 // %val = extractvalue { i32, i1 } %cmpxchg, 0
2894 // %success = extractvalue { i32, i1 } %cmpxchg, 1
2895 // %val.bc = bitcast i32 %val to float
2896 // %sel = select i1 %success, float %compare, float %val.bc
2897 if (auto *BI = dyn_cast<BitCastInst>(Val: V); BI && I == 0)
2898 V = BI->getOperand(i_nocapture: 0);
2899 auto *Extract = dyn_cast<ExtractValueInst>(Val: V);
2900 if (!Extract)
2901 return nullptr;
2902 if (Extract->getIndices()[0] != I)
2903 return nullptr;
2904 return dyn_cast<AtomicCmpXchgInst>(Val: Extract->getAggregateOperand());
2905 };
2906
2907 // Check if the compare value of a cmpxchg matches another value.
2908 auto isCompareSameAsValue = [](Value *CmpVal, Value *SelVal) {
2909 // The values match if they are the same or %CmpVal = bitcast %SelVal (see
2910 // above).
2911 if (CmpVal == SelVal || match(V: CmpVal, P: m_BitCast(Op: m_Specific(V: SelVal))))
2912 return true;
2913 // For FP constants, the value may have been bitcast to Int directly.
2914 auto *IntC = dyn_cast<ConstantInt>(Val: CmpVal);
2915 auto *FpC = dyn_cast<ConstantFP>(Val: SelVal);
2916 return IntC && FpC && IntC->getValue() == FpC->getValue().bitcastToAPInt();
2917 };
2918
2919 // If the select has a single user, and this user is a select instruction that
2920 // we can simplify, skip the cmpxchg simplification for now.
2921 if (SI.hasOneUse())
2922 if (auto *Select = dyn_cast<SelectInst>(Val: SI.user_back()))
2923 if (Select->getCondition() == SI.getCondition())
2924 if (Select->getFalseValue() == SI.getTrueValue() ||
2925 Select->getTrueValue() == SI.getFalseValue())
2926 return nullptr;
2927
2928 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2929 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2930 if (!CmpXchg)
2931 return nullptr;
2932
2933 // Check the true value case: The true value of the select is the returned
2934 // value of the same cmpxchg used by the condition, and the false value is the
2935 // cmpxchg instruction's compare operand.
2936 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2937 if (X == CmpXchg &&
2938 isCompareSameAsValue(X->getCompareOperand(), SI.getFalseValue()))
2939 return SI.getFalseValue();
2940
2941 // Check the false value case: The false value of the select is the returned
2942 // value of the same cmpxchg used by the condition, and the true value is the
2943 // cmpxchg instruction's compare operand.
2944 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2945 if (X == CmpXchg &&
2946 isCompareSameAsValue(X->getCompareOperand(), SI.getTrueValue()))
2947 return SI.getFalseValue();
2948
2949 return nullptr;
2950}
2951
2952/// Try to reduce a funnel/rotate pattern that includes a compare and select
2953/// into a funnel shift intrinsic. Example:
2954/// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2955/// --> call llvm.fshl.i32(a, a, b)
2956/// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
2957/// --> call llvm.fshl.i32(a, b, c)
2958/// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
2959/// --> call llvm.fshr.i32(a, b, c)
2960static Instruction *foldSelectFunnelShift(SelectInst &Sel,
2961 InstCombiner::BuilderTy &Builder) {
2962 // This must be a power-of-2 type for a bitmasking transform to be valid.
2963 unsigned Width = Sel.getType()->getScalarSizeInBits();
2964 if (!isPowerOf2_32(Value: Width))
2965 return nullptr;
2966
2967 BinaryOperator *Or0, *Or1;
2968 if (!match(V: Sel.getFalseValue(), P: m_OneUse(SubPattern: m_Or(L: m_BinOp(I&: Or0), R: m_BinOp(I&: Or1)))))
2969 return nullptr;
2970
2971 Value *SV0, *SV1, *SA0, *SA1;
2972 if (!match(V: Or0, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: SV0),
2973 R: m_ZExtOrSelf(Op: m_Value(V&: SA0))))) ||
2974 !match(V: Or1, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: SV1),
2975 R: m_ZExtOrSelf(Op: m_Value(V&: SA1))))) ||
2976 Or0->getOpcode() == Or1->getOpcode())
2977 return nullptr;
2978
2979 // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
2980 if (Or0->getOpcode() == BinaryOperator::LShr) {
2981 std::swap(a&: Or0, b&: Or1);
2982 std::swap(a&: SV0, b&: SV1);
2983 std::swap(a&: SA0, b&: SA1);
2984 }
2985 assert(Or0->getOpcode() == BinaryOperator::Shl &&
2986 Or1->getOpcode() == BinaryOperator::LShr &&
2987 "Illegal or(shift,shift) pair");
2988
2989 // Check the shift amounts to see if they are an opposite pair.
2990 Value *ShAmt;
2991 if (match(V: SA1, P: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: Width), R: m_Specific(V: SA0)))))
2992 ShAmt = SA0;
2993 else if (match(V: SA0, P: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: Width), R: m_Specific(V: SA1)))))
2994 ShAmt = SA1;
2995 else
2996 return nullptr;
2997
2998 // We should now have this pattern:
2999 // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
3000 // The false value of the select must be a funnel-shift of the true value:
3001 // IsFShl -> TVal must be SV0 else TVal must be SV1.
3002 bool IsFshl = (ShAmt == SA0);
3003 Value *TVal = Sel.getTrueValue();
3004 if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
3005 return nullptr;
3006
3007 // Finally, see if the select is filtering out a shift-by-zero.
3008 Value *Cond = Sel.getCondition();
3009 if (!match(V: Cond, P: m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: ShAmt),
3010 R: m_ZeroInt()))))
3011 return nullptr;
3012
3013 // If this is not a rotate then the select was blocking poison from the
3014 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
3015 if (SV0 != SV1) {
3016 if (IsFshl && !llvm::isGuaranteedNotToBePoison(V: SV1))
3017 SV1 = Builder.CreateFreeze(V: SV1);
3018 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(V: SV0))
3019 SV0 = Builder.CreateFreeze(V: SV0);
3020 }
3021
3022 // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
3023 // Convert to funnel shift intrinsic.
3024 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
3025 Function *F =
3026 Intrinsic::getOrInsertDeclaration(M: Sel.getModule(), id: IID, OverloadTys: Sel.getType());
3027 ShAmt = Builder.CreateZExt(V: ShAmt, DestTy: Sel.getType());
3028 return CallInst::Create(Func: F, Args: { SV0, SV1, ShAmt });
3029}
3030
3031static Instruction *foldSelectToCopysign(SelectInst &Sel,
3032 InstCombiner::BuilderTy &Builder) {
3033 Value *Cond = Sel.getCondition();
3034 Value *TVal = Sel.getTrueValue();
3035 Value *FVal = Sel.getFalseValue();
3036 Type *SelType = Sel.getType();
3037
3038 // Match select ?, TC, FC where the constants are equal but negated.
3039 // TODO: Generalize to handle a negated variable operand?
3040 const APFloat *TC, *FC;
3041 if (!match(V: TVal, P: m_APFloatAllowPoison(Res&: TC)) ||
3042 !match(V: FVal, P: m_APFloatAllowPoison(Res&: FC)) ||
3043 !abs(X: *TC).bitwiseIsEqual(RHS: abs(X: *FC)))
3044 return nullptr;
3045
3046 assert(TC != FC && "Expected equal select arms to simplify");
3047
3048 Value *X;
3049 const APInt *C;
3050 bool IsTrueIfSignSet;
3051 CmpPredicate Pred;
3052 if (!match(V: Cond, P: m_OneUse(SubPattern: m_ICmp(Pred, L: m_ElementWiseBitCast(Op: m_Value(V&: X)),
3053 R: m_APInt(Res&: C)))) ||
3054 !isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: IsTrueIfSignSet) || X->getType() != SelType)
3055 return nullptr;
3056
3057 // If needed, negate the value that will be the sign argument of the copysign:
3058 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
3059 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
3060 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
3061 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
3062 // Note: FMF from the select can not be propagated to the new instructions.
3063 if (IsTrueIfSignSet ^ TC->isNegative())
3064 X = Builder.CreateFNeg(V: X);
3065
3066 // Canonicalize the magnitude argument as the positive constant since we do
3067 // not care about its sign.
3068 Value *MagArg = ConstantFP::get(Ty: SelType, V: abs(X: *TC));
3069 Function *F = Intrinsic::getOrInsertDeclaration(
3070 M: Sel.getModule(), id: Intrinsic::copysign, OverloadTys: Sel.getType());
3071 return CallInst::Create(Func: F, Args: { MagArg, X });
3072}
3073
3074Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
3075 if (!isa<VectorType>(Val: Sel.getType()))
3076 return nullptr;
3077
3078 Value *Cond = Sel.getCondition();
3079 Value *TVal = Sel.getTrueValue();
3080 Value *FVal = Sel.getFalseValue();
3081 Value *C, *X, *Y;
3082
3083 if (match(V: Cond, P: m_VecReverse(Op0: m_Value(V&: C)))) {
3084 auto createSelReverse = [&](Value *C, Value *X, Value *Y) {
3085 Value *V = Builder.CreateSelect(C, True: X, False: Y, Name: Sel.getName(), MDFrom: &Sel);
3086 if (auto *I = dyn_cast<Instruction>(Val: V))
3087 I->copyIRFlags(V: &Sel);
3088 Module *M = Sel.getModule();
3089 Function *F = Intrinsic::getOrInsertDeclaration(
3090 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
3091 return CallInst::Create(Func: F, Args: V);
3092 };
3093
3094 if (match(V: TVal, P: m_VecReverse(Op0: m_Value(V&: X)))) {
3095 // select rev(C), rev(X), rev(Y) --> rev(select C, X, Y)
3096 if (match(V: FVal, P: m_VecReverse(Op0: m_Value(V&: Y))) &&
3097 (Cond->hasOneUse() || TVal->hasOneUse() || FVal->hasOneUse()))
3098 return createSelReverse(C, X, Y);
3099
3100 // select rev(C), rev(X), FValSplat --> rev(select C, X, FValSplat)
3101 if ((Cond->hasOneUse() || TVal->hasOneUse()) && isSplatValue(V: FVal))
3102 return createSelReverse(C, X, FVal);
3103 }
3104 // select rev(C), TValSplat, rev(Y) --> rev(select C, TValSplat, Y)
3105 else if (isSplatValue(V: TVal) && match(V: FVal, P: m_VecReverse(Op0: m_Value(V&: Y))) &&
3106 (Cond->hasOneUse() || FVal->hasOneUse()))
3107 return createSelReverse(C, TVal, Y);
3108 }
3109
3110 auto *VecTy = dyn_cast<FixedVectorType>(Val: Sel.getType());
3111 if (!VecTy)
3112 return nullptr;
3113
3114 unsigned NumElts = VecTy->getNumElements();
3115 APInt PoisonElts(NumElts, 0);
3116 APInt AllOnesEltMask(APInt::getAllOnes(numBits: NumElts));
3117 if (Value *V = SimplifyDemandedVectorElts(V: &Sel, DemandedElts: AllOnesEltMask, PoisonElts)) {
3118 if (V != &Sel)
3119 return replaceInstUsesWith(I&: Sel, V);
3120 return &Sel;
3121 }
3122
3123 // A select of a "select shuffle" with a common operand can be rearranged
3124 // to select followed by "select shuffle". Because of poison, this only works
3125 // in the case of a shuffle with no undefined mask elements.
3126 ArrayRef<int> Mask;
3127 if (match(V: TVal, P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: X), v2: m_Value(V&: Y), mask: m_Mask(Mask)))) &&
3128 !is_contained(Range&: Mask, Element: PoisonMaskElem) &&
3129 cast<ShuffleVectorInst>(Val: TVal)->isSelect()) {
3130 if (X == FVal) {
3131 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
3132 Value *NewSel = Builder.CreateSelect(C: Cond, True: Y, False: X, Name: "sel", MDFrom: &Sel);
3133 return new ShuffleVectorInst(X, NewSel, Mask);
3134 }
3135 if (Y == FVal) {
3136 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
3137 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: Y, Name: "sel", MDFrom: &Sel);
3138 return new ShuffleVectorInst(NewSel, Y, Mask);
3139 }
3140 }
3141 if (match(V: FVal, P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: X), v2: m_Value(V&: Y), mask: m_Mask(Mask)))) &&
3142 !is_contained(Range&: Mask, Element: PoisonMaskElem) &&
3143 cast<ShuffleVectorInst>(Val: FVal)->isSelect()) {
3144 if (X == TVal) {
3145 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
3146 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: Y, Name: "sel", MDFrom: &Sel);
3147 return new ShuffleVectorInst(X, NewSel, Mask);
3148 }
3149 if (Y == TVal) {
3150 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
3151 Value *NewSel = Builder.CreateSelect(C: Cond, True: Y, False: X, Name: "sel", MDFrom: &Sel);
3152 return new ShuffleVectorInst(NewSel, Y, Mask);
3153 }
3154 }
3155
3156 return nullptr;
3157}
3158
3159static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
3160 const DominatorTree &DT,
3161 InstCombiner::BuilderTy &Builder) {
3162 // Find the block's immediate dominator that ends with a conditional branch
3163 // that matches select's condition (maybe inverted).
3164 auto *IDomNode = DT[BB]->getIDom();
3165 if (!IDomNode)
3166 return nullptr;
3167 BasicBlock *IDom = IDomNode->getBlock();
3168
3169 Value *Cond = Sel.getCondition();
3170 Value *IfTrue, *IfFalse;
3171 BasicBlock *TrueSucc, *FalseSucc;
3172 if (match(V: IDom->getTerminator(),
3173 P: m_Br(C: m_Specific(V: Cond), T: m_BasicBlock(V&: TrueSucc),
3174 F: m_BasicBlock(V&: FalseSucc)))) {
3175 IfTrue = Sel.getTrueValue();
3176 IfFalse = Sel.getFalseValue();
3177 } else if (match(V: IDom->getTerminator(),
3178 P: m_Br(C: m_Not(V: m_Specific(V: Cond)), T: m_BasicBlock(V&: TrueSucc),
3179 F: m_BasicBlock(V&: FalseSucc)))) {
3180 IfTrue = Sel.getFalseValue();
3181 IfFalse = Sel.getTrueValue();
3182 } else
3183 return nullptr;
3184
3185 // Make sure the branches are actually different.
3186 if (TrueSucc == FalseSucc)
3187 return nullptr;
3188
3189 // We want to replace select %cond, %a, %b with a phi that takes value %a
3190 // for all incoming edges that are dominated by condition `%cond == true`,
3191 // and value %b for edges dominated by condition `%cond == false`. If %a
3192 // or %b are also phis from the same basic block, we can go further and take
3193 // their incoming values from the corresponding blocks.
3194 BasicBlockEdge TrueEdge(IDom, TrueSucc);
3195 BasicBlockEdge FalseEdge(IDom, FalseSucc);
3196 DenseMap<BasicBlock *, Value *> Inputs;
3197 for (auto *Pred : predecessors(BB)) {
3198 // Check implication.
3199 BasicBlockEdge Incoming(Pred, BB);
3200 if (DT.dominates(BBE1: TrueEdge, BBE2: Incoming))
3201 Inputs[Pred] = IfTrue->DoPHITranslation(CurBB: BB, PredBB: Pred);
3202 else if (DT.dominates(BBE1: FalseEdge, BBE2: Incoming))
3203 Inputs[Pred] = IfFalse->DoPHITranslation(CurBB: BB, PredBB: Pred);
3204 else
3205 return nullptr;
3206 // Check availability.
3207 if (auto *Insn = dyn_cast<Instruction>(Val: Inputs[Pred]))
3208 if (!DT.dominates(Def: Insn, User: Pred->getTerminator()))
3209 return nullptr;
3210 }
3211
3212 Builder.SetInsertPoint(TheBB: BB, IP: BB->begin());
3213 auto *PN = Builder.CreatePHI(Ty: Sel.getType(), NumReservedValues: Inputs.size());
3214 for (auto *Pred : predecessors(BB))
3215 PN->addIncoming(V: Inputs[Pred], BB: Pred);
3216 PN->takeName(V: &Sel);
3217 return PN;
3218}
3219
3220static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
3221 InstCombiner::BuilderTy &Builder) {
3222 // Try to replace this select with Phi in one of these blocks.
3223 SmallSetVector<BasicBlock *, 4> CandidateBlocks;
3224 CandidateBlocks.insert(X: Sel.getParent());
3225 for (Value *V : Sel.operands())
3226 if (auto *I = dyn_cast<Instruction>(Val: V))
3227 CandidateBlocks.insert(X: I->getParent());
3228
3229 for (BasicBlock *BB : CandidateBlocks)
3230 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
3231 return PN;
3232 return nullptr;
3233}
3234
3235/// Tries to reduce a pattern that arises when calculating the remainder of the
3236/// Euclidean division. When the divisor is a power of two and is guaranteed not
3237/// to be negative, a signed remainder can be folded with a bitwise and.
3238///
3239/// (x % n) < 0 ? (x % n) + n : (x % n)
3240/// -> x & (n - 1)
3241static Instruction *foldSelectWithSRem(SelectInst &SI, InstCombinerImpl &IC,
3242 IRBuilderBase &Builder) {
3243 Value *CondVal = SI.getCondition();
3244 Value *TrueVal = SI.getTrueValue();
3245 Value *FalseVal = SI.getFalseValue();
3246
3247 CmpPredicate Pred;
3248 Value *Op, *RemRes, *Remainder;
3249 const APInt *C;
3250 bool TrueIfSigned = false;
3251
3252 if (!(match(V: CondVal, P: m_ICmp(Pred, L: m_Value(V&: RemRes), R: m_APInt(Res&: C))) &&
3253 isSignBitCheck(Pred, RHS: *C, TrueIfSigned)))
3254 return nullptr;
3255
3256 // If the sign bit is not set, we have a SGE/SGT comparison, and the operands
3257 // of the select are inverted.
3258 if (!TrueIfSigned)
3259 std::swap(a&: TrueVal, b&: FalseVal);
3260
3261 auto FoldToBitwiseAnd = [&](Value *Remainder) -> Instruction * {
3262 Value *Add = Builder.CreateAdd(
3263 LHS: Remainder, RHS: Constant::getAllOnesValue(Ty: RemRes->getType()));
3264 return BinaryOperator::CreateAnd(V1: Op, V2: Add);
3265 };
3266
3267 // Match the general case:
3268 // %rem = srem i32 %x, %n
3269 // %cnd = icmp slt i32 %rem, 0
3270 // %add = add i32 %rem, %n
3271 // %sel = select i1 %cnd, i32 %add, i32 %rem
3272 if (match(V: TrueVal, P: m_c_Add(L: m_Specific(V: RemRes), R: m_Value(V&: Remainder))) &&
3273 match(V: RemRes, P: m_SRem(L: m_Value(V&: Op), R: m_Specific(V: Remainder))) &&
3274 IC.isKnownToBeAPowerOfTwo(V: Remainder, /*OrZero=*/true) &&
3275 FalseVal == RemRes)
3276 return FoldToBitwiseAnd(Remainder);
3277
3278 // Match the case where the one arm has been replaced by constant 1:
3279 // %rem = srem i32 %n, 2
3280 // %cnd = icmp slt i32 %rem, 0
3281 // %sel = select i1 %cnd, i32 1, i32 %rem
3282 if (match(V: TrueVal, P: m_One()) &&
3283 match(V: RemRes, P: m_SRem(L: m_Value(V&: Op), R: m_SpecificInt(V: 2))) &&
3284 FalseVal == RemRes)
3285 return FoldToBitwiseAnd(ConstantInt::get(Ty: RemRes->getType(), V: 2));
3286
3287 return nullptr;
3288}
3289
3290/// Given that \p CondVal is known to be \p CondIsTrue, try to simplify \p SI.
3291static Value *simplifyNestedSelectsUsingImpliedCond(SelectInst &SI,
3292 Value *CondVal,
3293 bool CondIsTrue,
3294 const DataLayout &DL) {
3295 Value *InnerCondVal = SI.getCondition();
3296 Value *InnerTrueVal = SI.getTrueValue();
3297 Value *InnerFalseVal = SI.getFalseValue();
3298 assert(CondVal->getType() == InnerCondVal->getType() &&
3299 "The type of inner condition must match with the outer.");
3300 if (auto Implied = isImpliedCondition(LHS: CondVal, RHS: InnerCondVal, DL, LHSIsTrue: CondIsTrue))
3301 return *Implied ? InnerTrueVal : InnerFalseVal;
3302 return nullptr;
3303}
3304
3305Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
3306 SelectInst &SI,
3307 bool IsAnd) {
3308 assert(Op->getType()->isIntOrIntVectorTy(1) &&
3309 "Op must be either i1 or vector of i1.");
3310 if (SI.getCondition()->getType() != Op->getType())
3311 return nullptr;
3312 if (Value *V = simplifyNestedSelectsUsingImpliedCond(SI, CondVal: Op, CondIsTrue: IsAnd, DL))
3313 return createSelectInstWithUnknownProfile(
3314 C: Op, S1: IsAnd ? V : ConstantInt::getTrue(Ty: Op->getType()),
3315 S2: IsAnd ? ConstantInt::getFalse(Ty: Op->getType()) : V);
3316 return nullptr;
3317}
3318
3319// Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
3320// fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
3321static Instruction *foldSelectWithFCmpToFabs(SelectInst &SI,
3322 InstCombinerImpl &IC) {
3323 Value *CondVal = SI.getCondition();
3324
3325 bool ChangedFMF = false;
3326 for (bool Swap : {false, true}) {
3327 Value *TrueVal = SI.getTrueValue();
3328 Value *X = SI.getFalseValue();
3329 CmpPredicate Pred;
3330
3331 if (Swap)
3332 std::swap(a&: TrueVal, b&: X);
3333
3334 if (!match(V: CondVal, P: m_FCmp(Pred, L: m_Specific(V: X), R: m_AnyZeroFP())))
3335 continue;
3336
3337 // fold (X <= +/-0.0) ? (0.0 - X) : X to fabs(X), when 'Swap' is false
3338 // fold (X > +/-0.0) ? X : (0.0 - X) to fabs(X), when 'Swap' is true
3339 // Note: We require "nnan" for this fold because fcmp ignores the signbit
3340 // of NAN, but IEEE-754 specifies the signbit of NAN values with
3341 // fneg/fabs operations.
3342 if (match(V: TrueVal, P: m_FSub(L: m_PosZeroFP(), R: m_Specific(V: X))) &&
3343 (cast<FPMathOperator>(Val: CondVal)->hasNoNaNs() || SI.hasNoNaNs() ||
3344 (SI.hasOneUse() && canIgnoreSignBitOfNaN(U: *SI.use_begin())) ||
3345 isKnownNeverNaN(V: X, SQ: IC.getSimplifyQuery().getWithInstruction(
3346 I: cast<Instruction>(Val: CondVal))))) {
3347 if (!Swap && (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
3348 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3349 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3350 }
3351 if (Swap && (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
3352 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3353 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3354 }
3355 }
3356
3357 if (!match(V: TrueVal, P: m_FNeg(X: m_Specific(V: X))))
3358 return nullptr;
3359
3360 // Forward-propagate nnan and ninf from the fcmp to the select.
3361 // If all inputs are not those values, then the select is not either.
3362 // Note: nsz is defined differently, so it may not be correct to propagate.
3363 FastMathFlags FMF = cast<FPMathOperator>(Val: CondVal)->getFastMathFlags();
3364 if (FMF.noNaNs() && !SI.hasNoNaNs()) {
3365 SI.setHasNoNaNs(true);
3366 ChangedFMF = true;
3367 }
3368 if (FMF.noInfs() && !SI.hasNoInfs()) {
3369 SI.setHasNoInfs(true);
3370 ChangedFMF = true;
3371 }
3372 // Forward-propagate nnan from the fneg to the select.
3373 // The nnan flag can be propagated iff fneg is selected when X is NaN.
3374 if (!SI.hasNoNaNs() && cast<FPMathOperator>(Val: TrueVal)->hasNoNaNs() &&
3375 (Swap ? FCmpInst::isOrdered(predicate: Pred) : FCmpInst::isUnordered(predicate: Pred))) {
3376 SI.setHasNoNaNs(true);
3377 ChangedFMF = true;
3378 }
3379
3380 // With nsz, when 'Swap' is false:
3381 // fold (X < +/-0.0) ? -X : X or (X <= +/-0.0) ? -X : X to fabs(X)
3382 // fold (X > +/-0.0) ? -X : X or (X >= +/-0.0) ? -X : X to -fabs(x)
3383 // when 'Swap' is true:
3384 // fold (X > +/-0.0) ? X : -X or (X >= +/-0.0) ? X : -X to fabs(X)
3385 // fold (X < +/-0.0) ? X : -X or (X <= +/-0.0) ? X : -X to -fabs(X)
3386 //
3387 // Note: We require "nnan" for this fold because fcmp ignores the signbit
3388 // of NAN, but IEEE-754 specifies the signbit of NAN values with
3389 // fneg/fabs operations.
3390 if (!SI.hasNoSignedZeros() &&
3391 (!SI.hasOneUse() || !canIgnoreSignBitOfZero(U: *SI.use_begin())))
3392 return nullptr;
3393 if (!SI.hasNoNaNs() &&
3394 (!SI.hasOneUse() || !canIgnoreSignBitOfNaN(U: *SI.use_begin())))
3395 return nullptr;
3396
3397 if (Swap)
3398 Pred = FCmpInst::getSwappedPredicate(pred: Pred);
3399
3400 bool IsLTOrLE = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
3401 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE;
3402 bool IsGTOrGE = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
3403 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE;
3404
3405 if (IsLTOrLE) {
3406 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3407 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3408 }
3409 if (IsGTOrGE) {
3410 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3411 Instruction *NewFNeg = UnaryOperator::CreateFNeg(V: Fabs);
3412 NewFNeg->setFastMathFlags(SI.getFastMathFlags());
3413 return NewFNeg;
3414 }
3415 }
3416
3417 // Match select with (icmp slt (bitcast X to int), 0)
3418 // or (icmp sgt (bitcast X to int), -1)
3419
3420 for (bool Swap : {false, true}) {
3421 Value *TrueVal = SI.getTrueValue();
3422 Value *X = SI.getFalseValue();
3423
3424 if (Swap)
3425 std::swap(a&: TrueVal, b&: X);
3426
3427 CmpPredicate Pred;
3428 const APInt *C;
3429 bool TrueIfSigned;
3430 if (!match(V: CondVal,
3431 P: m_ICmp(Pred, L: m_ElementWiseBitCast(Op: m_Specific(V: X)), R: m_APInt(Res&: C))) ||
3432 !isSignBitCheck(Pred, RHS: *C, TrueIfSigned))
3433 continue;
3434 if (!match(V: TrueVal, P: m_FNeg(X: m_Specific(V: X))))
3435 return nullptr;
3436 if (Swap == TrueIfSigned && !CondVal->hasOneUse() && !TrueVal->hasOneUse())
3437 return nullptr;
3438
3439 // Fold (IsNeg ? -X : X) or (!IsNeg ? X : -X) to fabs(X)
3440 // Fold (IsNeg ? X : -X) or (!IsNeg ? -X : X) to -fabs(X)
3441 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3442 if (Swap != TrueIfSigned)
3443 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3444 return UnaryOperator::CreateFNegFMF(Op: Fabs, FMFSource: &SI);
3445 }
3446
3447 return ChangedFMF ? &SI : nullptr;
3448}
3449
3450// Fold a select of an ordered fcmp using fabs of a NaN-scrubbed value:
3451// %s = select i1 (isnotnan T %x), T %x, T %y
3452// %a = call T @llvm.fabs.T(T %s)
3453// %c = fcmp <ordered-pred> T %a, %k
3454// %r = select i1 %c, T %s, T %y
3455// =>
3456// %a2 = call T @llvm.fabs.T(T %x)
3457// %c2 = fcmp <ordered-pred> T %a2, %k
3458// %r2 = select i1 %c2, T %x, T %y
3459static Instruction *
3460foldSelectOfOrderedFAbsCmpOfNaNScrubbedValue(SelectInst &SI,
3461 InstCombinerImpl &IC) {
3462 Instruction *OuterCmpI;
3463 Value *Cmp0, *Cmp1;
3464 if (!match(V: SI.getCondition(),
3465 P: m_OneUse(SubPattern: m_Instruction(I&: OuterCmpI,
3466 P: m_FCmp(L: m_Value(V&: Cmp0), R: m_Value(V&: Cmp1))))))
3467 return nullptr;
3468
3469 auto *OuterCmp = cast<FCmpInst>(Val: OuterCmpI);
3470 CmpInst::Predicate Pred = OuterCmp->getPredicate();
3471 if (!FCmpInst::isOrdered(predicate: Pred))
3472 return nullptr;
3473
3474 Value *Y = SI.getFalseValue();
3475 Value *InnerSel = SI.getTrueValue();
3476
3477 // Match a select that returns X when X is not NaN, and Y otherwise:
3478 // select (fcmp ord X, 0.0), X, Y
3479 Value *X;
3480 if (!match(V: InnerSel,
3481 P: m_Select(C: m_OneUse(SubPattern: m_SpecificFCmp(MatchPred: FCmpInst::FCMP_ORD, L: m_Value(V&: X),
3482 R: m_AnyZeroFP())),
3483 L: m_Deferred(V: X), R: m_Specific(V: Y))))
3484 return nullptr;
3485
3486 Instruction *FAbsI;
3487 auto MatchFAbsOfInnerSel = [&](Value *V) {
3488 return match(V,
3489 P: m_OneUse(SubPattern: m_Instruction(I&: FAbsI, P: m_FAbs(Op0: m_Specific(V: InnerSel)))));
3490 };
3491
3492 if (!MatchFAbsOfInnerSel(Cmp0)) {
3493 if (!MatchFAbsOfInnerSel(Cmp1))
3494 return nullptr;
3495
3496 std::swap(a&: Cmp0, b&: Cmp1);
3497 Pred = CmpInst::getSwappedPredicate(pred: Pred);
3498 }
3499
3500 FastMathFlags FAbsFMF = FAbsI->getFastMathFlags();
3501 FastMathFlags CmpFMF = OuterCmp->getFastMathFlags();
3502
3503 FastMathFlags CommonRewriteFMF =
3504 FastMathFlags::intersectRewrite(LHS: FAbsFMF, RHS: CmpFMF);
3505
3506 // unionValue with FastMathFlags() drops all rewriter based flags
3507 FastMathFlags NewFAbsFMF =
3508 CommonRewriteFMF | FastMathFlags::unionValue(LHS: FAbsFMF, RHS: FastMathFlags());
3509 FastMathFlags NewCmpFMF =
3510 CommonRewriteFMF | FastMathFlags::unionValue(LHS: CmpFMF, RHS: FastMathFlags());
3511
3512 // When X is NaN, the old code evaluated fabs(Y), while the new code evaluates
3513 // fabs(X). Do not preserve nnan on either newly-created instruction.
3514 NewFAbsFMF.setNoNaNs(false);
3515 NewCmpFMF.setNoNaNs(false);
3516
3517 Value *NewAbs = IC.Builder.CreateFAbs(V: X, FMFSource: FMFSource(NewFAbsFMF));
3518 Value *NewCmp =
3519 IC.Builder.CreateFCmpFMF(P: Pred, LHS: NewAbs, RHS: Cmp1, FMFSource: FMFSource(NewCmpFMF));
3520 Value *NewSel = IC.Builder.CreateSelectFMF(C: NewCmp, True: X, False: Y, FMFSource: &SI);
3521 return IC.replaceInstUsesWith(I&: SI, V: NewSel);
3522}
3523
3524// Match the following IR pattern:
3525// %x.lowbits = and i8 %x, %lowbitmask
3526// %x.lowbits.are.zero = icmp eq i8 %x.lowbits, 0
3527// %x.biased = add i8 %x, %bias
3528// %x.biased.highbits = and i8 %x.biased, %highbitmask
3529// %x.roundedup = select i1 %x.lowbits.are.zero, i8 %x, i8 %x.biased.highbits
3530// Define:
3531// %alignment = add i8 %lowbitmask, 1
3532// Iff 1. an %alignment is a power-of-two (aka, %lowbitmask is a low bit mask)
3533// and 2. %bias is equal to either %lowbitmask or %alignment,
3534// and 3. %highbitmask is equal to ~%lowbitmask (aka, to -%alignment)
3535// then this pattern can be transformed into:
3536// %x.offset = add i8 %x, %lowbitmask
3537// %x.roundedup = and i8 %x.offset, %highbitmask
3538static Value *
3539foldRoundUpIntegerWithPow2Alignment(SelectInst &SI,
3540 InstCombiner::BuilderTy &Builder) {
3541 Value *Cond = SI.getCondition();
3542 Value *X = SI.getTrueValue();
3543 Value *XBiasedHighBits = SI.getFalseValue();
3544
3545 CmpPredicate Pred;
3546 Value *XLowBits;
3547 if (!match(V: Cond, P: m_ICmp(Pred, L: m_Value(V&: XLowBits), R: m_ZeroInt())) ||
3548 !ICmpInst::isEquality(P: Pred))
3549 return nullptr;
3550
3551 if (Pred == ICmpInst::Predicate::ICMP_NE)
3552 std::swap(a&: X, b&: XBiasedHighBits);
3553
3554 // FIXME: we could support non non-splats here.
3555
3556 const APInt *LowBitMaskCst;
3557 if (!match(V: XLowBits, P: m_And(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: LowBitMaskCst))))
3558 return nullptr;
3559
3560 // Match even if the AND and ADD are swapped.
3561 const APInt *BiasCst, *HighBitMaskCst;
3562 if (!match(V: XBiasedHighBits,
3563 P: m_And(L: m_Add(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: BiasCst)),
3564 R: m_APIntAllowPoison(Res&: HighBitMaskCst))) &&
3565 !match(V: XBiasedHighBits,
3566 P: m_Add(L: m_And(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: HighBitMaskCst)),
3567 R: m_APIntAllowPoison(Res&: BiasCst))))
3568 return nullptr;
3569
3570 if (!LowBitMaskCst->isMask())
3571 return nullptr;
3572
3573 APInt InvertedLowBitMaskCst = ~*LowBitMaskCst;
3574 if (InvertedLowBitMaskCst != *HighBitMaskCst)
3575 return nullptr;
3576
3577 APInt AlignmentCst = *LowBitMaskCst + 1;
3578
3579 if (*BiasCst != AlignmentCst && *BiasCst != *LowBitMaskCst)
3580 return nullptr;
3581
3582 if (!XBiasedHighBits->hasOneUse()) {
3583 // We can't directly return XBiasedHighBits if it is more poisonous.
3584 if (*BiasCst == *LowBitMaskCst && impliesPoison(ValAssumedPoison: XBiasedHighBits, V: X))
3585 return XBiasedHighBits;
3586 return nullptr;
3587 }
3588
3589 // FIXME: could we preserve undef's here?
3590 Type *Ty = X->getType();
3591 Value *XOffset = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *LowBitMaskCst),
3592 Name: X->getName() + ".biased");
3593 Value *R = Builder.CreateAnd(LHS: XOffset, RHS: ConstantInt::get(Ty, V: *HighBitMaskCst));
3594 R->takeName(V: &SI);
3595 return R;
3596}
3597
3598namespace {
3599struct DecomposedSelect {
3600 Value *Cond = nullptr;
3601 Value *TrueVal = nullptr;
3602 Value *FalseVal = nullptr;
3603};
3604} // namespace
3605
3606/// Folds patterns like:
3607/// select c2 (select c1 a b) (select c1 b a)
3608/// into:
3609/// select (xor c1 c2) b a
3610static Instruction *
3611foldSelectOfSymmetricSelect(SelectInst &OuterSelVal,
3612 InstCombiner::BuilderTy &Builder) {
3613
3614 Value *OuterCond, *InnerCond, *InnerTrueVal, *InnerFalseVal;
3615 if (!match(
3616 V: &OuterSelVal,
3617 P: m_Select(C: m_Value(V&: OuterCond),
3618 L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: InnerCond), L: m_Value(V&: InnerTrueVal),
3619 R: m_Value(V&: InnerFalseVal))),
3620 R: m_OneUse(SubPattern: m_Select(C: m_Deferred(V: InnerCond),
3621 L: m_Deferred(V: InnerFalseVal),
3622 R: m_Deferred(V: InnerTrueVal))))))
3623 return nullptr;
3624
3625 if (OuterCond->getType() != InnerCond->getType())
3626 return nullptr;
3627
3628 Value *Xor = Builder.CreateXor(LHS: InnerCond, RHS: OuterCond);
3629 return SelectInst::Create(C: Xor, S1: InnerFalseVal, S2: InnerTrueVal);
3630}
3631
3632/// Look for patterns like
3633/// %outer.cond = select i1 %inner.cond, i1 %alt.cond, i1 false
3634/// %inner.sel = select i1 %inner.cond, i8 %inner.sel.t, i8 %inner.sel.f
3635/// %outer.sel = select i1 %outer.cond, i8 %outer.sel.t, i8 %inner.sel
3636/// and rewrite it as
3637/// %inner.sel = select i1 %cond.alternative, i8 %sel.outer.t, i8 %sel.inner.t
3638/// %sel.outer = select i1 %cond.inner, i8 %inner.sel, i8 %sel.inner.f
3639static Instruction *foldNestedSelects(SelectInst &OuterSelVal,
3640 InstCombiner::BuilderTy &Builder) {
3641 // We must start with a `select`.
3642 DecomposedSelect OuterSel;
3643 match(V: &OuterSelVal,
3644 P: m_Select(C: m_Value(V&: OuterSel.Cond), L: m_Value(V&: OuterSel.TrueVal),
3645 R: m_Value(V&: OuterSel.FalseVal)));
3646
3647 // Canonicalize inversion of the outermost `select`'s condition.
3648 if (match(V: OuterSel.Cond, P: m_Not(V: m_Value(V&: OuterSel.Cond))))
3649 std::swap(a&: OuterSel.TrueVal, b&: OuterSel.FalseVal);
3650
3651 // The condition of the outermost select must be an `and`/`or`.
3652 if (!match(V: OuterSel.Cond, P: m_c_LogicalOp(L: m_Value(), R: m_Value())))
3653 return nullptr;
3654
3655 // Depending on the logical op, inner select might be in different hand.
3656 bool IsAndVariant = match(V: OuterSel.Cond, P: m_LogicalAnd());
3657 Value *InnerSelVal = IsAndVariant ? OuterSel.FalseVal : OuterSel.TrueVal;
3658
3659 // Profitability check - avoid increasing instruction count.
3660 if (none_of(Range: ArrayRef<Value *>({OuterSelVal.getCondition(), InnerSelVal}),
3661 P: match_fn(P: m_OneUse(SubPattern: m_Value()))))
3662 return nullptr;
3663
3664 // The appropriate hand of the outermost `select` must be a select itself.
3665 DecomposedSelect InnerSel;
3666 if (!match(V: InnerSelVal,
3667 P: m_Select(C: m_Value(V&: InnerSel.Cond), L: m_Value(V&: InnerSel.TrueVal),
3668 R: m_Value(V&: InnerSel.FalseVal))))
3669 return nullptr;
3670
3671 // Canonicalize inversion of the innermost `select`'s condition.
3672 if (match(V: InnerSel.Cond, P: m_Not(V: m_Value(V&: InnerSel.Cond))))
3673 std::swap(a&: InnerSel.TrueVal, b&: InnerSel.FalseVal);
3674
3675 Value *AltCond = nullptr;
3676 auto matchOuterCond = [OuterSel, IsAndVariant, &AltCond](auto m_InnerCond) {
3677 // An unsimplified select condition can match both LogicalAnd and LogicalOr
3678 // (select true, true, false). Since below we assume that LogicalAnd implies
3679 // InnerSel match the FVal and vice versa for LogicalOr, we can't match the
3680 // alternative pattern here.
3681 return IsAndVariant ? match(OuterSel.Cond,
3682 m_c_LogicalAnd(m_InnerCond, m_Value(V&: AltCond)))
3683 : match(OuterSel.Cond,
3684 m_c_LogicalOr(m_InnerCond, m_Value(V&: AltCond)));
3685 };
3686
3687 // Finally, match the condition that was driving the outermost `select`,
3688 // it should be a logical operation between the condition that was driving
3689 // the innermost `select` (after accounting for the possible inversions
3690 // of the condition), and some other condition.
3691 if (matchOuterCond(m_Specific(V: InnerSel.Cond))) {
3692 // Done!
3693 } else if (Value * NotInnerCond; matchOuterCond(m_CombineAnd(
3694 Ps: m_Not(V: m_Specific(V: InnerSel.Cond)), Ps: m_Value(V&: NotInnerCond)))) {
3695 // Done!
3696 std::swap(a&: InnerSel.TrueVal, b&: InnerSel.FalseVal);
3697 InnerSel.Cond = NotInnerCond;
3698 } else // Not the pattern we were looking for.
3699 return nullptr;
3700
3701 Value *SelInner = Builder.CreateSelect(
3702 C: AltCond, True: IsAndVariant ? OuterSel.TrueVal : InnerSel.FalseVal,
3703 False: IsAndVariant ? InnerSel.TrueVal : OuterSel.FalseVal);
3704 SelInner->takeName(V: InnerSelVal);
3705 return SelectInst::Create(C: InnerSel.Cond,
3706 S1: IsAndVariant ? SelInner : InnerSel.TrueVal,
3707 S2: !IsAndVariant ? SelInner : InnerSel.FalseVal);
3708}
3709
3710/// Return true if V is poison or \p Expected given that ValAssumedPoison is
3711/// already poison. For example, if ValAssumedPoison is `icmp samesign X, 10`
3712/// and V is `icmp ne X, 5`, impliesPoisonOrCond returns true.
3713static bool impliesPoisonOrCond(const Value *ValAssumedPoison, const Value *V,
3714 bool Expected, const SimplifyQuery &SQ) {
3715 if (impliesPoison(ValAssumedPoison, V))
3716 return true;
3717
3718 // Handle the case that ValAssumedPoison is `icmp samesign pred X, C1` and V
3719 // is `icmp pred X, C2`, where C1 is well-defined.
3720 if (auto *ICmp = dyn_cast<ICmpInst>(Val: ValAssumedPoison)) {
3721 Value *LHS = ICmp->getOperand(i_nocapture: 0);
3722 const APInt *RHSC1;
3723 const APInt *RHSC2;
3724 CmpPredicate Pred;
3725 if (ICmp->hasSameSign() &&
3726 match(V: ICmp->getOperand(i_nocapture: 1), P: m_APIntForbidPoison(Res&: RHSC1)) &&
3727 match(V, P: m_ICmp(Pred, L: m_Specific(V: LHS), R: m_APIntAllowPoison(Res&: RHSC2)))) {
3728 unsigned BitWidth = RHSC1->getBitWidth();
3729 ConstantRange CRX =
3730 RHSC1->isNonNegative()
3731 ? ConstantRange(APInt::getSignedMinValue(numBits: BitWidth),
3732 APInt::getZero(numBits: BitWidth))
3733 : ConstantRange(APInt::getZero(numBits: BitWidth),
3734 APInt::getSignedMinValue(numBits: BitWidth));
3735 return CRX.icmp(Pred: Expected ? Pred : ICmpInst::getInverseCmpPredicate(Pred),
3736 Other: *RHSC2);
3737 }
3738 }
3739 // For non-poison X in [0, 1], `trunc nuw X to i1` is not poison, but an
3740 // additional `nsw` flag makes it poison for X == 1.
3741 Value *A;
3742 if (match(V: ValAssumedPoison, P: m_NUWTrunc(Op: m_Value(V&: A))) &&
3743 !cast<TruncInst>(Val: ValAssumedPoison)->hasNoSignedWrap() &&
3744 isGuaranteedNotToBePoison(V: A)) {
3745 assert(ValAssumedPoison->getType()->isIntOrIntVectorTy(1));
3746 return computeKnownBits(
3747 V: A, Q: SQ.getWithInstruction(I: cast<Instruction>(Val: ValAssumedPoison)))
3748 .getMaxValue() == 1;
3749 }
3750
3751 return false;
3752}
3753
3754Instruction *InstCombinerImpl::foldSelectOfBools(SelectInst &SI) {
3755 Value *CondVal = SI.getCondition();
3756 Value *TrueVal = SI.getTrueValue();
3757 Value *FalseVal = SI.getFalseValue();
3758 Type *SelType = SI.getType();
3759
3760 // Avoid potential infinite loops by checking for non-constant condition.
3761 // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
3762 // Scalar select must have simplified?
3763 if (!SelType->isIntOrIntVectorTy(BitWidth: 1) || isa<Constant>(Val: CondVal) ||
3764 TrueVal->getType() != CondVal->getType())
3765 return nullptr;
3766
3767 auto *One = ConstantInt::getTrue(Ty: SelType);
3768 auto *Zero = ConstantInt::getFalse(Ty: SelType);
3769 Value *A, *B, *C, *D;
3770
3771 // Folding select to and/or i1 isn't poison safe in general. impliesPoison
3772 // checks whether folding it does not convert a well-defined value into
3773 // poison.
3774 if (match(V: TrueVal, P: m_One())) {
3775 if (impliesPoisonOrCond(ValAssumedPoison: FalseVal, V: CondVal, /*Expected=*/false, SQ)) {
3776 // Change: A = select B, true, C --> A = or B, C
3777 return BinaryOperator::CreateOr(V1: CondVal, V2: FalseVal);
3778 }
3779
3780 if (match(V: CondVal, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: A), L: m_One(), R: m_Value(V&: B)))) &&
3781 impliesPoisonOrCond(ValAssumedPoison: FalseVal, V: B, /*Expected=*/false, SQ)) {
3782 // (A || B) || C --> A || (B | C)
3783 Value *LOr = Builder.CreateLogicalOr(Cond1: A, Cond2: Builder.CreateOr(LHS: B, RHS: FalseVal));
3784 if (auto *I = dyn_cast<Instruction>(Val: LOr)) {
3785 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *I, DEBUG_TYPE);
3786 }
3787 return replaceInstUsesWith(I&: SI, V: LOr);
3788 }
3789
3790 // (A && B) || (C && B) --> (A || C) && B
3791 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3792 match(V: FalseVal, P: m_LogicalAnd(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3793 (CondVal->hasOneUse() || FalseVal->hasOneUse())) {
3794 bool CondLogicAnd = isa<SelectInst>(Val: CondVal);
3795 bool FalseLogicAnd = isa<SelectInst>(Val: FalseVal);
3796 auto AndFactorization = [&](Value *Common, Value *InnerCond,
3797 Value *InnerVal,
3798 bool SelFirst = false) -> Instruction * {
3799 Value *InnerSel = Builder.CreateSelectWithUnknownProfile(
3800 C: InnerCond, True: One, False: InnerVal, DEBUG_TYPE);
3801 if (SelFirst)
3802 std::swap(a&: Common, b&: InnerSel);
3803 if (FalseLogicAnd || (CondLogicAnd && Common == A))
3804 return createSelectInstWithUnknownProfile(C: Common, S1: InnerSel, S2: Zero);
3805 else
3806 return BinaryOperator::CreateAnd(V1: Common, V2: InnerSel);
3807 };
3808
3809 if (A == C)
3810 return AndFactorization(A, B, D);
3811 if (A == D)
3812 return AndFactorization(A, B, C);
3813 if (B == C)
3814 return AndFactorization(B, A, D);
3815 if (B == D)
3816 return AndFactorization(B, A, C, CondLogicAnd && FalseLogicAnd);
3817 }
3818 }
3819
3820 if (match(V: FalseVal, P: m_Zero())) {
3821 if (impliesPoisonOrCond(ValAssumedPoison: TrueVal, V: CondVal, /*Expected=*/true, SQ)) {
3822 // Change: A = select B, C, false --> A = and B, C
3823 return BinaryOperator::CreateAnd(V1: CondVal, V2: TrueVal);
3824 }
3825
3826 if (match(V: CondVal, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: A), L: m_Value(V&: B), R: m_Zero()))) &&
3827 impliesPoisonOrCond(ValAssumedPoison: TrueVal, V: B, /*Expected=*/true, SQ)) {
3828 // (A && B) && C --> A && (B & C)
3829 Value *LAnd = Builder.CreateLogicalAnd(Cond1: A, Cond2: Builder.CreateAnd(LHS: B, RHS: TrueVal));
3830 if (auto *I = dyn_cast<Instruction>(Val: LAnd)) {
3831 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *I, DEBUG_TYPE);
3832 }
3833 return replaceInstUsesWith(I&: SI, V: LAnd);
3834 }
3835
3836 // (A || B) && (C || B) --> (A && C) || B
3837 if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3838 match(V: TrueVal, P: m_LogicalOr(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3839 (CondVal->hasOneUse() || TrueVal->hasOneUse())) {
3840 bool CondLogicOr = isa<SelectInst>(Val: CondVal);
3841 bool TrueLogicOr = isa<SelectInst>(Val: TrueVal);
3842 auto OrFactorization = [&](Value *Common, Value *InnerCond,
3843 Value *InnerVal,
3844 bool SelFirst = false) -> Instruction * {
3845 Value *InnerSel = Builder.CreateSelectWithUnknownProfile(
3846 C: InnerCond, True: InnerVal, False: Zero, DEBUG_TYPE);
3847 if (SelFirst)
3848 std::swap(a&: Common, b&: InnerSel);
3849 if (TrueLogicOr || (CondLogicOr && Common == A))
3850 return createSelectInstWithUnknownProfile(C: Common, S1: One, S2: InnerSel);
3851 else
3852 return BinaryOperator::CreateOr(V1: Common, V2: InnerSel);
3853 };
3854
3855 if (A == C)
3856 return OrFactorization(A, B, D);
3857 if (A == D)
3858 return OrFactorization(A, B, C);
3859 if (B == C)
3860 return OrFactorization(B, A, D);
3861 if (B == D)
3862 return OrFactorization(B, A, C, CondLogicOr && TrueLogicOr);
3863 }
3864 }
3865
3866 // We match the "full" 0 or 1 constant here to avoid a potential infinite
3867 // loop with vectors that may have undefined/poison elements.
3868 // select a, false, b -> select !a, b, false
3869 if (match(V: TrueVal, P: m_Specific(V: Zero))) {
3870 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
3871 SelectInst *NewSI = SelectInst::Create(C: NotCond, S1: FalseVal, S2: Zero, NameStr: "", InsertBefore: nullptr,
3872 /*MDFrom=*/&SI);
3873 NewSI->swapProfMetadata();
3874 return NewSI;
3875 }
3876 // select a, b, true -> select !a, true, b
3877 if (match(V: FalseVal, P: m_Specific(V: One))) {
3878 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
3879 SelectInst *NewSI =
3880 SelectInst::Create(C: NotCond, S1: One, S2: TrueVal, NameStr: "", InsertBefore: nullptr, /*MDFrom=*/&SI);
3881 NewSI->swapProfMetadata();
3882 return NewSI;
3883 }
3884
3885 // DeMorgan in select form: !a && !b --> !(a || b)
3886 // select !a, !b, false --> not (select a, true, b)
3887 if (match(V: &SI, P: m_LogicalAnd(L: m_Not(V: m_Value(V&: A)), R: m_Not(V: m_Value(V&: B)))) &&
3888 (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
3889 !match(V: A, P: m_ConstantExpr()) && !match(V: B, P: m_ConstantExpr())) {
3890 SelectInst *NewSI =
3891 cast<SelectInst>(Val: Builder.CreateSelect(C: A, True: One, False: B, Name: "", /*MDFrom=*/&SI));
3892 NewSI->swapProfMetadata();
3893 return BinaryOperator::CreateNot(Op: NewSI);
3894 }
3895
3896 // DeMorgan in select form: !a || !b --> !(a && b)
3897 // select !a, true, !b --> not (select a, b, false)
3898 if (match(V: &SI, P: m_LogicalOr(L: m_Not(V: m_Value(V&: A)), R: m_Not(V: m_Value(V&: B)))) &&
3899 (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
3900 !match(V: A, P: m_ConstantExpr()) && !match(V: B, P: m_ConstantExpr())) {
3901 SelectInst *NewSI =
3902 cast<SelectInst>(Val: Builder.CreateSelect(C: A, True: B, False: Zero, Name: "", /*MDFrom=*/&SI));
3903 NewSI->swapProfMetadata();
3904 return BinaryOperator::CreateNot(Op: NewSI);
3905 }
3906
3907 // select (select a, true, b), true, b -> select a, true, b
3908 if (match(V: CondVal, P: m_Select(C: m_Value(V&: A), L: m_One(), R: m_Value(V&: B))) &&
3909 match(V: TrueVal, P: m_One()) && match(V: FalseVal, P: m_Specific(V: B)))
3910 return replaceOperand(I&: SI, OpNum: 0, V: A);
3911 // select (select a, b, false), b, false -> select a, b, false
3912 if (match(V: CondVal, P: m_Select(C: m_Value(V&: A), L: m_Value(V&: B), R: m_Zero())) &&
3913 match(V: TrueVal, P: m_Specific(V: B)) && match(V: FalseVal, P: m_Zero()))
3914 return replaceOperand(I&: SI, OpNum: 0, V: A);
3915
3916 // ~(A & B) & (A | B) --> A ^ B
3917 if (match(V: &SI, P: m_c_LogicalAnd(L: m_Not(V: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))),
3918 R: m_c_LogicalOr(L: m_Deferred(V: A), R: m_Deferred(V: B)))))
3919 return BinaryOperator::CreateXor(V1: A, V2: B);
3920
3921 // select (~a | c), a, b -> select a, (select c, true, b), false
3922 if (match(V: CondVal,
3923 P: m_OneUse(SubPattern: m_c_Or(L: m_Not(V: m_Specific(V: TrueVal)), R: m_Value(V&: C))))) {
3924 // TODO(#183864): We could improve the profile if P(~a | c) < 0.5, which
3925 // implies strong bounds on both operands (P(a) is high, P(c) is low).
3926 Value *OrV =
3927 Builder.CreateSelectWithUnknownProfile(C, True: One, False: FalseVal, DEBUG_TYPE);
3928 return createSelectInstWithUnknownProfile(C: TrueVal, S1: OrV, S2: Zero);
3929 }
3930 // select (c & b), a, b -> select b, (select ~c, true, a), false
3931 if (match(V: CondVal, P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: C), R: m_Specific(V: FalseVal))))) {
3932 if (Value *NotC = getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder)) {
3933 Value *OrV = Builder.CreateSelectWithUnknownProfile(C: NotC, True: One, False: TrueVal,
3934 DEBUG_TYPE);
3935 return createSelectInstWithUnknownProfile(C: FalseVal, S1: OrV, S2: Zero);
3936 }
3937 }
3938 // select (a | c), a, b -> select a, true, (select ~c, b, false)
3939 if (match(V: CondVal, P: m_OneUse(SubPattern: m_c_Or(L: m_Specific(V: TrueVal), R: m_Value(V&: C))))) {
3940 if (Value *NotC = getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder)) {
3941 // TODO(#183864): We could improve the profile if P(a | c) < 0.5, which
3942 // implies strong bounds on both operands (both P(a) and P(c) are low).
3943 Value *AndV = Builder.CreateSelectWithUnknownProfile(C: NotC, True: FalseVal, False: Zero,
3944 DEBUG_TYPE);
3945 return createSelectInstWithUnknownProfile(C: TrueVal, S1: One, S2: AndV);
3946 }
3947 }
3948 // select (c & ~b), a, b -> select b, true, (select c, a, false)
3949 if (match(V: CondVal,
3950 P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: C), R: m_Not(V: m_Specific(V: FalseVal)))))) {
3951 Value *AndV =
3952 Builder.CreateSelectWithUnknownProfile(C, True: TrueVal, False: Zero, DEBUG_TYPE);
3953 return createSelectInstWithUnknownProfile(C: FalseVal, S1: One, S2: AndV);
3954 }
3955
3956 if (match(V: FalseVal, P: m_Zero()) || match(V: TrueVal, P: m_One())) {
3957 Use *Y = nullptr;
3958 bool IsAnd = match(V: FalseVal, P: m_Zero()) ? true : false;
3959 Value *Op1 = IsAnd ? TrueVal : FalseVal;
3960 if (isCheckForZeroAndMulWithOverflow(Op0: CondVal, Op1, IsAnd, Y)) {
3961 auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
3962 InsertNewInstBefore(New: FI, Old: cast<Instruction>(Val: Y->getUser())->getIterator());
3963 replaceUse(U&: *Y, NewValue: FI);
3964 return replaceInstUsesWith(I&: SI, V: Op1);
3965 }
3966
3967 if (auto *V = foldBooleanAndOr(LHS: CondVal, RHS: Op1, I&: SI, IsAnd,
3968 /*IsLogical=*/true))
3969 return replaceInstUsesWith(I&: SI, V);
3970 }
3971
3972 // select (a || b), c, false -> select a, c, false
3973 // select c, (a || b), false -> select c, a, false
3974 // if c implies that b is false.
3975 if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3976 match(V: FalseVal, P: m_Zero())) {
3977 std::optional<bool> Res = isImpliedCondition(LHS: TrueVal, RHS: B, DL);
3978 if (Res && *Res == false)
3979 return replaceOperand(I&: SI, OpNum: 0, V: A);
3980 }
3981 if (match(V: TrueVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3982 match(V: FalseVal, P: m_Zero())) {
3983 std::optional<bool> Res = isImpliedCondition(LHS: CondVal, RHS: B, DL);
3984 if (Res && *Res == false)
3985 return replaceOperand(I&: SI, OpNum: 1, V: A);
3986 }
3987 // select c, true, (a && b) -> select c, true, a
3988 // select (a && b), true, c -> select a, true, c
3989 // if c = false implies that b = true
3990 if (match(V: TrueVal, P: m_One()) &&
3991 match(V: FalseVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3992 std::optional<bool> Res = isImpliedCondition(LHS: CondVal, RHS: B, DL, LHSIsTrue: false);
3993 if (Res && *Res == true)
3994 return replaceOperand(I&: SI, OpNum: 2, V: A);
3995 }
3996 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3997 match(V: TrueVal, P: m_One())) {
3998 std::optional<bool> Res = isImpliedCondition(LHS: FalseVal, RHS: B, DL, LHSIsTrue: false);
3999 if (Res && *Res == true)
4000 return replaceOperand(I&: SI, OpNum: 0, V: A);
4001 }
4002
4003 if (match(V: TrueVal, P: m_One())) {
4004 // (C && A) || (!C && B) --> select C, A, B (and similar cases)
4005 if (auto *V = FoldOrOfLogicalAnds(Op0: CondVal, Op1: FalseVal)) {
4006 return V;
4007 }
4008 }
4009
4010 return nullptr;
4011}
4012
4013// Return true if we can safely remove the select instruction for std::bit_ceil
4014// pattern.
4015static bool isSafeToRemoveBitCeilSelect(ICmpInst::Predicate Pred, Value *Cond0,
4016 const APInt *Cond1, Value *CtlzOp,
4017 unsigned BitWidth,
4018 bool &ShouldDropNoWrap) {
4019 // The challenge in recognizing std::bit_ceil(X) is that the operand is used
4020 // for the CTLZ proper and select condition, each possibly with some
4021 // operation like add and sub.
4022 //
4023 // Our aim is to make sure that -ctlz & (BitWidth - 1) == 0 even when the
4024 // select instruction would select 1, which allows us to get rid of the select
4025 // instruction.
4026 //
4027 // To see if we can do so, we do some symbolic execution with ConstantRange.
4028 // Specifically, we compute the range of values that Cond0 could take when
4029 // Cond == false. Then we successively transform the range until we obtain
4030 // the range of values that CtlzOp could take.
4031 //
4032 // Conceptually, we follow the def-use chain backward from Cond0 while
4033 // transforming the range for Cond0 until we meet the common ancestor of Cond0
4034 // and CtlzOp. Then we follow the def-use chain forward until we obtain the
4035 // range for CtlzOp. That said, we only follow at most one ancestor from
4036 // Cond0. Likewise, we only follow at most one ancestor from CtrlOp.
4037
4038 ConstantRange CR = ConstantRange::makeExactICmpRegion(
4039 Pred: CmpInst::getInversePredicate(pred: Pred), Other: *Cond1);
4040
4041 ShouldDropNoWrap = false;
4042
4043 // Match the operation that's used to compute CtlzOp from CommonAncestor. If
4044 // CtlzOp == CommonAncestor, return true as no operation is needed. If a
4045 // match is found, execute the operation on CR, update CR, and return true.
4046 // Otherwise, return false.
4047 auto MatchForward = [&](Value *CommonAncestor) {
4048 const APInt *C = nullptr;
4049 if (CtlzOp == CommonAncestor)
4050 return true;
4051 if (match(V: CtlzOp, P: m_Add(L: m_Specific(V: CommonAncestor), R: m_APInt(Res&: C)))) {
4052 ShouldDropNoWrap = true;
4053 CR = CR.add(Other: *C);
4054 return true;
4055 }
4056 if (match(V: CtlzOp, P: m_Sub(L: m_APInt(Res&: C), R: m_Specific(V: CommonAncestor)))) {
4057 ShouldDropNoWrap = true;
4058 CR = ConstantRange(*C).sub(Other: CR);
4059 return true;
4060 }
4061 if (match(V: CtlzOp, P: m_Not(V: m_Specific(V: CommonAncestor)))) {
4062 CR = CR.binaryNot();
4063 return true;
4064 }
4065 return false;
4066 };
4067
4068 const APInt *C = nullptr;
4069 Value *CommonAncestor;
4070 if (MatchForward(Cond0)) {
4071 // Cond0 is either CtlzOp or CtlzOp's parent. CR has been updated.
4072 } else if (match(V: Cond0, P: m_Add(L: m_Value(V&: CommonAncestor), R: m_APInt(Res&: C)))) {
4073 CR = CR.sub(Other: *C);
4074 if (!MatchForward(CommonAncestor))
4075 return false;
4076 // Cond0's parent is either CtlzOp or CtlzOp's parent. CR has been updated.
4077 } else {
4078 return false;
4079 }
4080
4081 // Return true if all the values in the range are either 0 or negative (if
4082 // treated as signed). We do so by evaluating:
4083 //
4084 // CR - 1 u>= (1 << BitWidth) - 1.
4085 APInt IntMax = APInt::getSignMask(BitWidth) - 1;
4086 CR = CR.sub(Other: APInt(BitWidth, 1));
4087 return CR.icmp(Pred: ICmpInst::ICMP_UGE, Other: IntMax);
4088}
4089
4090// Transform the std::bit_ceil(X) pattern like:
4091//
4092// %dec = add i32 %x, -1
4093// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
4094// %sub = sub i32 32, %ctlz
4095// %shl = shl i32 1, %sub
4096// %ugt = icmp ugt i32 %x, 1
4097// %sel = select i1 %ugt, i32 %shl, i32 1
4098//
4099// into:
4100//
4101// %dec = add i32 %x, -1
4102// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
4103// %neg = sub i32 0, %ctlz
4104// %masked = and i32 %ctlz, 31
4105// %shl = shl i32 1, %sub
4106//
4107// Note that the select is optimized away while the shift count is masked with
4108// 31. We handle some variations of the input operand like std::bit_ceil(X +
4109// 1).
4110static Instruction *foldBitCeil(SelectInst &SI, IRBuilderBase &Builder,
4111 InstCombinerImpl &IC) {
4112 Type *SelType = SI.getType();
4113 unsigned BitWidth = SelType->getScalarSizeInBits();
4114 if (!isPowerOf2_32(Value: BitWidth))
4115 return nullptr;
4116
4117 Value *FalseVal = SI.getFalseValue();
4118 Value *TrueVal = SI.getTrueValue();
4119 CmpPredicate Pred;
4120 const APInt *Cond1;
4121 Value *Cond0, *Ctlz, *CtlzOp;
4122 if (!match(V: SI.getCondition(), P: m_ICmp(Pred, L: m_Value(V&: Cond0), R: m_APInt(Res&: Cond1))))
4123 return nullptr;
4124
4125 if (match(V: TrueVal, P: m_One())) {
4126 std::swap(a&: FalseVal, b&: TrueVal);
4127 Pred = CmpInst::getInversePredicate(pred: Pred);
4128 }
4129
4130 bool ShouldDropNoWrap;
4131
4132 if (!match(V: FalseVal, P: m_One()) ||
4133 !match(V: TrueVal,
4134 P: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: BitWidth),
4135 R: m_Value(V&: Ctlz)))))) ||
4136 !match(V: Ctlz, P: m_Ctlz(Op0: m_Value(V&: CtlzOp), Op1: m_Value())) ||
4137 !isSafeToRemoveBitCeilSelect(Pred, Cond0, Cond1, CtlzOp, BitWidth,
4138 ShouldDropNoWrap))
4139 return nullptr;
4140
4141 if (ShouldDropNoWrap) {
4142 cast<Instruction>(Val: CtlzOp)->setHasNoUnsignedWrap(false);
4143 cast<Instruction>(Val: CtlzOp)->setHasNoSignedWrap(false);
4144 }
4145
4146 // Build 1 << (-CTLZ & (BitWidth-1)). The negation likely corresponds to a
4147 // single hardware instruction as opposed to BitWidth - CTLZ, where BitWidth
4148 // is an integer constant. Masking with BitWidth-1 comes free on some
4149 // hardware as part of the shift instruction.
4150
4151 // Drop range attributes and re-infer them in the next iteration.
4152 cast<Instruction>(Val: Ctlz)->dropPoisonGeneratingAnnotations();
4153 IC.addToWorklist(I: cast<Instruction>(Val: Ctlz));
4154 Value *Neg = Builder.CreateNeg(V: Ctlz);
4155 Value *Masked =
4156 Builder.CreateAnd(LHS: Neg, RHS: ConstantInt::get(Ty: SelType, V: BitWidth - 1));
4157 return BinaryOperator::Create(Op: Instruction::Shl, S1: ConstantInt::get(Ty: SelType, V: 1),
4158 S2: Masked);
4159}
4160
4161// This function tries to fold the following operations:
4162// (x < y) ? -1 : zext(x != y)
4163// (x < y) ? -1 : zext(x > y)
4164// (x > y) ? 1 : sext(x != y)
4165// (x > y) ? 1 : sext(x < y)
4166// (x == y) ? 0 : (x > y ? 1 : -1)
4167// (x == y) ? 0 : (x < y ? -1 : 1)
4168// Special case: x == C ? 0 : (x > C - 1 ? 1 : -1)
4169// Special case: x == C ? 0 : (x < C + 1 ? -1 : 1)
4170// Into ucmp/scmp(x, y), where signedness is determined by the signedness
4171// of the comparison in the original sequence.
4172Instruction *InstCombinerImpl::foldSelectToCmp(SelectInst &SI) {
4173 Value *TV = SI.getTrueValue();
4174 Value *FV = SI.getFalseValue();
4175
4176 CmpPredicate Pred;
4177 Value *LHS, *RHS;
4178 if (!match(V: SI.getCondition(), P: m_ICmp(Pred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))
4179 return nullptr;
4180
4181 if (!LHS->getType()->isIntOrIntVectorTy())
4182 return nullptr;
4183
4184 // If there is no -1, 0 or 1 at TV, then invert the select statement and try
4185 // to canonicalize to one of the forms above
4186 if (!isa<Constant>(Val: TV)) {
4187 if (!isa<Constant>(Val: FV))
4188 return nullptr;
4189 Pred = ICmpInst::getInverseCmpPredicate(Pred);
4190 std::swap(a&: TV, b&: FV);
4191 }
4192
4193 if (ICmpInst::isNonStrictPredicate(predicate: Pred)) {
4194 if (Constant *C = dyn_cast<Constant>(Val: RHS)) {
4195 auto FlippedPredAndConst =
4196 getFlippedStrictnessPredicateAndConstant(Pred, C);
4197 if (!FlippedPredAndConst)
4198 return nullptr;
4199 Pred = FlippedPredAndConst->first;
4200 RHS = FlippedPredAndConst->second;
4201 } else {
4202 return nullptr;
4203 }
4204 }
4205
4206 // Try to swap operands and the predicate. We need to be careful when doing
4207 // so because two of the patterns have opposite predicates, so use the
4208 // constant inside select to determine if swapping operands would be
4209 // beneficial to us.
4210 if ((ICmpInst::isGT(P: Pred) && match(V: TV, P: m_AllOnes())) ||
4211 (ICmpInst::isLT(P: Pred) && match(V: TV, P: m_One()))) {
4212 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4213 std::swap(a&: LHS, b&: RHS);
4214 }
4215 bool IsSigned = ICmpInst::isSigned(Pred);
4216
4217 bool Replace = false;
4218 CmpPredicate ExtendedCmpPredicate;
4219 // (x < y) ? -1 : zext(x != y)
4220 // (x < y) ? -1 : zext(x > y)
4221 if (ICmpInst::isLT(P: Pred) && match(V: TV, P: m_AllOnes()) &&
4222 match(V: FV, P: m_ZExt(Op: m_c_ICmp(Pred&: ExtendedCmpPredicate, L: m_Specific(V: LHS),
4223 R: m_Specific(V: RHS)))) &&
4224 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
4225 ICmpInst::getSwappedPredicate(pred: ExtendedCmpPredicate) == Pred))
4226 Replace = true;
4227
4228 // (x > y) ? 1 : sext(x != y)
4229 // (x > y) ? 1 : sext(x < y)
4230 if (ICmpInst::isGT(P: Pred) && match(V: TV, P: m_One()) &&
4231 match(V: FV, P: m_SExt(Op: m_c_ICmp(Pred&: ExtendedCmpPredicate, L: m_Specific(V: LHS),
4232 R: m_Specific(V: RHS)))) &&
4233 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
4234 ICmpInst::getSwappedPredicate(pred: ExtendedCmpPredicate) == Pred))
4235 Replace = true;
4236
4237 // (x == y) ? 0 : (x > y ? 1 : -1)
4238 CmpPredicate FalseBranchSelectPredicate;
4239 const APInt *InnerTV, *InnerFV;
4240 if (Pred == ICmpInst::ICMP_EQ && match(V: TV, P: m_Zero()) &&
4241 match(V: FV, P: m_Select(C: m_c_ICmp(Pred&: FalseBranchSelectPredicate, L: m_Specific(V: LHS),
4242 R: m_Specific(V: RHS)),
4243 L: m_APInt(Res&: InnerTV), R: m_APInt(Res&: InnerFV)))) {
4244 if (!ICmpInst::isGT(P: FalseBranchSelectPredicate)) {
4245 FalseBranchSelectPredicate =
4246 ICmpInst::getSwappedPredicate(pred: FalseBranchSelectPredicate);
4247 std::swap(a&: LHS, b&: RHS);
4248 }
4249
4250 if (!InnerTV->isOne()) {
4251 std::swap(a&: InnerTV, b&: InnerFV);
4252 std::swap(a&: LHS, b&: RHS);
4253 }
4254
4255 if (ICmpInst::isGT(P: FalseBranchSelectPredicate) && InnerTV->isOne() &&
4256 InnerFV->isAllOnes()) {
4257 IsSigned = ICmpInst::isSigned(Pred: FalseBranchSelectPredicate);
4258 Replace = true;
4259 }
4260 }
4261
4262 // Special cases with constants: x == C ? 0 : (x > C-1 ? 1 : -1)
4263 if (Pred == ICmpInst::ICMP_EQ && match(V: TV, P: m_Zero())) {
4264 const APInt *C;
4265 if (match(V: RHS, P: m_APInt(Res&: C))) {
4266 CmpPredicate InnerPred;
4267 Value *InnerRHS;
4268 const APInt *InnerTV, *InnerFV;
4269 if (match(V: FV,
4270 P: m_Select(C: m_ICmp(Pred&: InnerPred, L: m_Specific(V: LHS), R: m_Value(V&: InnerRHS)),
4271 L: m_APInt(Res&: InnerTV), R: m_APInt(Res&: InnerFV)))) {
4272
4273 // x == C ? 0 : (x > C-1 ? 1 : -1)
4274 if (ICmpInst::isGT(P: InnerPred) && InnerTV->isOne() &&
4275 InnerFV->isAllOnes()) {
4276 IsSigned = ICmpInst::isSigned(Pred: InnerPred);
4277 bool CanSubOne = IsSigned ? !C->isMinSignedValue() : !C->isMinValue();
4278 if (CanSubOne) {
4279 APInt Cminus1 = *C - 1;
4280 if (match(V: InnerRHS, P: m_SpecificInt(V: Cminus1)))
4281 Replace = true;
4282 }
4283 }
4284
4285 // x == C ? 0 : (x < C+1 ? -1 : 1)
4286 if (ICmpInst::isLT(P: InnerPred) && InnerTV->isAllOnes() &&
4287 InnerFV->isOne()) {
4288 IsSigned = ICmpInst::isSigned(Pred: InnerPred);
4289 bool CanAddOne = IsSigned ? !C->isMaxSignedValue() : !C->isMaxValue();
4290 if (CanAddOne) {
4291 APInt Cplus1 = *C + 1;
4292 if (match(V: InnerRHS, P: m_SpecificInt(V: Cplus1)))
4293 Replace = true;
4294 }
4295 }
4296 }
4297 }
4298 }
4299
4300 Intrinsic::ID IID = IsSigned ? Intrinsic::scmp : Intrinsic::ucmp;
4301 if (Replace)
4302 return replaceInstUsesWith(
4303 I&: SI, V: Builder.CreateIntrinsic(RetTy: SI.getType(), ID: IID, Args: {LHS, RHS}));
4304 return nullptr;
4305}
4306
4307bool InstCombinerImpl::fmulByZeroIsZero(Value *MulVal, FastMathFlags FMF,
4308 const Instruction *CtxI) const {
4309 KnownFPClass Known =
4310 computeKnownFPClass(V: MulVal, FMF, InterestedClasses: fcNegative, SQ: SQ.getWithInstruction(I: CtxI));
4311
4312 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity() &&
4313 (FMF.noSignedZeros() || Known.signBitIsZeroOrNaN());
4314}
4315
4316static bool matchFMulByZeroIfResultEqZero(InstCombinerImpl &IC, Value *Cmp0,
4317 Value *Cmp1, Value *TrueVal,
4318 Value *FalseVal, Instruction &CtxI,
4319 bool SelectIsNSZ) {
4320 Value *MulRHS;
4321 if (match(V: Cmp1, P: m_PosZeroFP()) &&
4322 match(V: TrueVal, P: m_c_FMul(L: m_Specific(V: Cmp0), R: m_Value(V&: MulRHS)))) {
4323 FastMathFlags FMF = cast<FPMathOperator>(Val: TrueVal)->getFastMathFlags();
4324 // nsz must be on the select, it must be ignored on the multiply. We
4325 // need nnan and ninf on the multiply for the other value.
4326 FMF.setNoSignedZeros(SelectIsNSZ);
4327 return IC.fmulByZeroIsZero(MulVal: MulRHS, FMF, CtxI: &CtxI);
4328 }
4329
4330 return false;
4331}
4332
4333/// Check whether the KnownBits of a select arm may be affected by the
4334/// select condition.
4335static bool hasAffectedValue(Value *V, SmallPtrSetImpl<Value *> &Affected,
4336 unsigned Depth) {
4337 if (Depth == MaxAnalysisRecursionDepth)
4338 return false;
4339
4340 // Ignore the case where the select arm itself is affected. These cases
4341 // are handled more efficiently by other optimizations.
4342 if (Depth != 0 && Affected.contains(Ptr: V))
4343 return true;
4344
4345 if (auto *I = dyn_cast<Instruction>(Val: V)) {
4346 if (isa<PHINode>(Val: I)) {
4347 if (Depth == MaxAnalysisRecursionDepth - 1)
4348 return false;
4349 Depth = MaxAnalysisRecursionDepth - 2;
4350 }
4351 return any_of(Range: I->operands(), P: [&](Value *Op) {
4352 return Op->getType()->isIntOrIntVectorTy() &&
4353 hasAffectedValue(V: Op, Affected, Depth: Depth + 1);
4354 });
4355 }
4356
4357 return false;
4358}
4359
4360// This transformation enables the possibility of transforming fcmp + sel into
4361// a fmaxnum/fminnum intrinsic.
4362static Value *foldSelectIntoAddConstant(SelectInst &SI,
4363 InstCombiner::BuilderTy &Builder) {
4364 // Do this transformation only when select instruction gives NaN and NSZ
4365 // guarantee.
4366 auto *SIFOp = dyn_cast<FPMathOperator>(Val: &SI);
4367 if (!SIFOp || !SIFOp->hasNoSignedZeros() || !SIFOp->hasNoNaNs())
4368 return nullptr;
4369
4370 auto TryFoldIntoAddConstant =
4371 [&Builder, &SI](CmpInst::Predicate Pred, Value *X, Value *Z,
4372 Instruction *FAdd, Constant *C, bool Swapped) -> Value * {
4373 // Only these relational predicates can be transformed into maxnum/minnum
4374 // intrinsic.
4375 if (!CmpInst::isRelational(P: Pred) || !match(V: Z, P: m_AnyZeroFP()))
4376 return nullptr;
4377
4378 if (!match(V: FAdd, P: m_FAdd(L: m_Specific(V: X), R: m_Specific(V: C))))
4379 return nullptr;
4380
4381 Value *NewSelect = Builder.CreateSelect(C: SI.getCondition(), True: Swapped ? Z : X,
4382 False: Swapped ? X : Z, Name: "", MDFrom: &SI);
4383 NewSelect->takeName(V: &SI);
4384
4385 Value *NewFAdd = Builder.CreateFAdd(L: NewSelect, R: C);
4386 NewFAdd->takeName(V: FAdd);
4387
4388 // Propagate FastMath flags
4389 FastMathFlags SelectFMF = SI.getFastMathFlags();
4390 FastMathFlags FAddFMF = FAdd->getFastMathFlags();
4391 FastMathFlags NewFMF = FastMathFlags::intersectRewrite(LHS: SelectFMF, RHS: FAddFMF) |
4392 FastMathFlags::unionValue(LHS: SelectFMF, RHS: FAddFMF);
4393 cast<Instruction>(Val: NewFAdd)->setFastMathFlags(NewFMF);
4394 cast<Instruction>(Val: NewSelect)->setFastMathFlags(NewFMF);
4395
4396 return NewFAdd;
4397 };
4398
4399 // select((fcmp Pred, X, 0), (fadd X, C), C)
4400 // => fadd((select (fcmp Pred, X, 0), X, 0), C)
4401 //
4402 // Pred := OGT, OGE, OLT, OLE, UGT, UGE, ULT, and ULE
4403 Instruction *FAdd;
4404 Constant *C;
4405 Value *X, *Z;
4406 CmpPredicate Pred;
4407
4408 // Note: OneUse check for `Cmp` is necessary because it makes sure that other
4409 // InstCombine folds don't undo this transformation and cause an infinite
4410 // loop. Furthermore, it could also increase the operation count.
4411 if (match(V: &SI, P: m_Select(C: m_OneUse(SubPattern: m_FCmp(Pred, L: m_Value(V&: X), R: m_Value(V&: Z))),
4412 L: m_OneUse(SubPattern: m_Instruction(I&: FAdd)), R: m_Constant(C))))
4413 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/false);
4414
4415 if (match(V: &SI, P: m_Select(C: m_OneUse(SubPattern: m_FCmp(Pred, L: m_Value(V&: X), R: m_Value(V&: Z))),
4416 L: m_Constant(C), R: m_OneUse(SubPattern: m_Instruction(I&: FAdd)))))
4417 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/true);
4418
4419 return nullptr;
4420}
4421
4422static Value *foldSelectBitTest(SelectInst &Sel, Value *CondVal, Value *TrueVal,
4423 Value *FalseVal,
4424 InstCombiner::BuilderTy &Builder,
4425 const SimplifyQuery &SQ) {
4426 // If this is a vector select, we need a vector compare.
4427 Type *SelType = Sel.getType();
4428 if (SelType->isVectorTy() != CondVal->getType()->isVectorTy())
4429 return nullptr;
4430
4431 Value *V;
4432 APInt AndMask;
4433 bool CreateAnd = false;
4434 CmpPredicate Pred;
4435 Value *CmpLHS, *CmpRHS;
4436
4437 if (match(V: CondVal, P: m_ICmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS)))) {
4438 if (ICmpInst::isEquality(P: Pred)) {
4439 if (!match(V: CmpRHS, P: m_Zero()))
4440 return nullptr;
4441
4442 V = CmpLHS;
4443 const APInt *AndRHS;
4444 if (!match(V: CmpLHS, P: m_And(L: m_Value(), R: m_Power2(V&: AndRHS))))
4445 return nullptr;
4446
4447 AndMask = *AndRHS;
4448 } else if (auto Res = decomposeBitTestICmp(LHS: CmpLHS, RHS: CmpRHS, Pred)) {
4449 assert(ICmpInst::isEquality(Res->Pred) && "Not equality test?");
4450 AndMask = Res->Mask;
4451 V = Res->X;
4452 KnownBits Known = computeKnownBits(V, Q: SQ.getWithInstruction(I: &Sel));
4453 AndMask &= Known.getMaxValue();
4454 if (!AndMask.isPowerOf2())
4455 return nullptr;
4456
4457 Pred = Res->Pred;
4458 CreateAnd = true;
4459 } else {
4460 return nullptr;
4461 }
4462 } else if (auto *Trunc = dyn_cast<TruncInst>(Val: CondVal)) {
4463 V = Trunc->getOperand(i_nocapture: 0);
4464 AndMask = APInt(V->getType()->getScalarSizeInBits(), 1);
4465 Pred = ICmpInst::ICMP_NE;
4466 CreateAnd = !Trunc->hasNoUnsignedWrap();
4467 } else {
4468 return nullptr;
4469 }
4470
4471 if (Pred == ICmpInst::ICMP_NE)
4472 std::swap(a&: TrueVal, b&: FalseVal);
4473
4474 if (Value *X = foldSelectICmpAnd(Sel, CondVal, TrueVal, FalseVal, V, AndMask,
4475 CreateAnd, Builder))
4476 return X;
4477
4478 if (Value *X = foldSelectICmpAndBinOp(CondVal, TrueVal, FalseVal, V, AndMask,
4479 CreateAnd, Builder))
4480 return X;
4481
4482 return nullptr;
4483}
4484
4485/// This function makes the following folds:
4486/// select C, (sub 0, X), (xor X, -1)
4487/// -> sub (sext !C), X
4488/// select C, (xor X, -1), (sub 0, X)
4489/// -> sub (sext C), X
4490static Instruction *foldSelectNegNot(SelectInst &SI,
4491 InstCombiner::BuilderTy &Builder) {
4492 auto *CondVal = SI.getCondition();
4493 auto *TrueVal = SI.getTrueValue();
4494 auto *FalseVal = SI.getFalseValue();
4495 auto *SelTy = SI.getType();
4496
4497 if (!SelTy->isIntOrIntVectorTy() || SelTy->isIntOrIntVectorTy(BitWidth: 1))
4498 return nullptr;
4499
4500 if (CondVal->getType()->isVectorTy() != SelTy->isVectorTy())
4501 return nullptr;
4502
4503 auto matchNegNot = [&](Value *Neg, Value *Not, Value *&X) -> bool {
4504 return match(V: Neg, P: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X)))) &&
4505 match(V: Not, P: m_OneUse(SubPattern: m_Not(V: m_Specific(V: X))));
4506 };
4507
4508 Value *X;
4509 Value *Mask;
4510
4511 // select C, (sub 0, X), (xor X, -1) -> sub (sext !C), X
4512 if (matchNegNot(TrueVal, FalseVal, X)) {
4513 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4514 Mask = Builder.CreateSExt(V: NotCond, DestTy: SelTy);
4515 return BinaryOperator::CreateSub(V1: Mask, V2: X);
4516 }
4517
4518 // select C, (xor X, -1), (sub 0, X) -> sub (sext C), X
4519 if (matchNegNot(FalseVal, TrueVal, X)) {
4520 Mask = Builder.CreateSExt(V: CondVal, DestTy: SelTy);
4521 return BinaryOperator::CreateSub(V1: Mask, V2: X);
4522 }
4523
4524 return nullptr;
4525}
4526
4527/// Fold select (A & Shift == 0 | B & Shift == 0), 0, Shift -> Shift & A & B
4528/// where Shift is known to be a power of two.
4529static Instruction *foldSelectAndOrPowerOfTwo(SelectInst &SI,
4530 InstCombiner::BuilderTy &Builder,
4531 const SimplifyQuery &SQ) {
4532 Value *Cond = SI.getCondition();
4533
4534 if (!Cond->hasOneUse())
4535 return nullptr;
4536
4537 Value *TrueVal = SI.getTrueValue();
4538 Value *FalseVal = SI.getFalseValue();
4539
4540 Value *A, *B, *Shift;
4541
4542 bool Case1 =
4543 match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_Value(V&: Shift)) &&
4544 match(V: Cond, P: m_Or(L: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
4545 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: A)),
4546 R: m_Zero()),
4547 R: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
4548 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: B)),
4549 R: m_Zero())));
4550
4551 bool Case2 =
4552 match(V: FalseVal, P: m_Zero()) && match(V: TrueVal, P: m_Value(V&: Shift)) &&
4553 match(V: Cond, P: m_And(L: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE,
4554 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: A)),
4555 R: m_Zero()),
4556 R: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE,
4557 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: B)),
4558 R: m_Zero())));
4559
4560 if ((Case1 || Case2) && isKnownToBeAPowerOfTwo(V: Shift, /*OrZero=*/true,
4561 Q: SQ.getWithInstruction(I: &SI))) {
4562 Value *And1 = Builder.CreateAnd(LHS: Shift, RHS: A);
4563 return BinaryOperator::CreateAnd(V1: And1, V2: B);
4564 }
4565
4566 return nullptr;
4567}
4568
4569// Return true if no use can observe the sign of zero of the select result,
4570// looking through phis, selects and the loop back edge to the select itself.
4571static bool isSelectZeroSignInsignificant(SelectInst &SI) {
4572 // Bound the number of uses to look through to keep the compile time in
4573 // check.
4574 constexpr unsigned MaxUsesToLookThrough = 16;
4575 unsigned NumUses = 0;
4576 SmallPtrSet<Instruction *, 4> Visited;
4577 SmallVector<Instruction *> Worklist(1, &SI);
4578 while (!Worklist.empty()) {
4579 for (Use &U : Worklist.pop_back_val()->uses()) {
4580 if (++NumUses > MaxUsesToLookThrough)
4581 return false;
4582 auto *User = cast<Instruction>(Val: U.getUser());
4583 if (User == &SI)
4584 continue;
4585 if (canIgnoreSignBitOfZero(U))
4586 continue;
4587 if (isa<PHINode, SelectInst>(Val: User)) {
4588 if (Visited.insert(Ptr: User).second)
4589 Worklist.push_back(Elt: User);
4590 continue;
4591 }
4592 return false;
4593 }
4594 }
4595 return true;
4596}
4597
4598Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
4599 Value *CondVal = SI.getCondition();
4600 Value *TrueVal = SI.getTrueValue();
4601 Value *FalseVal = SI.getFalseValue();
4602 Type *SelType = SI.getType();
4603
4604 FastMathFlags FMF;
4605 if (auto *FPMO = dyn_cast_if_present<FPMathOperator>(Val: &SI))
4606 FMF = FPMO->getFastMathFlags();
4607
4608 if (Value *V = simplifySelectInst(Cond: CondVal, TrueVal, FalseVal, FMF,
4609 Q: SQ.getWithInstruction(I: &SI)))
4610 return replaceInstUsesWith(I&: SI, V);
4611
4612 if (Instruction *I = canonicalizeSelectToShuffle(SI))
4613 return I;
4614
4615 if (Instruction *I = canonicalizeScalarSelectOfVecs(Sel&: SI, IC&: *this))
4616 return I;
4617
4618 // Fold: select (icmp ult X, 2), X, ctpop(X) --> ctpop(X)
4619 // ctpop(0)==0 and ctpop(1)==1, so the guard is always redundant.
4620 if (match(V: FalseVal, P: m_Ctpop(Op0: m_Specific(V: TrueVal))) &&
4621 match(V: CondVal, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT, L: m_Specific(V: TrueVal),
4622 R: m_SpecificInt(V: 2)))) {
4623 cast<Instruction>(Val: FalseVal)->dropPoisonGeneratingAnnotations();
4624 addToWorklist(I: cast<Instruction>(Val: FalseVal));
4625 return replaceInstUsesWith(I&: SI, V: FalseVal);
4626 }
4627
4628 // If the type of select is not an integer type or if the condition and
4629 // the selection type are not both scalar nor both vector types, there is no
4630 // point in attempting to match these patterns.
4631 Type *CondType = CondVal->getType();
4632 if (!isa<Constant>(Val: CondVal) && SelType->isIntOrIntVectorTy() &&
4633 CondType->isVectorTy() == SelType->isVectorTy()) {
4634 if (Value *S = simplifyWithOpReplaced(V: TrueVal, Op: CondVal,
4635 RepOp: ConstantInt::getTrue(Ty: CondType), Q: SQ,
4636 /* AllowRefinement */ true))
4637 return replaceOperand(I&: SI, OpNum: 1, V: S);
4638
4639 if (Value *S = simplifyWithOpReplaced(V: FalseVal, Op: CondVal,
4640 RepOp: ConstantInt::getFalse(Ty: CondType), Q: SQ,
4641 /* AllowRefinement */ true))
4642 return replaceOperand(I&: SI, OpNum: 2, V: S);
4643
4644 if (replaceInInstruction(V: TrueVal, Old: CondVal,
4645 New: ConstantInt::getTrue(Ty: CondType)) ||
4646 replaceInInstruction(V: FalseVal, Old: CondVal,
4647 New: ConstantInt::getFalse(Ty: CondType)))
4648 return &SI;
4649 }
4650
4651 if (Instruction *R = foldSelectOfBools(SI))
4652 return R;
4653
4654 // Selecting between two integer or vector splat integer constants?
4655 //
4656 // Note that we don't handle a scalar select of vectors:
4657 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
4658 // because that may need 3 instructions to splat the condition value:
4659 // extend, insertelement, shufflevector.
4660 //
4661 // Do not handle i1 TrueVal and FalseVal otherwise would result in
4662 // zext/sext i1 to i1.
4663 if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(BitWidth: 1) &&
4664 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
4665 // select C, 1, 0 -> zext C to int
4666 if (match(V: TrueVal, P: m_One()) && match(V: FalseVal, P: m_Zero()))
4667 return new ZExtInst(CondVal, SelType);
4668
4669 // select C, -1, 0 -> sext C to int
4670 if (match(V: TrueVal, P: m_AllOnes()) && match(V: FalseVal, P: m_Zero()))
4671 return new SExtInst(CondVal, SelType);
4672
4673 // select C, 0, 1 -> zext !C to int
4674 if (match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_One())) {
4675 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4676 return new ZExtInst(NotCond, SelType);
4677 }
4678
4679 // select C, 0, -1 -> sext !C to int
4680 if (match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_AllOnes())) {
4681 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4682 return new SExtInst(NotCond, SelType);
4683 }
4684 }
4685
4686 if (Instruction *I = foldSelectNegNot(SI, Builder))
4687 return I;
4688
4689 if (Instruction *I = foldSelectAndOrPowerOfTwo(SI, Builder, SQ))
4690 return I;
4691
4692 auto *SIFPOp = dyn_cast<FPMathOperator>(Val: &SI);
4693
4694 if (auto *FCmp = dyn_cast<FCmpInst>(Val: CondVal)) {
4695 FCmpInst::Predicate Pred = FCmp->getPredicate();
4696 Value *Cmp0 = FCmp->getOperand(i_nocapture: 0), *Cmp1 = FCmp->getOperand(i_nocapture: 1);
4697 // Are we selecting a value based on a comparison of the two values?
4698 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
4699 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
4700 // Canonicalize to use ordered comparisons by swapping the select
4701 // operands.
4702 //
4703 // e.g.
4704 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
4705 if (FCmp->hasOneUse() && FCmpInst::isUnordered(predicate: Pred)) {
4706 FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
4707 Value *NewCond = Builder.CreateFCmpFMF(P: InvPred, LHS: Cmp0, RHS: Cmp1, FMFSource: FCmp,
4708 Name: FCmp->getName() + ".inv");
4709 // Propagate ninf/nnan from fcmp to select.
4710 FastMathFlags FMF = SI.getFastMathFlags();
4711 if (FCmp->hasNoNaNs())
4712 FMF.setNoNaNs(true);
4713 if (FCmp->hasNoInfs())
4714 FMF.setNoInfs(true);
4715 Value *NewSel =
4716 Builder.CreateSelectFMF(C: NewCond, True: FalseVal, False: TrueVal, FMFSource: FMF);
4717 return replaceInstUsesWith(I&: SI, V: NewSel);
4718 }
4719 }
4720
4721 if (SIFPOp) {
4722 // Fold out scale-if-equals-zero pattern.
4723 //
4724 // This pattern appears in code with denormal range checks after it's
4725 // assumed denormals are treated as zero. This drops a canonicalization.
4726
4727 // TODO: Could relax the signed zero logic. We just need to know the sign
4728 // of the result matches (fmul x, y has the same sign as x).
4729 //
4730 // TODO: Handle always-canonicalizing variant that selects some value or 1
4731 // scaling factor in the fmul visitor.
4732
4733 // TODO: Handle ldexp too
4734
4735 Value *MatchCmp0 = nullptr;
4736 Value *MatchCmp1 = nullptr;
4737
4738 // (select (fcmp [ou]eq x, 0.0), (fmul x, K), x => x
4739 // (select (fcmp [ou]ne x, 0.0), x, (fmul x, K) => x
4740 if (Pred == CmpInst::FCMP_OEQ || Pred == CmpInst::FCMP_UEQ) {
4741 MatchCmp0 = FalseVal;
4742 MatchCmp1 = TrueVal;
4743 } else if (Pred == CmpInst::FCMP_ONE || Pred == CmpInst::FCMP_UNE) {
4744 MatchCmp0 = TrueVal;
4745 MatchCmp1 = FalseVal;
4746 }
4747
4748 if (Cmp0 == MatchCmp0 &&
4749 matchFMulByZeroIfResultEqZero(IC&: *this, Cmp0, Cmp1, TrueVal: MatchCmp1, FalseVal: MatchCmp0,
4750 CtxI&: SI, SelectIsNSZ: SIFPOp->hasNoSignedZeros()))
4751 return replaceInstUsesWith(I&: SI, V: Cmp0);
4752
4753 Type *EltTy = SelType->getScalarType();
4754
4755 // TODO: Generalize to any ordered / unordered compare.
4756 if ((Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) &&
4757 match(V: Cmp1, P: m_PosZeroFP()) && EltTy->isIEEELikeFPTy()) {
4758 // Fold out only-canonicalize-non-nans pattern. This implements a
4759 // wrapper around llvm.canonicalize which is not required to quiet
4760 // signaling nans or preserve nan payload bits.
4761 //
4762 // %hard.canonical = call @llvm.canonicalize(%x)
4763 // %soft.canonical = fdiv 1.0, %x
4764 // %ord = fcmp ord %x, 0.0
4765 // %x.canon = select i1 %ord, %hard.canonical, %soft.canonical
4766 //
4767 // With known IEEE handling:
4768 // => %x
4769 //
4770 // With other denormal behaviors:
4771 // => llvm.canonicalize(%x)
4772 //
4773 // Note the fdiv could be any value preserving, potentially
4774 // canonicalizing floating-point operation such as fmul by 1.0. However,
4775 // since in the llvm model canonicalization is not mandatory, the fmul
4776 // would have been dropped by the time we reached here. The trick here
4777 // is to use a reciprocal fdiv. It's not a droppable no-op, as it could
4778 // return an infinity if %x were sufficiently small, but in this pattern
4779 // we're only using the output for nan values.
4780
4781 if (Pred == CmpInst::FCMP_ORD) {
4782 MatchCmp0 = TrueVal;
4783 MatchCmp1 = FalseVal;
4784 } else {
4785 MatchCmp0 = FalseVal;
4786 MatchCmp1 = TrueVal;
4787 }
4788
4789 bool RcpIfNan = match(V: MatchCmp1, P: m_FDiv(L: m_FPOne(), R: m_Specific(V: Cmp0)));
4790 bool CanonicalizeIfNotNan =
4791 match(V: MatchCmp0, P: m_FCanonicalize(Op0: m_Specific(V: Cmp0)));
4792
4793 if (RcpIfNan || CanonicalizeIfNotNan) {
4794 const fltSemantics &FPSem = EltTy->getFltSemantics();
4795 DenormalMode Mode = F.getDenormalMode(FPType: FPSem);
4796
4797 if (RcpIfNan) {
4798 if (Mode == DenormalMode::getIEEE()) {
4799 // Special case for the other select operand. Otherwise, we may
4800 // need to insert freeze on Cmp0 in the compare and select.
4801 if (CanonicalizeIfNotNan)
4802 return replaceInstUsesWith(I&: SI, V: Cmp0);
4803
4804 if (isGuaranteedNotToBeUndef(V: Cmp0, AC: &AC, CtxI: &SI, DT: &DT)) {
4805 // select (fcmp ord x, 0), y, (fdiv 1, x)
4806 // => select (fcmp ord x, 0), y, x
4807 //
4808 // select (fcmp uno x, 0), (fdiv 1, x), y
4809 // => select (fcmp uno x, 0), x, y
4810 replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 2 : 1, V: Cmp0);
4811 return &SI;
4812 }
4813
4814 auto *FrCmp0 = InsertNewInstBefore(
4815 New: new FreezeInst(Cmp0, Cmp0->getName() + ".fr"),
4816 Old: FCmp->getIterator());
4817
4818 replaceOperand(I&: *FCmp, OpNum: 0, V: FrCmp0);
4819 return replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 2 : 1,
4820 V: FrCmp0);
4821 }
4822 }
4823
4824 if (CanonicalizeIfNotNan) {
4825 // IEEE handling does not have non-canonical values, so the
4826 // canonicalize can be dropped for direct replacement without
4827 // looking for the intermediate maybe-canonicalizing operation.
4828 if (Mode == DenormalMode::getIEEE()) {
4829 // select (fcmp ord x, 0), canonicalize(x), y
4830 // => select (fcmp ord x, 0), x, y
4831
4832 replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 1 : 2, V: Cmp0);
4833 return &SI;
4834 }
4835
4836 // If denormals may be flushed, we need to retain the canonicalize
4837 // call. This introduces a canonicalization on the nan path, which
4838 // we are not free to do as that could change the sign bit or
4839 // payload bits. We can only do this if there were a no-op like
4840 // floating-point instruction which may have changed the nan bits
4841 // anyway.
4842
4843 // Leave the dynamic mode case alone. This would introduce new
4844 // constraints if the mode may be refined later.
4845 if (RcpIfNan && (Mode.inputsAreZero() || Mode.outputsAreZero()))
4846 return replaceInstUsesWith(I&: SI, V: MatchCmp0);
4847 assert(RcpIfNan || Mode != DenormalMode::getIEEE());
4848 }
4849 }
4850 }
4851 }
4852 }
4853
4854 if (SIFPOp) {
4855 // TODO: Try to forward-propagate FMF from select arms to the select.
4856
4857 auto *FCmp = dyn_cast<FCmpInst>(Val: CondVal);
4858
4859 // Canonicalize select of FP values where NaN and -0.0 are not valid as
4860 // minnum/maxnum intrinsics.
4861 //
4862 // Note that the `nnan` flag is propagated from the comparison, not from the
4863 // select. While it's technically possible to transform a `fcmp` + `select
4864 // nnan` to a `minnum`/`maxnum` call *without* an `nnan`, that would be a
4865 // pessimization in practice. Many targets can't map `minnum`/`maxnum` to a
4866 // single instruction, and if they cannot prove the absence of NaN, must
4867 // lower it to a routine or a libcall. There are additional reasons besides
4868 // performance to avoid introducing libcalls where none existed before
4869 // (https://github.com/llvm/llvm-project/issues/54554).
4870 //
4871 // As such, we want to ensure that the generated `minnum`/`maxnum` intrinsic
4872 // has the `nnan nsz` flags, which allow it to be lowered *back* to a
4873 // fcmp+select if that's the best way to express it on the target.
4874 if (FCmp && FCmp->hasNoNaNs() &&
4875 (SIFPOp->hasNoSignedZeros() || isSelectZeroSignInsignificant(SI))) {
4876 Value *X, *Y;
4877 if (match(V: &SI, P: m_OrdOrUnordFMax(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
4878 Value *BinIntr =
4879 Builder.CreateBinaryIntrinsic(ID: Intrinsic::maxnum, LHS: X, RHS: Y, FMFSource: &SI);
4880 if (auto *BinIntrInst = dyn_cast<Instruction>(Val: BinIntr)) {
4881 // `ninf` must be propagated from the comparison too, rather than the
4882 // select: https://github.com/llvm/llvm-project/pull/136433
4883 BinIntrInst->setHasNoInfs(FCmp->hasNoInfs());
4884 // The `nsz` flag is a precondition, so let's ensure it's always added
4885 // to the min/max operation, even if it wasn't on the select. This
4886 // could happen if the select doesn't have `nsz`, but no use of the
4887 // result can observe the sign of zero.
4888 BinIntrInst->setHasNoSignedZeros(true);
4889 // As mentioned above, `nnan` is also a precondition, so we always set
4890 // the flag.
4891 BinIntrInst->setHasNoNaNs(true);
4892 }
4893 return replaceInstUsesWith(I&: SI, V: BinIntr);
4894 }
4895
4896 if (match(V: &SI, P: m_OrdOrUnordFMin(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
4897 Value *BinIntr =
4898 Builder.CreateBinaryIntrinsic(ID: Intrinsic::minnum, LHS: X, RHS: Y, FMFSource: &SI);
4899 if (auto *BinIntrInst = dyn_cast<Instruction>(Val: BinIntr)) {
4900 BinIntrInst->setHasNoInfs(FCmp->hasNoInfs());
4901 BinIntrInst->setHasNoSignedZeros(true);
4902 BinIntrInst->setHasNoNaNs(true);
4903 }
4904 return replaceInstUsesWith(I&: SI, V: BinIntr);
4905 }
4906 }
4907 }
4908
4909 // Fold selecting to fabs.
4910 if (Instruction *Fabs = foldSelectWithFCmpToFabs(SI, IC&: *this))
4911 return Fabs;
4912
4913 if (Instruction *I = foldSelectOfOrderedFAbsCmpOfNaNScrubbedValue(SI, IC&: *this))
4914 return I;
4915
4916 // See if we are selecting two values based on a comparison of the two values.
4917 if (CmpInst *CI = dyn_cast<CmpInst>(Val: CondVal))
4918 if (Instruction *NewSel = foldSelectValueEquivalence(Sel&: SI, Cmp&: *CI))
4919 return NewSel;
4920
4921 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Val: CondVal))
4922 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
4923 return Result;
4924
4925 if (Instruction *V =
4926 foldSelectICmpAndAnd(SelType, Cond: CondVal, TVal: TrueVal, FVal: FalseVal, Builder))
4927 return V;
4928
4929 if (Value *V = foldSelectBitTest(Sel&: SI, CondVal, TrueVal, FalseVal, Builder, SQ))
4930 return replaceInstUsesWith(I&: SI, V);
4931
4932 if (Instruction *Add = foldAddSubSelect(SI, Builder))
4933 return Add;
4934 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
4935 return Add;
4936 if (Instruction *Or = foldSetClearBits(Sel&: SI, Builder))
4937 return Or;
4938 if (Instruction *Mul = foldSelectZeroOrFixedOp(SI, IC&: *this))
4939 return Mul;
4940
4941 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4942 auto *TI = dyn_cast<Instruction>(Val: TrueVal);
4943 auto *FI = dyn_cast<Instruction>(Val: FalseVal);
4944 if (TI && FI && TI->getOpcode() == FI->getOpcode())
4945 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
4946 return IV;
4947
4948 if (Instruction *I = foldSelectIntrinsic(SI))
4949 return I;
4950
4951 if (Instruction *I = foldSelectExtConst(Sel&: SI))
4952 return I;
4953
4954 if (Instruction *I = foldSelectWithSRem(SI, IC&: *this, Builder))
4955 return I;
4956
4957 // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
4958 // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
4959 auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
4960 bool Swap) -> GetElementPtrInst * {
4961 Value *Ptr = Gep->getPointerOperand();
4962 if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
4963 !Gep->hasOneUse())
4964 return nullptr;
4965 Value *Idx = Gep->getOperand(i_nocapture: 1);
4966 if (isa<VectorType>(Val: CondVal->getType()) && !isa<VectorType>(Val: Idx->getType()))
4967 return nullptr;
4968 Type *ElementType = Gep->getSourceElementType();
4969 Value *NewT = Idx;
4970 Value *NewF = Constant::getNullValue(Ty: Idx->getType());
4971 if (Swap)
4972 std::swap(a&: NewT, b&: NewF);
4973 Value *NewSI =
4974 Builder.CreateSelect(C: CondVal, True: NewT, False: NewF, Name: SI.getName() + ".idx", MDFrom: &SI);
4975 return GetElementPtrInst::Create(PointeeType: ElementType, Ptr, IdxList: NewSI,
4976 NW: Gep->getNoWrapFlags());
4977 };
4978 if (auto *TrueGep = dyn_cast<GetElementPtrInst>(Val: TrueVal))
4979 if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
4980 return NewGep;
4981 if (auto *FalseGep = dyn_cast<GetElementPtrInst>(Val: FalseVal))
4982 if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
4983 return NewGep;
4984
4985 // See if we can fold the select into one of our operands.
4986 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
4987 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
4988 return FoldI;
4989
4990 Value *LHS, *RHS;
4991 Instruction::CastOps CastOp;
4992 SelectPatternResult SPR = matchSelectPattern(V: &SI, LHS, RHS, CastOp: &CastOp);
4993 auto SPF = SPR.Flavor;
4994 if (SPF) {
4995 Value *LHS2, *RHS2;
4996 if (SelectPatternFlavor SPF2 = matchSelectPattern(V: LHS, LHS&: LHS2, RHS&: RHS2).Flavor)
4997 if (Instruction *R = foldSPFofSPF(Inner: cast<Instruction>(Val: LHS), SPF1: SPF2, A: LHS2,
4998 B: RHS2, Outer&: SI, SPF2: SPF, C: RHS))
4999 return R;
5000 if (SelectPatternFlavor SPF2 = matchSelectPattern(V: RHS, LHS&: LHS2, RHS&: RHS2).Flavor)
5001 if (Instruction *R = foldSPFofSPF(Inner: cast<Instruction>(Val: RHS), SPF1: SPF2, A: LHS2,
5002 B: RHS2, Outer&: SI, SPF2: SPF, C: LHS))
5003 return R;
5004 }
5005
5006 if (SelectPatternResult::isMinOrMax(SPF)) {
5007 // Canonicalize so that
5008 // - type casts are outside select patterns.
5009 // - float clamp is transformed to min/max pattern
5010
5011 bool IsCastNeeded = LHS->getType() != SelType;
5012 Value *CmpLHS = cast<CmpInst>(Val: CondVal)->getOperand(i_nocapture: 0);
5013 Value *CmpRHS = cast<CmpInst>(Val: CondVal)->getOperand(i_nocapture: 1);
5014 if (IsCastNeeded ||
5015 (LHS->getType()->isFPOrFPVectorTy() &&
5016 ((CmpLHS != LHS && CmpLHS != RHS) ||
5017 (CmpRHS != LHS && CmpRHS != RHS)))) {
5018 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, Ordered: SPR.Ordered);
5019
5020 Value *Cmp;
5021 if (CmpInst::isIntPredicate(P: MinMaxPred))
5022 Cmp = Builder.CreateICmp(P: MinMaxPred, LHS, RHS);
5023 else
5024 Cmp = Builder.CreateFCmpFMF(P: MinMaxPred, LHS, RHS,
5025 FMFSource: cast<Instruction>(Val: SI.getCondition()));
5026
5027 Value *NewSI = Builder.CreateSelect(C: Cmp, True: LHS, False: RHS, Name: SI.getName(), MDFrom: &SI);
5028 if (!IsCastNeeded)
5029 return replaceInstUsesWith(I&: SI, V: NewSI);
5030
5031 Value *NewCast = Builder.CreateCast(Op: CastOp, V: NewSI, DestTy: SelType);
5032 return replaceInstUsesWith(I&: SI, V: NewCast);
5033 }
5034 }
5035 }
5036
5037 // See if we can fold the select into a phi node if the condition is a select.
5038 if (auto *PN = dyn_cast<PHINode>(Val: SI.getCondition()))
5039 if (Instruction *NV = foldOpIntoPhi(I&: SI, PN))
5040 return NV;
5041
5042 if (SelectInst *TrueSI = dyn_cast<SelectInst>(Val: TrueVal)) {
5043 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
5044 // Fold nested selects if the inner condition can be implied by the outer
5045 // condition.
5046 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
5047 SI&: *TrueSI, CondVal, /*CondIsTrue=*/true, DL))
5048 return replaceOperand(I&: SI, OpNum: 1, V);
5049
5050 // We choose this as normal form to enable folding on the And and
5051 // shortening paths for the values (this helps getUnderlyingObjects() for
5052 // example).
5053 if (TrueSI->hasOneUse()) {
5054 Value *And = nullptr, *OtherVal = nullptr;
5055 // select(C0, select(C1, a, b), b) -> select(C0&&C1, a, b)
5056 if (TrueSI->getFalseValue() == FalseVal) {
5057 And = Builder.CreateLogicalAnd(Cond1: CondVal, Cond2: TrueSI->getCondition(), Name: "",
5058 MDFrom: &SI);
5059 OtherVal = TrueSI->getTrueValue();
5060 }
5061 // select(C0, select(C1, b, a), b) -> select(C0&&!C1, a, b)
5062 else if (TrueSI->getTrueValue() == FalseVal) {
5063 Value *InvertedCond = Builder.CreateNot(V: TrueSI->getCondition());
5064 And = Builder.CreateLogicalAnd(Cond1: CondVal, Cond2: InvertedCond, Name: "", MDFrom: &SI);
5065 OtherVal = TrueSI->getFalseValue();
5066 }
5067 if (And && OtherVal) {
5068 replaceOperand(I&: SI, OpNum: 0, V: And);
5069 replaceOperand(I&: SI, OpNum: 1, V: OtherVal);
5070 setExplicitlyUnknownBranchWeightsIfProfiled(I&: SI, DEBUG_TYPE);
5071 return &SI;
5072 }
5073 }
5074 }
5075 }
5076 if (SelectInst *FalseSI = dyn_cast<SelectInst>(Val: FalseVal)) {
5077 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
5078 // Fold nested selects if the inner condition can be implied by the outer
5079 // condition.
5080 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
5081 SI&: *FalseSI, CondVal, /*CondIsTrue=*/false, DL))
5082 return replaceOperand(I&: SI, OpNum: 2, V);
5083
5084 if (FalseSI->hasOneUse()) {
5085 Value *Or = nullptr, *OtherVal = nullptr;
5086 // select(C0, a, select(C1, a, b)) -> select(C0||C1, a, b)
5087 if (FalseSI->getTrueValue() == TrueVal) {
5088 Or = Builder.CreateLogicalOr(Cond1: CondVal, Cond2: FalseSI->getCondition(), Name: "",
5089 MDFrom: &SI);
5090 OtherVal = FalseSI->getFalseValue();
5091 }
5092 // select(C0, a, select(C1, b, a)) -> select(C0||!C1, a, b)
5093 else if (FalseSI->getFalseValue() == TrueVal) {
5094 Value *InvertedCond = Builder.CreateNot(V: FalseSI->getCondition());
5095 Or = Builder.CreateLogicalOr(Cond1: CondVal, Cond2: InvertedCond, Name: "", MDFrom: &SI);
5096 OtherVal = FalseSI->getTrueValue();
5097 }
5098 if (Or && OtherVal) {
5099 replaceOperand(I&: SI, OpNum: 0, V: Or);
5100 replaceOperand(I&: SI, OpNum: 2, V: OtherVal);
5101 setExplicitlyUnknownBranchWeightsIfProfiled(I&: SI, DEBUG_TYPE);
5102 return &SI;
5103 }
5104 }
5105 }
5106 }
5107
5108 // Try to simplify a binop sandwiched between 2 selects with the same
5109 // condition. This is not valid for div/rem because the select might be
5110 // preventing a division-by-zero.
5111 // TODO: A div/rem restriction is conservative; use something like
5112 // isSafeToSpeculativelyExecute().
5113 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
5114 BinaryOperator *TrueBO;
5115 if (match(V: TrueVal, P: m_OneUse(SubPattern: m_BinOp(I&: TrueBO))) && !TrueBO->isIntDivRem()) {
5116 if (auto *TrueBOSI = dyn_cast<SelectInst>(Val: TrueBO->getOperand(i_nocapture: 0))) {
5117 if (TrueBOSI->getCondition() == CondVal) {
5118 replaceOperand(I&: *TrueBO, OpNum: 0, V: TrueBOSI->getTrueValue());
5119 Worklist.push(I: TrueBO);
5120 return &SI;
5121 }
5122 }
5123 if (auto *TrueBOSI = dyn_cast<SelectInst>(Val: TrueBO->getOperand(i_nocapture: 1))) {
5124 if (TrueBOSI->getCondition() == CondVal) {
5125 replaceOperand(I&: *TrueBO, OpNum: 1, V: TrueBOSI->getTrueValue());
5126 Worklist.push(I: TrueBO);
5127 return &SI;
5128 }
5129 }
5130 }
5131
5132 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
5133 BinaryOperator *FalseBO;
5134 if (match(V: FalseVal, P: m_OneUse(SubPattern: m_BinOp(I&: FalseBO))) && !FalseBO->isIntDivRem()) {
5135 if (auto *FalseBOSI = dyn_cast<SelectInst>(Val: FalseBO->getOperand(i_nocapture: 0))) {
5136 if (FalseBOSI->getCondition() == CondVal) {
5137 replaceOperand(I&: *FalseBO, OpNum: 0, V: FalseBOSI->getFalseValue());
5138 Worklist.push(I: FalseBO);
5139 return &SI;
5140 }
5141 }
5142 if (auto *FalseBOSI = dyn_cast<SelectInst>(Val: FalseBO->getOperand(i_nocapture: 1))) {
5143 if (FalseBOSI->getCondition() == CondVal) {
5144 replaceOperand(I&: *FalseBO, OpNum: 1, V: FalseBOSI->getFalseValue());
5145 Worklist.push(I: FalseBO);
5146 return &SI;
5147 }
5148 }
5149 }
5150
5151 Value *NotCond;
5152 if (match(V: CondVal, P: m_Not(V: m_Value(V&: NotCond))) &&
5153 !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
5154 replaceOperand(I&: SI, OpNum: 0, V: NotCond);
5155 SI.swapValues();
5156 SI.swapProfMetadata();
5157 return &SI;
5158 }
5159
5160 if (Instruction *I = foldVectorSelect(Sel&: SI))
5161 return I;
5162
5163 // If we can compute the condition, there's no need for a select.
5164 // Like the above fold, we are attempting to reduce compile-time cost by
5165 // putting this fold here with limitations rather than in InstSimplify.
5166 // The motivation for this call into value tracking is to take advantage of
5167 // the assumption cache, so make sure that is populated.
5168 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
5169 KnownBits Known(1);
5170 computeKnownBits(V: CondVal, Known, CxtI: &SI);
5171 if (Known.One.isOne())
5172 return replaceInstUsesWith(I&: SI, V: TrueVal);
5173 if (Known.Zero.isOne())
5174 return replaceInstUsesWith(I&: SI, V: FalseVal);
5175 }
5176
5177 if (Instruction *BitCastSel = foldSelectCmpBitcasts(Sel&: SI, Builder))
5178 return BitCastSel;
5179
5180 // Simplify selects that test the returned flag of cmpxchg instructions.
5181 if (Value *V = foldSelectCmpXchg(SI))
5182 return replaceInstUsesWith(I&: SI, V);
5183
5184 if (Instruction *Select = foldSelectBinOpIdentity(Sel&: SI, TLI, IC&: *this))
5185 return Select;
5186
5187 if (Instruction *Funnel = foldSelectFunnelShift(Sel&: SI, Builder))
5188 return Funnel;
5189
5190 if (Instruction *Copysign = foldSelectToCopysign(Sel&: SI, Builder))
5191 return Copysign;
5192
5193 if (Instruction *PN = foldSelectToPhi(Sel&: SI, DT, Builder))
5194 return replaceInstUsesWith(I&: SI, V: PN);
5195
5196 if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
5197 return replaceInstUsesWith(I&: SI, V);
5198
5199 if (Value *V = foldSelectIntoAddConstant(SI, Builder))
5200 return replaceInstUsesWith(I&: SI, V);
5201
5202 // select(mask, mload(ptr,mask,0), 0) -> mload(ptr,mask,0)
5203 // Load inst is intentionally not checked for hasOneUse()
5204 if (match(V: FalseVal, P: m_Zero()) &&
5205 (match(V: TrueVal, P: m_MaskedLoad(Op0: m_Value(), Op1: m_Specific(V: CondVal),
5206 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))) ||
5207 match(V: TrueVal, P: m_MaskedGather(Op0: m_Value(), Op1: m_Specific(V: CondVal),
5208 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))))) {
5209 auto *MaskedInst = cast<IntrinsicInst>(Val: TrueVal);
5210 if (isa<UndefValue>(Val: MaskedInst->getArgOperand(i: 2)))
5211 MaskedInst->setArgOperand(i: 2, v: FalseVal /* Zero */);
5212 return replaceInstUsesWith(I&: SI, V: MaskedInst);
5213 }
5214
5215 Value *Mask;
5216 if (match(V: TrueVal, P: m_Zero()) &&
5217 (match(V: FalseVal, P: m_MaskedLoad(Op0: m_Value(), Op1: m_Value(V&: Mask),
5218 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))) ||
5219 match(V: FalseVal, P: m_MaskedGather(Op0: m_Value(), Op1: m_Value(V&: Mask),
5220 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero())))) &&
5221 (CondVal->getType() == Mask->getType())) {
5222 // We can remove the select by ensuring the load zeros all lanes the
5223 // select would have. We determine this by proving there is no overlap
5224 // between the load and select masks.
5225 // (i.e (load_mask & select_mask) == 0 == no overlap)
5226 bool CanMergeSelectIntoLoad = false;
5227 if (Value *V = simplifyAndInst(LHS: CondVal, RHS: Mask, Q: SQ.getWithInstruction(I: &SI)))
5228 CanMergeSelectIntoLoad = match(V, P: m_Zero());
5229
5230 if (CanMergeSelectIntoLoad) {
5231 auto *MaskedInst = cast<IntrinsicInst>(Val: FalseVal);
5232 if (isa<UndefValue>(Val: MaskedInst->getArgOperand(i: 2)))
5233 MaskedInst->setArgOperand(i: 2, v: TrueVal /* Zero */);
5234 return replaceInstUsesWith(I&: SI, V: MaskedInst);
5235 }
5236 }
5237
5238 if (Instruction *I = foldSelectOfSymmetricSelect(OuterSelVal&: SI, Builder))
5239 return I;
5240
5241 if (Instruction *I = foldNestedSelects(OuterSelVal&: SI, Builder))
5242 return I;
5243
5244 // Match logical variants of the pattern,
5245 // and transform them iff that gets rid of inversions.
5246 // (~x) | y --> ~(x & (~y))
5247 // (~x) & y --> ~(x | (~y))
5248 if (sinkNotIntoOtherHandOfLogicalOp(I&: SI))
5249 return &SI;
5250
5251 if (Instruction *I = foldBitCeil(SI, Builder, IC&: *this))
5252 return I;
5253
5254 if (Instruction *I = foldSelectToCmp(SI))
5255 return I;
5256
5257 if (Instruction *I = foldSelectEqualityTest(Sel&: SI))
5258 return I;
5259
5260 // Fold:
5261 // (select A && B, T, F) -> (select A, (select B, T, F), F)
5262 // (select A || B, T, F) -> (select A, T, (select B, T, F))
5263 // if (select B, T, F) is foldable.
5264 // TODO: preserve FMF flags
5265 auto FoldSelectWithAndOrCond = [&](bool IsAnd, Value *A,
5266 Value *B) -> Instruction * {
5267 if (Value *V = simplifySelectInst(Cond: B, TrueVal, FalseVal, FMF,
5268 Q: SQ.getWithInstruction(I: &SI))) {
5269 Value *NewTrueVal = IsAnd ? V : TrueVal;
5270 Value *NewFalseVal = IsAnd ? FalseVal : V;
5271
5272 // If the True and False values don't change, then preserve the branch
5273 // metadata of the original select as the net effect of this change is to
5274 // simplify the conditional.
5275 Instruction *MDFrom = nullptr;
5276 if (NewTrueVal == TrueVal && NewFalseVal == FalseVal) {
5277 MDFrom = &SI;
5278 }
5279 return SelectInst::Create(C: A, S1: NewTrueVal, S2: NewFalseVal, NameStr: "", InsertBefore: nullptr,
5280 MDFrom);
5281 }
5282
5283 // Is (select B, T, F) a SPF?
5284 if (CondVal->hasOneUse() && SelType->isIntOrIntVectorTy()) {
5285 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Val: B))
5286 if (Value *V = canonicalizeSPF(Cmp&: *Cmp, TrueVal, FalseVal, IC&: *this)) {
5287 return SelectInst::Create(
5288 C: A, S1: IsAnd ? V : TrueVal, S2: IsAnd ? FalseVal : V, NameStr: "", InsertBefore: nullptr,
5289 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : &SI);
5290 }
5291 }
5292
5293 return nullptr;
5294 };
5295
5296 Value *LHS, *RHS;
5297 if (match(V: CondVal, P: m_And(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5298 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
5299 return I;
5300 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, RHS, LHS))
5301 return I;
5302 } else if (match(V: CondVal, P: m_Or(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5303 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
5304 return I;
5305 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, RHS, LHS))
5306 return I;
5307 } else {
5308 // We cannot swap the operands of logical and/or.
5309 // TODO: Can we swap the operands by inserting a freeze?
5310 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5311 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
5312 return I;
5313 } else if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5314 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
5315 return I;
5316 }
5317 }
5318
5319 // select Cond, !X, X -> xor Cond, X
5320 if (CondVal->getType() == SI.getType() && isKnownInversion(X: FalseVal, Y: TrueVal))
5321 return BinaryOperator::CreateXor(V1: CondVal, V2: FalseVal);
5322
5323 // For vectors, this transform is only safe if the simplification does not
5324 // look through any lane-crossing operations. For now, limit to scalars only.
5325 if (SelType->isIntegerTy() &&
5326 (!isa<Constant>(Val: TrueVal) || !isa<Constant>(Val: FalseVal))) {
5327 // Try to simplify select arms based on KnownBits implied by the condition.
5328 CondContext CC(CondVal);
5329 findValuesAffectedByCondition(Cond: CondVal, /*IsAssume=*/false, InsertAffected: [&](Value *V) {
5330 CC.AffectedValues.insert(Ptr: V);
5331 });
5332 SimplifyQuery Q = SQ.getWithInstruction(I: &SI).getWithCondContext(CC);
5333 if (!CC.AffectedValues.empty()) {
5334 if (!isa<Constant>(Val: TrueVal) &&
5335 hasAffectedValue(V: TrueVal, Affected&: CC.AffectedValues, /*Depth=*/0)) {
5336 KnownBits Known = llvm::computeKnownBits(V: TrueVal, Q);
5337 if (Known.isConstant())
5338 return replaceOperand(I&: SI, OpNum: 1,
5339 V: ConstantInt::get(Ty: SelType, V: Known.getConstant()));
5340 }
5341
5342 CC.Invert = true;
5343 if (!isa<Constant>(Val: FalseVal) &&
5344 hasAffectedValue(V: FalseVal, Affected&: CC.AffectedValues, /*Depth=*/0)) {
5345 KnownBits Known = llvm::computeKnownBits(V: FalseVal, Q);
5346 if (Known.isConstant())
5347 return replaceOperand(I&: SI, OpNum: 2,
5348 V: ConstantInt::get(Ty: SelType, V: Known.getConstant()));
5349 }
5350 }
5351 }
5352
5353 // select (trunc nuw X to i1), X, Y --> select (trunc nuw X to i1), 1, Y
5354 // select (trunc nuw X to i1), Y, X --> select (trunc nuw X to i1), Y, 0
5355 // select (trunc nsw X to i1), X, Y --> select (trunc nsw X to i1), -1, Y
5356 // select (trunc nsw X to i1), Y, X --> select (trunc nsw X to i1), Y, 0
5357 Value *Trunc;
5358 if (match(V: CondVal, P: m_NUWTrunc(Op: m_Value(V&: Trunc))) && !isa<Constant>(Val: Trunc)) {
5359 if (TrueVal == Trunc)
5360 return replaceOperand(I&: SI, OpNum: 1, V: ConstantInt::get(Ty: TrueVal->getType(), V: 1));
5361 if (FalseVal == Trunc)
5362 return replaceOperand(I&: SI, OpNum: 2, V: ConstantInt::get(Ty: FalseVal->getType(), V: 0));
5363 }
5364 if (match(V: CondVal, P: m_NSWTrunc(Op: m_Value(V&: Trunc))) && !isa<Constant>(Val: Trunc)) {
5365 if (TrueVal == Trunc)
5366 return replaceOperand(I&: SI, OpNum: 1,
5367 V: Constant::getAllOnesValue(Ty: TrueVal->getType()));
5368 if (FalseVal == Trunc)
5369 return replaceOperand(I&: SI, OpNum: 2, V: ConstantInt::get(Ty: FalseVal->getType(), V: 0));
5370 }
5371
5372 if (match(V: CondVal, P: m_Trunc(Op: m_Value(V&: Trunc))) && Trunc->getType() == SelType) {
5373 if (match(V: FalseVal, P: m_Zero()) && impliesPoison(ValAssumedPoison: TrueVal, V: CondVal) &&
5374 llvm::computeKnownBits(V: TrueVal, Q: SQ.getWithInstruction(I: &SI))
5375 .countMaxActiveBits() == 1)
5376 return BinaryOperator::CreateAnd(V1: Trunc, V2: TrueVal);
5377
5378 if (cast<TruncInst>(Val: CondVal)->hasNoUnsignedWrap() &&
5379 match(V: TrueVal, P: m_One()) && impliesPoison(ValAssumedPoison: FalseVal, V: CondVal) &&
5380 llvm::computeKnownBits(V: FalseVal, Q: SQ.getWithInstruction(I: &SI))
5381 .countMaxActiveBits() == 1) {
5382 return BinaryOperator::CreateOr(V1: Trunc, V2: FalseVal);
5383 }
5384 }
5385
5386 Value *MaskedLoadPtr;
5387 if (match(V: TrueVal, P: m_OneUse(SubPattern: m_MaskedLoad(Op0: m_Value(V&: MaskedLoadPtr),
5388 Op1: m_Specific(V: CondVal), Op2: m_Value())))) {
5389 auto *LoadInst = cast<IntrinsicInst>(Val: TrueVal);
5390 // Keep the load at its original position to avoid crossing writes. The new
5391 // passthrough must therefore be available there.
5392 if (DT.dominates(Def: FalseVal, User: LoadInst)) {
5393 Builder.SetInsertPoint(LoadInst);
5394 Instruction *In = Builder.CreateMaskedLoad(
5395 Ty: TrueVal->getType(), Ptr: MaskedLoadPtr,
5396 Alignment: LoadInst->getParamAlign(ArgNo: 0).valueOrOne(), Mask: CondVal, PassThru: FalseVal);
5397 In->setAAMetadata(LoadInst->getAAMetadata());
5398 return replaceInstUsesWith(I&: SI, V: In);
5399 }
5400 }
5401
5402 // Canonicalize sign function ashr pattern: select (icmp slt X, 1), ashr X,
5403 // bitwidth-1, 1 -> scmp(X, 0)
5404 // Also handles: select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
5405 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5406 CmpPredicate Pred;
5407 Value *CmpLHS, *CmpRHS;
5408
5409 // Canonicalize sign function ashr patterns:
5410 // select (icmp slt X, 1), ashr X, bitwidth-1, 1 -> scmp(X, 0)
5411 // select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
5412 if (match(V: &SI, P: m_Select(C: m_ICmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS)),
5413 L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal))) &&
5414 ((Pred == ICmpInst::ICMP_SLT && match(V: CmpRHS, P: m_One()) &&
5415 match(V: TrueVal,
5416 P: m_AShr(L: m_Specific(V: CmpLHS), R: m_SpecificInt(V: BitWidth - 1))) &&
5417 match(V: FalseVal, P: m_One())) ||
5418 (Pred == ICmpInst::ICMP_SGT && match(V: CmpRHS, P: m_Zero()) &&
5419 match(V: TrueVal, P: m_One()) &&
5420 match(V: FalseVal,
5421 P: m_AShr(L: m_Specific(V: CmpLHS), R: m_SpecificInt(V: BitWidth - 1)))))) {
5422
5423 Function *Scmp = Intrinsic::getOrInsertDeclaration(
5424 M: SI.getModule(), id: Intrinsic::scmp, OverloadTys: {SI.getType(), SI.getType()});
5425 return CallInst::Create(Func: Scmp, Args: {CmpLHS, ConstantInt::get(Ty: SI.getType(), V: 0)});
5426 }
5427
5428 return nullptr;
5429}
5430