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