1//===- InstCombineMulDivRem.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 visit functions for mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/PatternMatch.h"
30#include "llvm/IR/Type.h"
31#include "llvm/IR/Value.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Transforms/InstCombine/InstCombiner.h"
35#include "llvm/Transforms/Utils/BuildLibCalls.h"
36#include <cassert>
37
38#define DEBUG_TYPE "instcombine"
39#include "llvm/Transforms/Utils/InstructionWorklist.h"
40
41using namespace llvm;
42using namespace PatternMatch;
43
44namespace llvm {
45extern cl::opt<bool> ProfcheckDisableMetadataFixes;
46}
47
48/// The specific integer value is used in a context where it is known to be
49/// non-zero. If this allows us to simplify the computation, do so and return
50/// the new operand, otherwise return null.
51static Value *simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC,
52 Instruction &CxtI) {
53 // If V has multiple uses, then we would have to do more analysis to determine
54 // if this is safe. For example, the use could be in dynamically unreached
55 // code.
56 if (!V->hasOneUse()) return nullptr;
57
58 bool MadeChange = false;
59
60 // ((1 << A) >>u B) --> (1 << (A-B))
61 // Because V cannot be zero, we know that B is less than A.
62 Value *A = nullptr, *B = nullptr, *One = nullptr;
63 if (match(V, P: m_LShr(L: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: One), R: m_Value(V&: A))), R: m_Value(V&: B))) &&
64 match(V: One, P: m_One())) {
65 A = IC.Builder.CreateSub(LHS: A, RHS: B);
66 return IC.Builder.CreateShl(LHS: One, RHS: A);
67 }
68
69 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
70 // inexact. Similarly for <<.
71 BinaryOperator *I = dyn_cast<BinaryOperator>(Val: V);
72 if (I && I->isLogicalShift() &&
73 IC.isKnownToBeAPowerOfTwo(V: I->getOperand(i_nocapture: 0), OrZero: false, CxtI: &CxtI)) {
74 // We know that this is an exact/nuw shift and that the input is a
75 // non-zero context as well.
76 {
77 IRBuilderBase::InsertPointGuard Guard(IC.Builder);
78 IC.Builder.SetInsertPoint(I);
79 if (Value *V2 = simplifyValueKnownNonZero(V: I->getOperand(i_nocapture: 0), IC, CxtI)) {
80 IC.replaceOperand(I&: *I, OpNum: 0, V: V2);
81 MadeChange = true;
82 }
83 }
84
85 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
86 I->setIsExact();
87 MadeChange = true;
88 }
89
90 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
91 I->setHasNoUnsignedWrap();
92 MadeChange = true;
93 }
94 }
95
96 // TODO: Lots more we could do here:
97 // If V is a phi node, we can call this on each of its operands.
98 // "select cond, X, 0" can simplify to "X".
99
100 return MadeChange ? V : nullptr;
101}
102
103// TODO: This is a specific form of a much more general pattern.
104// We could detect a select with any binop identity constant, or we
105// could use SimplifyBinOp to see if either arm of the select reduces.
106// But that needs to be done carefully and/or while removing potential
107// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
108static Value *foldMulSelectToNegate(BinaryOperator &I,
109 InstCombiner::BuilderTy &Builder) {
110 Value *Cond, *OtherOp;
111
112 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
113 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
114 if (match(V: &I, P: m_c_Mul(L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_One(), R: m_AllOnes())),
115 R: m_Value(V&: OtherOp)))) {
116 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
117 Value *Neg = Builder.CreateNeg(V: OtherOp, Name: "", HasNSW: HasAnyNoWrap);
118 return Builder.CreateSelect(C: Cond, True: OtherOp, False: Neg);
119 }
120 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
121 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
122 if (match(V: &I, P: m_c_Mul(L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_AllOnes(), R: m_One())),
123 R: m_Value(V&: OtherOp)))) {
124 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
125 Value *Neg = Builder.CreateNeg(V: OtherOp, Name: "", HasNSW: HasAnyNoWrap);
126 return Builder.CreateSelect(C: Cond, True: Neg, False: OtherOp);
127 }
128
129 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
130 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
131 if (match(V: &I, P: m_c_FMul(L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_SpecificFP(V: 1.0),
132 R: m_SpecificFP(V: -1.0))),
133 R: m_Value(V&: OtherOp))))
134 return Builder.CreateSelectFMF(C: Cond, True: OtherOp,
135 False: Builder.CreateFNegFMF(V: OtherOp, FMFSource: &I), FMFSource: &I);
136
137 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
138 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
139 if (match(V: &I, P: m_c_FMul(L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_SpecificFP(V: -1.0),
140 R: m_SpecificFP(V: 1.0))),
141 R: m_Value(V&: OtherOp))))
142 return Builder.CreateSelectFMF(C: Cond, True: Builder.CreateFNegFMF(V: OtherOp, FMFSource: &I),
143 False: OtherOp, FMFSource: &I);
144
145 return nullptr;
146}
147
148/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
149/// Callers are expected to call this twice to handle commuted patterns.
150static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
151 InstCombiner::BuilderTy &Builder) {
152 Value *X = Mul.getOperand(i_nocapture: 0), *Y = Mul.getOperand(i_nocapture: 1);
153 if (CommuteOperands)
154 std::swap(a&: X, b&: Y);
155
156 const bool HasNSW = Mul.hasNoSignedWrap();
157 const bool HasNUW = Mul.hasNoUnsignedWrap();
158
159 // X * (1 << Z) --> X << Z
160 Value *Z;
161 if (match(V: Y, P: m_Shl(L: m_One(), R: m_Value(V&: Z)))) {
162 bool PropagateNSW = HasNSW && cast<ShlOperator>(Val: Y)->hasNoSignedWrap();
163 return Builder.CreateShl(LHS: X, RHS: Z, Name: Mul.getName(), HasNUW, HasNSW: PropagateNSW);
164 }
165
166 // Similar to above, but an increment of the shifted value becomes an add:
167 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
168 // This increases uses of X, so it may require a freeze, but that is still
169 // expected to be an improvement because it removes the multiply.
170 BinaryOperator *Shift;
171 if (match(V: Y, P: m_OneUse(SubPattern: m_Add(L: m_BinOp(I&: Shift), R: m_One()))) &&
172 match(V: Shift, P: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Z))))) {
173 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
174 Value *FrX = X;
175 if (!isGuaranteedNotToBeUndef(V: X))
176 FrX = Builder.CreateFreeze(V: X, Name: X->getName() + ".fr");
177 Value *Shl = Builder.CreateShl(LHS: FrX, RHS: Z, Name: "mulshl", HasNUW, HasNSW: PropagateNSW);
178 return Builder.CreateAdd(LHS: Shl, RHS: FrX, Name: Mul.getName(), HasNUW, HasNSW: PropagateNSW);
179 }
180
181 // Similar to above, but a decrement of the shifted value is disguised as
182 // 'not' and becomes a sub:
183 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
184 // This increases uses of X, so it may require a freeze, but that is still
185 // expected to be an improvement because it removes the multiply.
186 if (match(V: Y, P: m_OneUse(SubPattern: m_Not(V: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: Z))))))) {
187 Value *FrX = X;
188 if (!isGuaranteedNotToBeUndef(V: X))
189 FrX = Builder.CreateFreeze(V: X, Name: X->getName() + ".fr");
190 Value *Shl = Builder.CreateShl(LHS: FrX, RHS: Z, Name: "mulshl");
191 return Builder.CreateSub(LHS: Shl, RHS: FrX, Name: Mul.getName());
192 }
193
194 return nullptr;
195}
196
197Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
198 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
199 if (Value *V =
200 simplifyMulInst(LHS: Op0, RHS: Op1, IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(),
201 Q: SQ.getWithInstruction(I: &I)))
202 return replaceInstUsesWith(I, V);
203
204 if (SimplifyAssociativeOrCommutative(I))
205 return &I;
206
207 if (Instruction *X = foldVectorBinop(Inst&: I))
208 return X;
209
210 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
211 return Phi;
212
213 if (Value *V = foldUsingDistributiveLaws(I))
214 return replaceInstUsesWith(I, V);
215
216 Type *Ty = I.getType();
217 const unsigned BitWidth = Ty->getScalarSizeInBits();
218 const bool HasNSW = I.hasNoSignedWrap();
219 const bool HasNUW = I.hasNoUnsignedWrap();
220
221 // X * -1 --> 0 - X
222 if (match(V: Op1, P: m_AllOnes())) {
223 return HasNSW ? BinaryOperator::CreateNSWNeg(Op: Op0)
224 : BinaryOperator::CreateNeg(Op: Op0);
225 }
226
227 // Also allow combining multiply instructions on vectors.
228 {
229 Value *NewOp;
230 Constant *C1, *C2;
231 const APInt *IVal;
232 if (match(V: &I, P: m_Mul(L: m_Shl(L: m_Value(V&: NewOp), R: m_ImmConstant(C&: C2)),
233 R: m_ImmConstant(C&: C1))) &&
234 match(V: C1, P: m_APInt(Res&: IVal))) {
235 // ((X << C2)*C1) == (X * (C1 << C2))
236 Constant *Shl =
237 ConstantFoldBinaryOpOperands(Opcode: Instruction::Shl, LHS: C1, RHS: C2, DL);
238 assert(Shl && "Constant folding of immediate constants failed");
239 BinaryOperator *Mul = cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 0));
240 BinaryOperator *BO = BinaryOperator::CreateMul(V1: NewOp, V2: Shl);
241 if (HasNUW && Mul->hasNoUnsignedWrap())
242 BO->setHasNoUnsignedWrap();
243 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
244 BO->setHasNoSignedWrap();
245 return BO;
246 }
247
248 if (match(V: &I, P: m_Mul(L: m_Value(V&: NewOp), R: m_Constant(C&: C1)))) {
249 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
250 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C: C1)) {
251 BinaryOperator *Shl = BinaryOperator::CreateShl(V1: NewOp, V2: NewCst);
252
253 if (HasNUW)
254 Shl->setHasNoUnsignedWrap();
255 if (HasNSW) {
256 const APInt *V;
257 if (match(V: NewCst, P: m_APInt(Res&: V)) && *V != V->getBitWidth() - 1)
258 Shl->setHasNoSignedWrap();
259 }
260
261 return Shl;
262 }
263 }
264 }
265
266 // mul (shr exact X, N), (2^N + 1) -> add (X, shr exact (X, N))
267 {
268 Value *NewOp;
269 const APInt *ShiftC;
270 const APInt *MulAP;
271 if (BitWidth > 2 &&
272 match(V: &I, P: m_Mul(L: m_Exact(SubPattern: m_Shr(L: m_Value(V&: NewOp), R: m_APInt(Res&: ShiftC))),
273 R: m_APInt(Res&: MulAP))) &&
274 (*MulAP - 1).isPowerOf2() && *ShiftC == MulAP->logBase2()) {
275 Value *BinOp = Op0;
276 BinaryOperator *OpBO = cast<BinaryOperator>(Val: Op0);
277
278 // mul nuw (ashr exact X, N) -> add nuw (X, lshr exact (X, N))
279 if (HasNUW && OpBO->getOpcode() == Instruction::AShr && OpBO->hasOneUse())
280 BinOp = Builder.CreateLShr(LHS: NewOp, RHS: ConstantInt::get(Ty, V: *ShiftC), Name: "",
281 /*isExact=*/true);
282
283 auto *NewAdd = BinaryOperator::CreateAdd(V1: NewOp, V2: BinOp);
284 if (HasNSW && (HasNUW || OpBO->getOpcode() == Instruction::LShr ||
285 ShiftC->getZExtValue() < BitWidth - 1))
286 NewAdd->setHasNoSignedWrap(true);
287
288 NewAdd->setHasNoUnsignedWrap(HasNUW);
289 return NewAdd;
290 }
291 }
292
293 if (Op0->hasOneUse() && match(V: Op1, P: m_NegatedPower2())) {
294 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
295 // The "* (1<<C)" thus becomes a potential shifting opportunity.
296 if (Value *NegOp0 =
297 Negator::Negate(/*IsNegation*/ LHSIsZero: true, IsNSW: HasNSW, Root: Op0, IC&: *this)) {
298 auto *Op1C = cast<Constant>(Val: Op1);
299 return replaceInstUsesWith(
300 I, V: Builder.CreateMul(LHS: NegOp0, RHS: ConstantExpr::getNeg(C: Op1C), Name: "",
301 /*HasNUW=*/false,
302 HasNSW: HasNSW && Op1C->isNotMinSignedValue()));
303 }
304
305 // Try to convert multiply of extended operand to narrow negate and shift
306 // for better analysis.
307 // This is valid if the shift amount (trailing zeros in the multiplier
308 // constant) clears more high bits than the bitwidth difference between
309 // source and destination types:
310 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
311 const APInt *NegPow2C;
312 Value *X;
313 if (match(V: Op0, P: m_ZExtOrSExt(Op: m_Value(V&: X))) &&
314 match(V: Op1, P: m_APIntAllowPoison(Res&: NegPow2C))) {
315 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
316 unsigned ShiftAmt = NegPow2C->countr_zero();
317 if (ShiftAmt >= BitWidth - SrcWidth) {
318 Value *N = Builder.CreateNeg(V: X, Name: X->getName() + ".neg");
319 Value *Z = Builder.CreateZExt(V: N, DestTy: Ty, Name: N->getName() + ".z");
320 return BinaryOperator::CreateShl(V1: Z, V2: ConstantInt::get(Ty, V: ShiftAmt));
321 }
322 }
323 }
324
325 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
326 return FoldedMul;
327
328 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Op&: I))
329 return FoldedLogic;
330
331 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
332 return replaceInstUsesWith(I, V: FoldedMul);
333
334 // Simplify mul instructions with a constant RHS.
335 Constant *MulC;
336 if (match(V: Op1, P: m_ImmConstant(C&: MulC))) {
337 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
338 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
339 Value *X;
340 Constant *C1;
341 if (match(V: Op0, P: m_OneUse(SubPattern: m_AddLike(L: m_Value(V&: X), R: m_ImmConstant(C&: C1))))) {
342 // C1*MulC simplifies to a tidier constant.
343 Value *NewC = Builder.CreateMul(LHS: C1, RHS: MulC);
344 auto *BOp0 = cast<BinaryOperator>(Val: Op0);
345 bool Op0NUW =
346 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
347 Value *NewMul = Builder.CreateMul(LHS: X, RHS: MulC);
348 auto *BO = BinaryOperator::CreateAdd(V1: NewMul, V2: NewC);
349 if (HasNUW && Op0NUW) {
350 // If NewMulBO is constant we also can set BO to nuw.
351 if (auto *NewMulBO = dyn_cast<BinaryOperator>(Val: NewMul))
352 NewMulBO->setHasNoUnsignedWrap();
353 BO->setHasNoUnsignedWrap();
354 }
355 return BO;
356 }
357 }
358
359 // abs(X) * abs(X) -> X * X
360 Value *X;
361 if (Op0 == Op1 && match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X))))
362 return BinaryOperator::CreateMul(V1: X, V2: X);
363
364 {
365 Value *Y;
366 // abs(X) * abs(Y) -> abs(X * Y)
367 if (I.hasNoSignedWrap() &&
368 match(V: Op0,
369 P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X), Op1: m_One()))) &&
370 match(V: Op1, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: Y), Op1: m_One()))))
371 return replaceInstUsesWith(
372 I, V: Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs,
373 LHS: Builder.CreateNSWMul(LHS: X, RHS: Y),
374 RHS: Builder.getTrue()));
375 }
376
377 // -X * C --> X * -C
378 Value *Y;
379 Constant *Op1C;
380 if (match(V: Op0, P: m_Neg(V: m_Value(V&: X))) && match(V: Op1, P: m_Constant(C&: Op1C)))
381 return BinaryOperator::CreateMul(V1: X, V2: ConstantExpr::getNeg(C: Op1C));
382
383 // -X * -Y --> X * Y
384 if (match(V: Op0, P: m_Neg(V: m_Value(V&: X))) && match(V: Op1, P: m_Neg(V: m_Value(V&: Y)))) {
385 auto *NewMul = BinaryOperator::CreateMul(V1: X, V2: Y);
386 if (HasNSW && cast<OverflowingBinaryOperator>(Val: Op0)->hasNoSignedWrap() &&
387 cast<OverflowingBinaryOperator>(Val: Op1)->hasNoSignedWrap())
388 NewMul->setHasNoSignedWrap();
389 return NewMul;
390 }
391
392 // -X * Y --> -(X * Y)
393 // X * -Y --> -(X * Y)
394 if (match(V: &I, P: m_c_Mul(L: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))), R: m_Value(V&: Y))))
395 return BinaryOperator::CreateNeg(Op: Builder.CreateMul(LHS: X, RHS: Y));
396
397 // (-X * Y) * -X --> (X * Y) * X
398 // (-X << Y) * -X --> (X << Y) * X
399 if (match(V: Op1, P: m_Neg(V: m_Value(V&: X)))) {
400 if (Value *NegOp0 = Negator::Negate(LHSIsZero: false, /*IsNSW*/ false, Root: Op0, IC&: *this))
401 return BinaryOperator::CreateMul(V1: NegOp0, V2: X);
402 }
403
404 if (Op0->hasOneUse()) {
405 // (mul (div exact X, C0), C1)
406 // -> (div exact X, C0 / C1)
407 // iff C0 % C1 == 0 and X / (C0 / C1) doesn't create UB.
408 const APInt *C1;
409 auto UDivCheck = [&C1](const APInt &C) { return C.urem(RHS: *C1).isZero(); };
410 auto SDivCheck = [&C1](const APInt &C) {
411 APInt Quot, Rem;
412 APInt::sdivrem(LHS: C, RHS: *C1, Quotient&: Quot, Remainder&: Rem);
413 return Rem.isZero() && !Quot.isAllOnes();
414 };
415 if (match(V: Op1, P: m_APInt(Res&: C1)) &&
416 (match(V: Op0, P: m_Exact(SubPattern: m_UDiv(L: m_Value(V&: X), R: m_CheckedInt(CheckFn: UDivCheck)))) ||
417 match(V: Op0, P: m_Exact(SubPattern: m_SDiv(L: m_Value(V&: X), R: m_CheckedInt(CheckFn: SDivCheck)))))) {
418 auto BOpc = cast<BinaryOperator>(Val: Op0)->getOpcode();
419 return BinaryOperator::CreateExact(
420 Opc: BOpc, V1: X,
421 V2: Builder.CreateBinOp(Opc: BOpc, LHS: cast<BinaryOperator>(Val: Op0)->getOperand(i_nocapture: 1),
422 RHS: Op1));
423 }
424 }
425
426 // (X / Y) * Y = X - (X % Y)
427 // (X / Y) * -Y = (X % Y) - X
428 {
429 Value *Y = Op1;
430 BinaryOperator *Div = dyn_cast<BinaryOperator>(Val: Op0);
431 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
432 Div->getOpcode() != Instruction::SDiv)) {
433 Y = Op0;
434 Div = dyn_cast<BinaryOperator>(Val: Op1);
435 }
436 Value *Neg = dyn_castNegVal(V: Y);
437 if (Div && Div->hasOneUse() &&
438 (Div->getOperand(i_nocapture: 1) == Y || Div->getOperand(i_nocapture: 1) == Neg) &&
439 (Div->getOpcode() == Instruction::UDiv ||
440 Div->getOpcode() == Instruction::SDiv)) {
441 Value *X = Div->getOperand(i_nocapture: 0), *DivOp1 = Div->getOperand(i_nocapture: 1);
442
443 // If the division is exact, X % Y is zero, so we end up with X or -X.
444 if (Div->isExact()) {
445 if (DivOp1 == Y)
446 return replaceInstUsesWith(I, V: X);
447 return BinaryOperator::CreateNeg(Op: X);
448 }
449
450 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
451 : Instruction::SRem;
452 // X must be frozen because we are increasing its number of uses.
453 Value *XFreeze = X;
454 if (!isGuaranteedNotToBeUndef(V: X))
455 XFreeze = Builder.CreateFreeze(V: X, Name: X->getName() + ".fr");
456 Value *Rem = Builder.CreateBinOp(Opc: RemOpc, LHS: XFreeze, RHS: DivOp1);
457 if (DivOp1 == Y)
458 return BinaryOperator::CreateSub(V1: XFreeze, V2: Rem);
459 return BinaryOperator::CreateSub(V1: Rem, V2: XFreeze);
460 }
461 }
462
463 // Fold the following two scenarios:
464 // 1) i1 mul -> i1 and.
465 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
466 // Note: We could use known bits to generalize this and related patterns with
467 // shifts/truncs
468 if (Ty->isIntOrIntVectorTy(BitWidth: 1) ||
469 (match(V: Op0, P: m_And(L: m_Value(), R: m_One())) &&
470 match(V: Op1, P: m_And(L: m_Value(), R: m_One()))))
471 return BinaryOperator::CreateAnd(V1: Op0, V2: Op1);
472
473 if (Value *R = foldMulShl1(Mul&: I, /* CommuteOperands */ false, Builder))
474 return replaceInstUsesWith(I, V: R);
475 if (Value *R = foldMulShl1(Mul&: I, /* CommuteOperands */ true, Builder))
476 return replaceInstUsesWith(I, V: R);
477
478 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
479 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
480 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
481 if (((match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: Op1, P: m_ZExt(Op: m_Value(V&: Y)))) ||
482 (match(V: Op0, P: m_SExt(Op: m_Value(V&: X))) && match(V: Op1, P: m_SExt(Op: m_Value(V&: Y))))) &&
483 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && X->getType() == Y->getType() &&
484 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
485 Value *And = Builder.CreateAnd(LHS: X, RHS: Y, Name: "mulbool");
486 return CastInst::Create(Instruction::ZExt, S: And, Ty);
487 }
488 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
489 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
490 // Note: -1 * 1 == 1 * -1 == -1
491 if (((match(V: Op0, P: m_SExt(Op: m_Value(V&: X))) && match(V: Op1, P: m_ZExt(Op: m_Value(V&: Y)))) ||
492 (match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: Op1, P: m_SExt(Op: m_Value(V&: Y))))) &&
493 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && X->getType() == Y->getType() &&
494 (Op0->hasOneUse() || Op1->hasOneUse())) {
495 Value *And = Builder.CreateAnd(LHS: X, RHS: Y, Name: "mulbool");
496 return CastInst::Create(Instruction::SExt, S: And, Ty);
497 }
498
499 // (zext bool X) * Y --> X ? Y : 0
500 // Y * (zext bool X) --> X ? Y : 0
501 if (match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1))
502 return createSelectInstWithUnknownProfile(C: X, S1: Op1,
503 S2: ConstantInt::getNullValue(Ty));
504 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1))
505 return createSelectInstWithUnknownProfile(C: X, S1: Op0,
506 S2: ConstantInt::getNullValue(Ty));
507
508 // mul (sext X), Y -> select X, -Y, 0
509 // mul Y, (sext X) -> select X, -Y, 0
510 if (match(V: &I, P: m_c_Mul(L: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X))), R: m_Value(V&: Y))) &&
511 X->getType()->isIntOrIntVectorTy(BitWidth: 1))
512 return createSelectInstWithUnknownProfile(
513 C: X, S1: Builder.CreateNeg(V: Y, Name: "", HasNSW: I.hasNoSignedWrap()),
514 S2: ConstantInt::getNullValue(Ty: Op0->getType()));
515
516 Constant *ImmC;
517 if (match(V: Op1, P: m_ImmConstant(C&: ImmC))) {
518 // (sext bool X) * C --> X ? -C : 0
519 if (match(V: Op0, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
520 Constant *NegC = ConstantExpr::getNeg(C: ImmC);
521 return createSelectInstWithUnknownProfile(C: X, S1: NegC,
522 S2: ConstantInt::getNullValue(Ty));
523 }
524
525 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
526 const APInt *C;
527 if (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: X), R: m_APInt(Res&: C)))) &&
528 *C == C->getBitWidth() - 1) {
529 Constant *NegC = ConstantExpr::getNeg(C: ImmC);
530 Value *IsNeg = Builder.CreateIsNeg(Arg: X, Name: "isneg");
531 return createSelectInstWithUnknownProfile(C: IsNeg, S1: NegC,
532 S2: ConstantInt::getNullValue(Ty));
533 }
534 }
535
536 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
537 // TODO: We are not checking one-use because the elimination of the multiply
538 // is better for analysis?
539 const APInt *C;
540 if (match(V: &I, P: m_c_BinOp(L: m_LShr(L: m_Value(V&: X), R: m_APInt(Res&: C)), R: m_Value(V&: Y))) &&
541 *C == C->getBitWidth() - 1) {
542 Value *IsNeg = Builder.CreateIsNeg(Arg: X, Name: "isneg");
543 return createSelectInstWithUnknownProfile(C: IsNeg, S1: Y,
544 S2: ConstantInt::getNullValue(Ty));
545 }
546
547 // (and X, 1) * Y --> (trunc X) ? Y : 0
548 if (match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_One())), R: m_Value(V&: Y)))) {
549 Value *Tr = Builder.CreateTrunc(V: X, DestTy: CmpInst::makeCmpResultType(opnd_type: Ty));
550 return createSelectInstWithUnknownProfile(C: Tr, S1: Y,
551 S2: ConstantInt::getNullValue(Ty));
552 }
553
554 // ((ashr X, 31) | 1) * X --> abs(X)
555 // X * ((ashr X, 31) | 1) --> abs(X)
556 if (match(V: &I, P: m_c_BinOp(L: m_Or(L: m_AShr(L: m_Value(V&: X),
557 R: m_SpecificIntAllowPoison(V: BitWidth - 1)),
558 R: m_One()),
559 R: m_Deferred(V: X)))) {
560 Value *Abs = Builder.CreateBinaryIntrinsic(
561 ID: Intrinsic::abs, LHS: X, RHS: ConstantInt::getBool(Context&: I.getContext(), V: HasNSW));
562 Abs->takeName(V: &I);
563 return replaceInstUsesWith(I, V: Abs);
564 }
565
566 if (Instruction *Ext = narrowMathIfNoOverflow(I))
567 return Ext;
568
569 if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
570 return Res;
571
572 // (mul Op0 Op1):
573 // if Log2(Op0) folds away ->
574 // (shl Op1, Log2(Op0))
575 // if Log2(Op1) folds away ->
576 // (shl Op0, Log2(Op1))
577 if (Value *Res = tryGetLog2(Op: Op0, /*AssumeNonZero=*/false)) {
578 BinaryOperator *Shl = BinaryOperator::CreateShl(V1: Op1, V2: Res);
579 // We can only propegate nuw flag.
580 Shl->setHasNoUnsignedWrap(HasNUW);
581 return Shl;
582 }
583 if (Value *Res = tryGetLog2(Op: Op1, /*AssumeNonZero=*/false)) {
584 BinaryOperator *Shl = BinaryOperator::CreateShl(V1: Op0, V2: Res);
585 // We can only propegate nuw flag.
586 Shl->setHasNoUnsignedWrap(HasNUW);
587 return Shl;
588 }
589
590 bool Changed = false;
591 if (!HasNSW && willNotOverflowSignedMul(LHS: Op0, RHS: Op1, CxtI: I)) {
592 Changed = true;
593 I.setHasNoSignedWrap(true);
594 }
595
596 if (!HasNUW && willNotOverflowUnsignedMul(LHS: Op0, RHS: Op1, CxtI: I, IsNSW: I.hasNoSignedWrap())) {
597 Changed = true;
598 I.setHasNoUnsignedWrap(true);
599 }
600
601 return Changed ? &I : nullptr;
602}
603
604Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
605 BinaryOperator::BinaryOps Opcode = I.getOpcode();
606 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
607 "Expected fmul or fdiv");
608
609 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
610 Value *X, *Y;
611
612 // -X * -Y --> X * Y
613 // -X / -Y --> X / Y
614 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
615 return BinaryOperator::CreateWithCopiedFlags(Opc: Opcode, V1: X, V2: Y, CopyO: &I);
616
617 // fabs(X) * fabs(X) -> X * X
618 // fabs(X) / fabs(X) -> X / X
619 if (Op0 == Op1 && match(V: Op0, P: m_FAbs(Op0: m_Value(V&: X))))
620 return BinaryOperator::CreateWithCopiedFlags(Opc: Opcode, V1: X, V2: X, CopyO: &I);
621
622 // fabs(X) * fabs(Y) --> fabs(X * Y)
623 // fabs(X) / fabs(Y) --> fabs(X / Y)
624 if (match(V: Op0, P: m_FAbs(Op0: m_Value(V&: X))) && match(V: Op1, P: m_FAbs(Op0: m_Value(V&: Y))) &&
625 (Op0->hasOneUse() || Op1->hasOneUse())) {
626 Value *XY = Builder.CreateBinOpFMF(Opc: Opcode, LHS: X, RHS: Y, FMFSource: &I);
627 Value *Fabs =
628 Builder.CreateUnaryIntrinsic(ID: Intrinsic::fabs, V: XY, FMFSource: &I, Name: I.getName());
629 return replaceInstUsesWith(I, V: Fabs);
630 }
631
632 return nullptr;
633}
634
635Instruction *InstCombinerImpl::foldPowiReassoc(BinaryOperator &I) {
636 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
637 Value *Y, Value *Z) {
638 InstCombiner::BuilderTy &Builder = IC.Builder;
639 Value *YZ = Builder.CreateAdd(LHS: Y, RHS: Z);
640 Instruction *NewPow = Builder.CreateIntrinsic(
641 ID: Intrinsic::powi, Types: {X->getType(), YZ->getType()}, Args: {X, YZ}, FMFSource: &I);
642
643 return NewPow;
644 };
645
646 Value *X, *Y, *Z;
647 unsigned Opcode = I.getOpcode();
648 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
649 "Unexpected opcode");
650
651 // powi(X, Y) * X --> powi(X, Y+1)
652 // X * powi(X, Y) --> powi(X, Y+1)
653 if (match(V: &I, P: m_c_FMul(L: m_OneUse(SubPattern: m_AllowReassoc(SubPattern: m_Intrinsic<Intrinsic::powi>(
654 Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))),
655 R: m_Deferred(V: X)))) {
656 Constant *One = ConstantInt::get(Ty: Y->getType(), V: 1);
657 if (willNotOverflowSignedAdd(LHS: Y, RHS: One, CxtI: I)) {
658 Instruction *NewPow = createPowiExpr(I, *this, X, Y, One);
659 return replaceInstUsesWith(I, V: NewPow);
660 }
661 }
662
663 // powi(x, y) * powi(x, z) -> powi(x, y + z)
664 Value *Op0 = I.getOperand(i_nocapture: 0);
665 Value *Op1 = I.getOperand(i_nocapture: 1);
666 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
667 match(V: Op0, P: m_AllowReassoc(
668 SubPattern: m_Intrinsic<Intrinsic::powi>(Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) &&
669 match(V: Op1, P: m_AllowReassoc(SubPattern: m_Intrinsic<Intrinsic::powi>(Op0: m_Specific(V: X),
670 Op1: m_Value(V&: Z)))) &&
671 Y->getType() == Z->getType()) {
672 Instruction *NewPow = createPowiExpr(I, *this, X, Y, Z);
673 return replaceInstUsesWith(I, V: NewPow);
674 }
675
676 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
677 // powi(X, Y) / X --> powi(X, Y-1)
678 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
679 // nnan are required.
680 // TODO: Multi-use may be also better off creating Powi(x,y-1)
681 if (match(V: Op0, P: m_OneUse(SubPattern: m_AllowReassoc(SubPattern: m_Intrinsic<Intrinsic::powi>(
682 Op0: m_Specific(V: Op1), Op1: m_Value(V&: Y))))) &&
683 willNotOverflowSignedSub(LHS: Y, RHS: ConstantInt::get(Ty: Y->getType(), V: 1), CxtI: I)) {
684 Constant *NegOne = ConstantInt::getAllOnesValue(Ty: Y->getType());
685 Instruction *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
686 return replaceInstUsesWith(I, V: NewPow);
687 }
688
689 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
690 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
691 // nnan are required.
692 // TODO: Multi-use may be also better off creating Powi(x,y-1)
693 if (match(V: Op0, P: m_OneUse(SubPattern: m_AllowReassoc(SubPattern: m_Intrinsic<Intrinsic::powi>(
694 Op0: m_Value(V&: X), Op1: m_Value(V&: Y))))) &&
695 match(V: Op1, P: m_AllowReassoc(SubPattern: m_c_FMul(L: m_Specific(V: X), R: m_Value(V&: Z)))) &&
696 willNotOverflowSignedSub(LHS: Y, RHS: ConstantInt::get(Ty: Y->getType(), V: 1), CxtI: I)) {
697 Constant *NegOne = ConstantInt::getAllOnesValue(Ty: Y->getType());
698 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
699 return BinaryOperator::CreateFDivFMF(V1: NewPow, V2: Z, FMFSource: &I);
700 }
701 }
702
703 return nullptr;
704}
705
706// If we have the following pattern,
707// X = 1.0/sqrt(a)
708// R1 = X * X
709// R2 = a/sqrt(a)
710// then this method collects all the instructions that match R1 and R2.
711static bool getFSqrtDivOptPattern(Instruction *Div,
712 SmallPtrSetImpl<Instruction *> &R1,
713 SmallPtrSetImpl<Instruction *> &R2) {
714 Value *A;
715 if (match(V: Div, P: m_FDiv(L: m_FPOne(), R: m_Sqrt(Op0: m_Value(V&: A)))) ||
716 match(V: Div, P: m_FDiv(L: m_SpecificFP(V: -1.0), R: m_Sqrt(Op0: m_Value(V&: A))))) {
717 for (User *U : Div->users()) {
718 Instruction *I = cast<Instruction>(Val: U);
719 if (match(V: I, P: m_FMul(L: m_Specific(V: Div), R: m_Specific(V: Div))))
720 R1.insert(Ptr: I);
721 }
722
723 CallInst *CI = cast<CallInst>(Val: Div->getOperand(i: 1));
724 for (User *U : CI->users()) {
725 Instruction *I = cast<Instruction>(Val: U);
726 if (match(V: I, P: m_FDiv(L: m_Specific(V: A), R: m_Sqrt(Op0: m_Specific(V: A)))))
727 R2.insert(Ptr: I);
728 }
729 }
730 return !R1.empty() && !R2.empty();
731}
732
733// Check legality for transforming
734// x = 1.0/sqrt(a)
735// r1 = x * x;
736// r2 = a/sqrt(a);
737//
738// TO
739//
740// r1 = 1/a
741// r2 = sqrt(a)
742// x = r1 * r2
743// This transform works only when 'a' is known positive.
744static bool isFSqrtDivToFMulLegal(Instruction *X,
745 SmallPtrSetImpl<Instruction *> &R1,
746 SmallPtrSetImpl<Instruction *> &R2) {
747 // Check if the required pattern for the transformation exists.
748 if (!getFSqrtDivOptPattern(Div: X, R1, R2))
749 return false;
750
751 BasicBlock *BBx = X->getParent();
752 BasicBlock *BBr1 = (*R1.begin())->getParent();
753 BasicBlock *BBr2 = (*R2.begin())->getParent();
754
755 CallInst *FSqrt = cast<CallInst>(Val: X->getOperand(i: 1));
756 if (!FSqrt->hasAllowReassoc() || !FSqrt->hasNoNaNs() ||
757 !FSqrt->hasNoSignedZeros() || !FSqrt->hasNoInfs())
758 return false;
759
760 // We change x = 1/sqrt(a) to x = sqrt(a) * 1/a . This change isn't allowed
761 // by recip fp as it is strictly meant to transform ops of type a/b to
762 // a * 1/b. So, this can be considered as algebraic rewrite and reassoc flag
763 // has been used(rather abused)in the past for algebraic rewrites.
764 if (!X->hasAllowReassoc() || !X->hasAllowReciprocal() || !X->hasNoInfs())
765 return false;
766
767 // Check the constraints on X, R1 and R2 combined.
768 // fdiv instruction and one of the multiplications must reside in the same
769 // block. If not, the optimized code may execute more ops than before and
770 // this may hamper the performance.
771 if (BBx != BBr1 && BBx != BBr2)
772 return false;
773
774 // Check the constraints on instructions in R1.
775 if (any_of(Range&: R1, P: [BBr1](Instruction *I) {
776 // When you have multiple instructions residing in R1 and R2
777 // respectively, it's difficult to generate combinations of (R1,R2) and
778 // then check if we have the required pattern. So, for now, just be
779 // conservative.
780 return (I->getParent() != BBr1 || !I->hasAllowReassoc());
781 }))
782 return false;
783
784 // Check the constraints on instructions in R2.
785 return all_of(Range&: R2, P: [BBr2](Instruction *I) {
786 // When you have multiple instructions residing in R1 and R2
787 // respectively, it's difficult to generate combination of (R1,R2) and
788 // then check if we have the required pattern. So, for now, just be
789 // conservative.
790 return (I->getParent() == BBr2 && I->hasAllowReassoc());
791 });
792}
793
794Instruction *InstCombinerImpl::foldFMulReassoc(BinaryOperator &I) {
795 Value *Op0 = I.getOperand(i_nocapture: 0);
796 Value *Op1 = I.getOperand(i_nocapture: 1);
797 Value *X, *Y;
798 Constant *C;
799 BinaryOperator *Op0BinOp;
800
801 // Reassociate constant RHS with another constant to form constant
802 // expression.
803 if (match(V: Op1, P: m_Constant(C)) && C->isFiniteNonZeroFP() &&
804 match(V: Op0, P: m_AllowReassoc(SubPattern: m_BinOp(I&: Op0BinOp)))) {
805 // Everything in this scope folds I with Op0, intersecting their FMF.
806 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
807 Constant *C1;
808 if (match(V: Op0, P: m_OneUse(SubPattern: m_FDiv(L: m_Constant(C&: C1), R: m_Value(V&: X))))) {
809 // (C1 / X) * C --> (C * C1) / X
810 Constant *CC1 =
811 ConstantFoldBinaryOpOperands(Opcode: Instruction::FMul, LHS: C, RHS: C1, DL);
812 if (CC1 && CC1->isNormalFP())
813 return BinaryOperator::CreateFDivFMF(V1: CC1, V2: X, FMF);
814 }
815 if (match(V: Op0, P: m_FDiv(L: m_Value(V&: X), R: m_Constant(C&: C1)))) {
816 // FIXME: This seems like it should also be checking for arcp
817 // (X / C1) * C --> X * (C / C1)
818 Constant *CDivC1 =
819 ConstantFoldBinaryOpOperands(Opcode: Instruction::FDiv, LHS: C, RHS: C1, DL);
820 if (CDivC1 && CDivC1->isNormalFP())
821 return BinaryOperator::CreateFMulFMF(V1: X, V2: CDivC1, FMF);
822
823 // If the constant was a denormal, try reassociating differently.
824 // (X / C1) * C --> X / (C1 / C)
825 Constant *C1DivC =
826 ConstantFoldBinaryOpOperands(Opcode: Instruction::FDiv, LHS: C1, RHS: C, DL);
827 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
828 return BinaryOperator::CreateFDivFMF(V1: X, V2: C1DivC, FMF);
829 }
830
831 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
832 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
833 // further folds and (X * C) + C2 is 'fma'.
834 if (match(V: Op0, P: m_OneUse(SubPattern: m_FAdd(L: m_Value(V&: X), R: m_Constant(C&: C1))))) {
835 // (X + C1) * C --> (X * C) + (C * C1)
836 if (Constant *CC1 =
837 ConstantFoldBinaryOpOperands(Opcode: Instruction::FMul, LHS: C, RHS: C1, DL)) {
838 Value *XC = Builder.CreateFMulFMF(L: X, R: C, FMFSource: FMF);
839 return BinaryOperator::CreateFAddFMF(V1: XC, V2: CC1, FMF);
840 }
841 }
842 if (match(V: Op0, P: m_OneUse(SubPattern: m_FSub(L: m_Constant(C&: C1), R: m_Value(V&: X))))) {
843 // (C1 - X) * C --> (C * C1) - (X * C)
844 if (Constant *CC1 =
845 ConstantFoldBinaryOpOperands(Opcode: Instruction::FMul, LHS: C, RHS: C1, DL)) {
846 Value *XC = Builder.CreateFMulFMF(L: X, R: C, FMFSource: FMF);
847 return BinaryOperator::CreateFSubFMF(V1: CC1, V2: XC, FMF);
848 }
849 }
850 }
851
852 Value *Z;
853 if (match(V: &I,
854 P: m_c_FMul(L: m_AllowReassoc(SubPattern: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Y)))),
855 R: m_Value(V&: Z)))) {
856 BinaryOperator *DivOp = cast<BinaryOperator>(Val: ((Z == Op0) ? Op1 : Op0));
857 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
858 if (FMF.allowReassoc()) {
859 // Sink division: (X / Y) * Z --> (X * Z) / Y
860 auto *NewFMul = Builder.CreateFMulFMF(L: X, R: Z, FMFSource: FMF);
861 return BinaryOperator::CreateFDivFMF(V1: NewFMul, V2: Y, FMF);
862 }
863 }
864
865 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
866 // nnan disallows the possibility of returning a number if both operands are
867 // negative (in that case, we should return NaN).
868 if (I.hasNoNaNs() && match(V: Op0, P: m_OneUse(SubPattern: m_Sqrt(Op0: m_Value(V&: X)))) &&
869 match(V: Op1, P: m_OneUse(SubPattern: m_Sqrt(Op0: m_Value(V&: Y))))) {
870 Value *XY = Builder.CreateFMulFMF(L: X, R: Y, FMFSource: &I);
871 Value *Sqrt = Builder.CreateUnaryIntrinsic(ID: Intrinsic::sqrt, V: XY, FMFSource: &I);
872 return replaceInstUsesWith(I, V: Sqrt);
873 }
874
875 // The following transforms are done irrespective of the number of uses
876 // for the expression "1.0/sqrt(X)".
877 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
878 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
879 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
880 // has the necessary (reassoc) fast-math-flags.
881 if (I.hasNoSignedZeros() &&
882 match(V: Op0, P: (m_FDiv(L: m_SpecificFP(V: 1.0), R: m_Value(V&: Y)))) &&
883 match(V: Y, P: m_Sqrt(Op0: m_Value(V&: X))) && Op1 == X)
884 return BinaryOperator::CreateFDivFMF(V1: X, V2: Y, FMFSource: &I);
885 if (I.hasNoSignedZeros() &&
886 match(V: Op1, P: (m_FDiv(L: m_SpecificFP(V: 1.0), R: m_Value(V&: Y)))) &&
887 match(V: Y, P: m_Sqrt(Op0: m_Value(V&: X))) && Op0 == X)
888 return BinaryOperator::CreateFDivFMF(V1: X, V2: Y, FMFSource: &I);
889
890 // Like the similar transform in instsimplify, this requires 'nsz' because
891 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
892 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(N: 2)) {
893 // Peek through fdiv to find squaring of square root:
894 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
895 if (match(V: Op0, P: m_FDiv(L: m_Value(V&: X), R: m_Sqrt(Op0: m_Value(V&: Y))))) {
896 Value *XX = Builder.CreateFMulFMF(L: X, R: X, FMFSource: &I);
897 return BinaryOperator::CreateFDivFMF(V1: XX, V2: Y, FMFSource: &I);
898 }
899 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
900 if (match(V: Op0, P: m_FDiv(L: m_Sqrt(Op0: m_Value(V&: Y)), R: m_Value(V&: X)))) {
901 Value *XX = Builder.CreateFMulFMF(L: X, R: X, FMFSource: &I);
902 return BinaryOperator::CreateFDivFMF(V1: Y, V2: XX, FMFSource: &I);
903 }
904 }
905
906 // pow(X, Y) * X --> pow(X, Y+1)
907 // X * pow(X, Y) --> pow(X, Y+1)
908 if (match(V: &I, P: m_c_FMul(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::pow>(Op0: m_Value(V&: X),
909 Op1: m_Value(V&: Y))),
910 R: m_Deferred(V: X)))) {
911 Value *Y1 = Builder.CreateFAddFMF(L: Y, R: ConstantFP::get(Ty: I.getType(), V: 1.0), FMFSource: &I);
912 Value *Pow = Builder.CreateBinaryIntrinsic(ID: Intrinsic::pow, LHS: X, RHS: Y1, FMFSource: &I);
913 return replaceInstUsesWith(I, V: Pow);
914 }
915
916 if (Instruction *FoldedPowi = foldPowiReassoc(I))
917 return FoldedPowi;
918
919 if (I.isOnlyUserOfAnyOperand()) {
920 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
921 if (match(V: Op0, P: m_Intrinsic<Intrinsic::pow>(Op0: m_Value(V&: X), Op1: m_Value(V&: Y))) &&
922 match(V: Op1, P: m_Intrinsic<Intrinsic::pow>(Op0: m_Specific(V: X), Op1: m_Value(V&: Z)))) {
923 auto *YZ = Builder.CreateFAddFMF(L: Y, R: Z, FMFSource: &I);
924 auto *NewPow = Builder.CreateBinaryIntrinsic(ID: Intrinsic::pow, LHS: X, RHS: YZ, FMFSource: &I);
925 return replaceInstUsesWith(I, V: NewPow);
926 }
927 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
928 if (match(V: Op0, P: m_Intrinsic<Intrinsic::pow>(Op0: m_Value(V&: X), Op1: m_Value(V&: Y))) &&
929 match(V: Op1, P: m_Intrinsic<Intrinsic::pow>(Op0: m_Value(V&: Z), Op1: m_Specific(V: Y)))) {
930 auto *XZ = Builder.CreateFMulFMF(L: X, R: Z, FMFSource: &I);
931 auto *NewPow = Builder.CreateBinaryIntrinsic(ID: Intrinsic::pow, LHS: XZ, RHS: Y, FMFSource: &I);
932 return replaceInstUsesWith(I, V: NewPow);
933 }
934
935 // exp(X) * exp(Y) -> exp(X + Y)
936 if (match(V: Op0, P: m_Intrinsic<Intrinsic::exp>(Op0: m_Value(V&: X))) &&
937 match(V: Op1, P: m_Intrinsic<Intrinsic::exp>(Op0: m_Value(V&: Y)))) {
938 Value *XY = Builder.CreateFAddFMF(L: X, R: Y, FMFSource: &I);
939 Value *Exp = Builder.CreateUnaryIntrinsic(ID: Intrinsic::exp, V: XY, FMFSource: &I);
940 return replaceInstUsesWith(I, V: Exp);
941 }
942
943 // exp2(X) * exp2(Y) -> exp2(X + Y)
944 if (match(V: Op0, P: m_Intrinsic<Intrinsic::exp2>(Op0: m_Value(V&: X))) &&
945 match(V: Op1, P: m_Intrinsic<Intrinsic::exp2>(Op0: m_Value(V&: Y)))) {
946 Value *XY = Builder.CreateFAddFMF(L: X, R: Y, FMFSource: &I);
947 Value *Exp2 = Builder.CreateUnaryIntrinsic(ID: Intrinsic::exp2, V: XY, FMFSource: &I);
948 return replaceInstUsesWith(I, V: Exp2);
949 }
950 }
951
952 // (X*Y) * X => (X*X) * Y where Y != X
953 // The purpose is two-fold:
954 // 1) to form a power expression (of X).
955 // 2) potentially shorten the critical path: After transformation, the
956 // latency of the instruction Y is amortized by the expression of X*X,
957 // and therefore Y is in a "less critical" position compared to what it
958 // was before the transformation.
959 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_FMul(L: m_Specific(V: Op1), R: m_Value(V&: Y)))) && Op1 != Y) {
960 Value *XX = Builder.CreateFMulFMF(L: Op1, R: Op1, FMFSource: &I);
961 return BinaryOperator::CreateFMulFMF(V1: XX, V2: Y, FMFSource: &I);
962 }
963 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_FMul(L: m_Specific(V: Op0), R: m_Value(V&: Y)))) && Op0 != Y) {
964 Value *XX = Builder.CreateFMulFMF(L: Op0, R: Op0, FMFSource: &I);
965 return BinaryOperator::CreateFMulFMF(V1: XX, V2: Y, FMFSource: &I);
966 }
967
968 return nullptr;
969}
970
971Instruction *InstCombinerImpl::visitFMul(BinaryOperator &I) {
972 if (Value *V = simplifyFMulInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
973 FMF: I.getFastMathFlags(),
974 Q: SQ.getWithInstruction(I: &I)))
975 return replaceInstUsesWith(I, V);
976
977 if (SimplifyAssociativeOrCommutative(I))
978 return &I;
979
980 if (Instruction *X = foldVectorBinop(Inst&: I))
981 return X;
982
983 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
984 return Phi;
985
986 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
987 return FoldedMul;
988
989 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
990 return replaceInstUsesWith(I, V: FoldedMul);
991
992 if (Instruction *R = foldFPSignBitOps(I))
993 return R;
994
995 if (Instruction *R = foldFBinOpOfIntCasts(I))
996 return R;
997
998 // X * -1.0 --> -X
999 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1000 if (match(V: Op1, P: m_SpecificFP(V: -1.0)))
1001 return UnaryOperator::CreateFNegFMF(Op: Op0, FMFSource: &I);
1002
1003 // -X * C --> X * -C
1004 Value *X, *Y;
1005 Constant *C;
1006 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_Constant(C)))
1007 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
1008 return BinaryOperator::CreateFMulFMF(V1: X, V2: NegC, FMFSource: &I);
1009
1010 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
1011 // (uitofp bool X) * Y --> X ? Y : 0
1012 // Y * (uitofp bool X) --> X ? Y : 0
1013 // Note INF * 0 is NaN.
1014 if (match(V: Op0, P: m_UIToFP(Op: m_Value(V&: X))) &&
1015 X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
1016 auto *SI = createSelectInstWithUnknownProfile(
1017 C: X, S1: Op1, S2: ConstantFP::get(Ty: I.getType(), V: 0.0));
1018 SI->copyFastMathFlags(FMF: I.getFastMathFlags());
1019 return SI;
1020 }
1021 if (match(V: Op1, P: m_UIToFP(Op: m_Value(V&: X))) &&
1022 X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
1023 auto *SI = createSelectInstWithUnknownProfile(
1024 C: X, S1: Op0, S2: ConstantFP::get(Ty: I.getType(), V: 0.0));
1025 SI->copyFastMathFlags(FMF: I.getFastMathFlags());
1026 return SI;
1027 }
1028 }
1029
1030 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
1031 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS: Op0, RHS: Op1))
1032 return replaceInstUsesWith(I, V);
1033
1034 if (I.hasAllowReassoc())
1035 if (Instruction *FoldedMul = foldFMulReassoc(I))
1036 return FoldedMul;
1037
1038 // log2(X * 0.5) * Y = log2(X) * Y - Y
1039 if (I.isFast()) {
1040 IntrinsicInst *Log2 = nullptr;
1041 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::log2>(
1042 Op0: m_OneUse(SubPattern: m_FMul(L: m_Value(V&: X), R: m_SpecificFP(V: 0.5))))))) {
1043 Log2 = cast<IntrinsicInst>(Val: Op0);
1044 Y = Op1;
1045 }
1046 if (match(V: Op1, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::log2>(
1047 Op0: m_OneUse(SubPattern: m_FMul(L: m_Value(V&: X), R: m_SpecificFP(V: 0.5))))))) {
1048 Log2 = cast<IntrinsicInst>(Val: Op1);
1049 Y = Op0;
1050 }
1051 if (Log2) {
1052 Value *Log2 = Builder.CreateUnaryIntrinsic(ID: Intrinsic::log2, V: X, FMFSource: &I);
1053 Value *LogXTimesY = Builder.CreateFMulFMF(L: Log2, R: Y, FMFSource: &I);
1054 return BinaryOperator::CreateFSubFMF(V1: LogXTimesY, V2: Y, FMFSource: &I);
1055 }
1056 }
1057
1058 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
1059 // Given a phi node with entry value as 0 and it used in fmul operation,
1060 // we can replace fmul with 0 safely and eleminate loop operation.
1061 PHINode *PN = nullptr;
1062 Value *Start = nullptr, *Step = nullptr;
1063 if (matchSimpleRecurrence(I: &I, P&: PN, Start, Step) && I.hasNoNaNs() &&
1064 I.hasNoSignedZeros() && match(V: Start, P: m_Zero()))
1065 return replaceInstUsesWith(I, V: Start);
1066
1067 // minimum(X, Y) * maximum(X, Y) => X * Y.
1068 if (match(V: &I,
1069 P: m_c_FMul(L: m_Intrinsic<Intrinsic::maximum>(Op0: m_Value(V&: X), Op1: m_Value(V&: Y)),
1070 R: m_c_Intrinsic<Intrinsic::minimum>(Op0: m_Deferred(V: X),
1071 Op1: m_Deferred(V: Y))))) {
1072 BinaryOperator *Result = BinaryOperator::CreateFMulFMF(V1: X, V2: Y, FMFSource: &I);
1073 // We cannot preserve ninf if nnan flag is not set.
1074 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
1075 // while in optimized version NaN * Inf and this is a poison with ninf flag.
1076 if (!Result->hasNoNaNs())
1077 Result->setHasNoInfs(false);
1078 return Result;
1079 }
1080
1081 // tan(X) * cos(X) -> sin(X)
1082 if (I.hasAllowContract() &&
1083 match(V: &I,
1084 P: m_c_FMul(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::tan>(Op0: m_Value(V&: X))),
1085 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::cos>(Op0: m_Deferred(V: X)))))) {
1086 auto *Sin = Builder.CreateUnaryIntrinsic(ID: Intrinsic::sin, V: X, FMFSource: &I);
1087 if (auto *Metadata = I.getMetadata(KindID: LLVMContext::MD_fpmath)) {
1088 Sin->setMetadata(KindID: LLVMContext::MD_fpmath, Node: Metadata);
1089 }
1090 return replaceInstUsesWith(I, V: Sin);
1091 }
1092
1093 // X * ldexp(1.0, Y) -> ldexp(X, Y)
1094 if (match(V: &I, P: m_AllowReassoc(SubPattern: m_c_FMul(
1095 L: m_Value(V&: X),
1096 R: m_AllowReassoc(SubPattern: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::ldexp>(
1097 Op0: m_FPOne(), Op1: m_Value(V&: Y))))))))
1098 return replaceInstUsesWith(
1099 I, V: Builder.CreateIntrinsic(ID: Intrinsic::ldexp,
1100 Types: {X->getType(), Y->getType()}, Args: {X, Y}, FMFSource: &I));
1101
1102 if (SimplifyDemandedInstructionFPClass(Inst&: I))
1103 return &I;
1104
1105 return nullptr;
1106}
1107
1108/// Fold a divide or remainder with a select instruction divisor when one of the
1109/// select operands is zero. In that case, we can use the other select operand
1110/// because div/rem by zero is undefined.
1111bool InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
1112 SelectInst *SI = dyn_cast<SelectInst>(Val: I.getOperand(i_nocapture: 1));
1113 if (!SI)
1114 return false;
1115
1116 int NonNullOperand;
1117 if (match(V: SI->getTrueValue(), P: m_Zero()))
1118 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1119 NonNullOperand = 2;
1120 else if (match(V: SI->getFalseValue(), P: m_Zero()))
1121 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1122 NonNullOperand = 1;
1123 else
1124 return false;
1125
1126 // Change the div/rem to use 'Y' instead of the select.
1127 replaceOperand(I, OpNum: 1, V: SI->getOperand(i_nocapture: NonNullOperand));
1128
1129 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1130 // problem. However, the select, or the condition of the select may have
1131 // multiple uses. Based on our knowledge that the operand must be non-zero,
1132 // propagate the known value for the select into other uses of it, and
1133 // propagate a known value of the condition into its other users.
1134
1135 // If the select and condition only have a single use, don't bother with this,
1136 // early exit.
1137 Value *SelectCond = SI->getCondition();
1138 if (SI->use_empty() && SelectCond->hasOneUse())
1139 return true;
1140
1141 // Scan the current block backward, looking for other uses of SI.
1142 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
1143 Type *CondTy = SelectCond->getType();
1144 while (BBI != BBFront) {
1145 --BBI;
1146 // If we found an instruction that we can't assume will return, so
1147 // information from below it cannot be propagated above it.
1148 if (!isGuaranteedToTransferExecutionToSuccessor(I: &*BBI))
1149 break;
1150
1151 // Replace uses of the select or its condition with the known values.
1152 for (Use &Op : BBI->operands()) {
1153 if (Op == SI) {
1154 replaceUse(U&: Op, NewValue: SI->getOperand(i_nocapture: NonNullOperand));
1155 Worklist.push(I: &*BBI);
1156 } else if (Op == SelectCond) {
1157 replaceUse(U&: Op, NewValue: NonNullOperand == 1 ? ConstantInt::getTrue(Ty: CondTy)
1158 : ConstantInt::getFalse(Ty: CondTy));
1159 Worklist.push(I: &*BBI);
1160 }
1161 }
1162
1163 // If we past the instruction, quit looking for it.
1164 if (&*BBI == SI)
1165 SI = nullptr;
1166 if (&*BBI == SelectCond)
1167 SelectCond = nullptr;
1168
1169 // If we ran out of things to eliminate, break out of the loop.
1170 if (!SelectCond && !SI)
1171 break;
1172
1173 }
1174 return true;
1175}
1176
1177/// True if the multiply can not be expressed in an int this size.
1178static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1179 bool IsSigned) {
1180 bool Overflow;
1181 Product = IsSigned ? C1.smul_ov(RHS: C2, Overflow) : C1.umul_ov(RHS: C2, Overflow);
1182 return Overflow;
1183}
1184
1185/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1186static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1187 bool IsSigned) {
1188 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1189
1190 // Bail if we will divide by zero.
1191 if (C2.isZero())
1192 return false;
1193
1194 // Bail if we would divide INT_MIN by -1.
1195 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1196 return false;
1197
1198 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1199 if (IsSigned)
1200 APInt::sdivrem(LHS: C1, RHS: C2, Quotient, Remainder);
1201 else
1202 APInt::udivrem(LHS: C1, RHS: C2, Quotient, Remainder);
1203
1204 return Remainder.isMinValue();
1205}
1206
1207static Value *foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder) {
1208 assert((I.getOpcode() == Instruction::SDiv ||
1209 I.getOpcode() == Instruction::UDiv) &&
1210 "Expected integer divide");
1211
1212 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1213 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1214 Type *Ty = I.getType();
1215
1216 Value *X, *Y, *Z;
1217
1218 // With appropriate no-wrap constraints, remove a common factor in the
1219 // dividend and divisor that is disguised as a left-shifted value.
1220 if (match(V: Op1, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
1221 match(V: Op0, P: m_c_Mul(L: m_Specific(V: X), R: m_Value(V&: Y)))) {
1222 // Both operands must have the matching no-wrap for this kind of division.
1223 auto *Mul = cast<OverflowingBinaryOperator>(Val: Op0);
1224 auto *Shl = cast<OverflowingBinaryOperator>(Val: Op1);
1225 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1226 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1227
1228 // (X * Y) u/ (X << Z) --> Y u>> Z
1229 if (!IsSigned && HasNUW)
1230 return Builder.CreateLShr(LHS: Y, RHS: Z, Name: "", isExact: I.isExact());
1231
1232 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1233 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1234 Value *Shl = Builder.CreateShl(LHS: ConstantInt::get(Ty, V: 1), RHS: Z);
1235 return Builder.CreateSDiv(LHS: Y, RHS: Shl, Name: "", isExact: I.isExact());
1236 }
1237 }
1238
1239 // With appropriate no-wrap constraints, remove a common factor in the
1240 // dividend and divisor that is disguised as a left-shift amount.
1241 if (match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
1242 match(V: Op1, P: m_Shl(L: m_Value(V&: Y), R: m_Specific(V: Z)))) {
1243 auto *Shl0 = cast<OverflowingBinaryOperator>(Val: Op0);
1244 auto *Shl1 = cast<OverflowingBinaryOperator>(Val: Op1);
1245
1246 // For unsigned div, we need 'nuw' on both shifts or
1247 // 'nsw' on both shifts + 'nuw' on the dividend.
1248 // (X << Z) / (Y << Z) --> X / Y
1249 if (!IsSigned &&
1250 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1251 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1252 Shl1->hasNoSignedWrap())))
1253 return Builder.CreateUDiv(LHS: X, RHS: Y, Name: "", isExact: I.isExact());
1254
1255 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1256 // (X << Z) / (Y << Z) --> X / Y
1257 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1258 Shl1->hasNoUnsignedWrap())
1259 return Builder.CreateSDiv(LHS: X, RHS: Y, Name: "", isExact: I.isExact());
1260 }
1261
1262 // If X << Y and X << Z does not overflow, then:
1263 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1264 if (match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1265 match(V: Op1, P: m_Shl(L: m_Specific(V: X), R: m_Value(V&: Z)))) {
1266 auto *Shl0 = cast<OverflowingBinaryOperator>(Val: Op0);
1267 auto *Shl1 = cast<OverflowingBinaryOperator>(Val: Op1);
1268
1269 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1270 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1271 Constant *One = ConstantInt::get(Ty: X->getType(), V: 1);
1272 // Only preserve the nsw flag if dividend has nsw
1273 // or divisor has nsw and operator is sdiv.
1274 Value *Dividend = Builder.CreateShl(
1275 LHS: One, RHS: Y, Name: "shl.dividend",
1276 /*HasNUW=*/true,
1277 /*HasNSW=*/
1278 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1279 : Shl0->hasNoSignedWrap());
1280 return Builder.CreateLShr(LHS: Dividend, RHS: Z, Name: "", isExact: I.isExact());
1281 }
1282 }
1283
1284 return nullptr;
1285}
1286
1287/// Common integer divide/remainder transforms
1288Instruction *InstCombinerImpl::commonIDivRemTransforms(BinaryOperator &I) {
1289 assert(I.isIntDivRem() && "Unexpected instruction");
1290 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1291
1292 // If any element of a constant divisor fixed width vector is zero or undef
1293 // the behavior is undefined and we can fold the whole op to poison.
1294 auto *Op1C = dyn_cast<Constant>(Val: Op1);
1295 Type *Ty = I.getType();
1296 auto *VTy = dyn_cast<FixedVectorType>(Val: Ty);
1297 if (Op1C && VTy) {
1298 unsigned NumElts = VTy->getNumElements();
1299 for (unsigned i = 0; i != NumElts; ++i) {
1300 Constant *Elt = Op1C->getAggregateElement(Elt: i);
1301 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Val: Elt)))
1302 return replaceInstUsesWith(I, V: PoisonValue::get(T: Ty));
1303 }
1304 }
1305
1306 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
1307 return Phi;
1308
1309 // The RHS is known non-zero.
1310 if (Value *V = simplifyValueKnownNonZero(V: I.getOperand(i_nocapture: 1), IC&: *this, CxtI&: I))
1311 return replaceOperand(I, OpNum: 1, V);
1312
1313 // Handle cases involving: div/rem X, (select Cond, Y, Z)
1314 if (simplifyDivRemOfSelectWithZeroOp(I))
1315 return &I;
1316
1317 // If the divisor is a select-of-constants, try to constant fold all div ops:
1318 // C div/rem (select Cond, TrueC, FalseC) --> select Cond, (C div/rem TrueC),
1319 // (C div/rem FalseC)
1320 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1321 if (match(V: Op0, P: m_ImmConstant()) &&
1322 match(V: Op1, P: m_Select(C: m_Value(), L: m_ImmConstant(), R: m_ImmConstant()))) {
1323 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: Op1),
1324 /*FoldWithMultiUse*/ true))
1325 return R;
1326 }
1327
1328 return nullptr;
1329}
1330
1331/// This function implements the transforms common to both integer division
1332/// instructions (udiv and sdiv). It is called by the visitors to those integer
1333/// division instructions.
1334/// Common integer divide transforms
1335Instruction *InstCombinerImpl::commonIDivTransforms(BinaryOperator &I) {
1336 if (Instruction *Res = commonIDivRemTransforms(I))
1337 return Res;
1338
1339 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1340 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1341 Type *Ty = I.getType();
1342
1343 const APInt *C2;
1344 if (match(V: Op1, P: m_APInt(Res&: C2))) {
1345 Value *X;
1346 const APInt *C1;
1347
1348 // (X / C1) / C2 -> X / (C1*C2)
1349 if ((IsSigned && match(V: Op0, P: m_SDiv(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) ||
1350 (!IsSigned && match(V: Op0, P: m_UDiv(L: m_Value(V&: X), R: m_APInt(Res&: C1))))) {
1351 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1352 if (!multiplyOverflows(C1: *C1, C2: *C2, Product, IsSigned))
1353 return BinaryOperator::Create(Op: I.getOpcode(), S1: X,
1354 S2: ConstantInt::get(Ty, V: Product));
1355 }
1356
1357 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1358 if ((IsSigned && match(V: Op0, P: m_NSWMul(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) ||
1359 (!IsSigned && match(V: Op0, P: m_NUWMul(L: m_Value(V&: X), R: m_APInt(Res&: C1))))) {
1360
1361 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1362 if (isMultiple(C1: *C2, C2: *C1, Quotient, IsSigned)) {
1363 auto *NewDiv = BinaryOperator::Create(Op: I.getOpcode(), S1: X,
1364 S2: ConstantInt::get(Ty, V: Quotient));
1365 NewDiv->setIsExact(I.isExact());
1366 return NewDiv;
1367 }
1368
1369 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1370 if (isMultiple(C1: *C1, C2: *C2, Quotient, IsSigned)) {
1371 auto *Mul = BinaryOperator::Create(Op: Instruction::Mul, S1: X,
1372 S2: ConstantInt::get(Ty, V: Quotient));
1373 auto *OBO = cast<OverflowingBinaryOperator>(Val: Op0);
1374 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1375 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1376 return Mul;
1377 }
1378 }
1379
1380 if ((IsSigned && match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_APInt(Res&: C1))) &&
1381 C1->ult(RHS: C1->getBitWidth() - 1)) ||
1382 (!IsSigned && match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_APInt(Res&: C1))) &&
1383 C1->ult(RHS: C1->getBitWidth()))) {
1384 APInt C1Shifted = APInt::getOneBitSet(
1385 numBits: C1->getBitWidth(), BitNo: static_cast<unsigned>(C1->getZExtValue()));
1386
1387 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1388 if (isMultiple(C1: *C2, C2: C1Shifted, Quotient, IsSigned)) {
1389 auto *BO = BinaryOperator::Create(Op: I.getOpcode(), S1: X,
1390 S2: ConstantInt::get(Ty, V: Quotient));
1391 BO->setIsExact(I.isExact());
1392 return BO;
1393 }
1394
1395 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1396 if (isMultiple(C1: C1Shifted, C2: *C2, Quotient, IsSigned)) {
1397 auto *Mul = BinaryOperator::Create(Op: Instruction::Mul, S1: X,
1398 S2: ConstantInt::get(Ty, V: Quotient));
1399 auto *OBO = cast<OverflowingBinaryOperator>(Val: Op0);
1400 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1401 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1402 return Mul;
1403 }
1404 }
1405
1406 // Distribute div over add to eliminate a matching div/mul pair:
1407 // ((X * C2) + C1) / C2 --> X + C1/C2
1408 // We need a multiple of the divisor for a signed add constant, but
1409 // unsigned is fine with any constant pair.
1410 if (IsSigned &&
1411 match(V: Op0, P: m_NSWAddLike(L: m_NSWMul(L: m_Value(V&: X), R: m_SpecificInt(V: *C2)),
1412 R: m_APInt(Res&: C1))) &&
1413 isMultiple(C1: *C1, C2: *C2, Quotient, IsSigned)) {
1414 return BinaryOperator::CreateNSWAdd(V1: X, V2: ConstantInt::get(Ty, V: Quotient));
1415 }
1416 if (!IsSigned &&
1417 match(V: Op0, P: m_NUWAddLike(L: m_NUWMul(L: m_Value(V&: X), R: m_SpecificInt(V: *C2)),
1418 R: m_APInt(Res&: C1)))) {
1419 return BinaryOperator::CreateNUWAdd(V1: X,
1420 V2: ConstantInt::get(Ty, V: C1->udiv(RHS: *C2)));
1421 }
1422
1423 if (!C2->isZero()) // avoid X udiv 0
1424 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1425 return FoldedDiv;
1426 }
1427
1428 if (match(V: Op0, P: m_One())) {
1429 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1430 if (IsSigned) {
1431 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1432 // (Op1 + 1) u< 3 ? Op1 : 0
1433 // Op1 must be frozen because we are increasing its number of uses.
1434 Value *F1 = Op1;
1435 if (!isGuaranteedNotToBeUndef(V: Op1))
1436 F1 = Builder.CreateFreeze(V: Op1, Name: Op1->getName() + ".fr");
1437 Value *Inc = Builder.CreateAdd(LHS: F1, RHS: Op0);
1438 Value *Cmp = Builder.CreateICmpULT(LHS: Inc, RHS: ConstantInt::get(Ty, V: 3));
1439 return createSelectInstWithUnknownProfile(C: Cmp, S1: F1,
1440 S2: ConstantInt::get(Ty, V: 0));
1441 } else {
1442 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1443 // result is one, otherwise it's zero.
1444 return new ZExtInst(Builder.CreateICmpEQ(LHS: Op1, RHS: Op0), Ty);
1445 }
1446 }
1447
1448 // See if we can fold away this div instruction.
1449 if (SimplifyDemandedInstructionBits(Inst&: I))
1450 return &I;
1451
1452 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1453 Value *X, *Z;
1454 if (match(V: Op0, P: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Z)))) // (X - Z) / Y; Y = Op1
1455 if ((IsSigned && match(V: Z, P: m_SRem(L: m_Specific(V: X), R: m_Specific(V: Op1)))) ||
1456 (!IsSigned && match(V: Z, P: m_URem(L: m_Specific(V: X), R: m_Specific(V: Op1)))))
1457 return BinaryOperator::Create(Op: I.getOpcode(), S1: X, S2: Op1);
1458
1459 // (X << Y) / X -> 1 << Y
1460 Value *Y;
1461 if (IsSigned && match(V: Op0, P: m_NSWShl(L: m_Specific(V: Op1), R: m_Value(V&: Y))))
1462 return BinaryOperator::CreateNSWShl(V1: ConstantInt::get(Ty, V: 1), V2: Y);
1463 if (!IsSigned && match(V: Op0, P: m_NUWShl(L: m_Specific(V: Op1), R: m_Value(V&: Y))))
1464 return BinaryOperator::CreateNUWShl(V1: ConstantInt::get(Ty, V: 1), V2: Y);
1465
1466 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1467 if (match(V: Op1, P: m_c_Mul(L: m_Specific(V: Op0), R: m_Value(V&: Y)))) {
1468 bool HasNSW = cast<OverflowingBinaryOperator>(Val: Op1)->hasNoSignedWrap();
1469 bool HasNUW = cast<OverflowingBinaryOperator>(Val: Op1)->hasNoUnsignedWrap();
1470 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1471 replaceOperand(I, OpNum: 0, V: ConstantInt::get(Ty, V: 1));
1472 replaceOperand(I, OpNum: 1, V: Y);
1473 return &I;
1474 }
1475 }
1476
1477 // (X << Z) / (X * Y) -> (1 << Z) / Y
1478 // TODO: Handle sdiv.
1479 if (!IsSigned && Op1->hasOneUse() &&
1480 match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
1481 match(V: Op1, P: m_c_Mul(L: m_Specific(V: X), R: m_Value(V&: Y))))
1482 if (cast<OverflowingBinaryOperator>(Val: Op1)->hasNoUnsignedWrap()) {
1483 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1484 V1: Builder.CreateShl(LHS: ConstantInt::get(Ty, V: 1), RHS: Z, Name: "", /*NUW*/ HasNUW: true), V2: Y);
1485 NewDiv->setIsExact(I.isExact());
1486 return NewDiv;
1487 }
1488
1489 if (Value *R = foldIDivShl(I, Builder))
1490 return replaceInstUsesWith(I, V: R);
1491
1492 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1493 // after peeking through another divide:
1494 // ((Op1 * X) / Y) / Op1 --> X / Y
1495 if (match(V: Op0, P: m_BinOp(Opcode: I.getOpcode(), L: m_c_Mul(L: m_Specific(V: Op1), R: m_Value(V&: X)),
1496 R: m_Value(V&: Y)))) {
1497 auto *InnerDiv = cast<PossiblyExactOperator>(Val: Op0);
1498 auto *Mul = cast<OverflowingBinaryOperator>(Val: InnerDiv->getOperand(i_nocapture: 0));
1499 Instruction *NewDiv = nullptr;
1500 if (!IsSigned && Mul->hasNoUnsignedWrap())
1501 NewDiv = BinaryOperator::CreateUDiv(V1: X, V2: Y);
1502 else if (IsSigned && Mul->hasNoSignedWrap())
1503 NewDiv = BinaryOperator::CreateSDiv(V1: X, V2: Y);
1504
1505 // Exact propagates only if both of the original divides are exact.
1506 if (NewDiv) {
1507 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1508 return NewDiv;
1509 }
1510 }
1511
1512 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1513 if (match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
1514 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Val: Op0)->hasNoSignedWrap();
1515 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Val: Op0)->hasNoUnsignedWrap();
1516
1517 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1518 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Val: Op1)->hasNoSignedWrap();
1519 auto OB1HasNUW =
1520 cast<OverflowingBinaryOperator>(Val: Op1)->hasNoUnsignedWrap();
1521 const APInt *C1, *C2;
1522 if (IsSigned && OB0HasNSW) {
1523 if (OB1HasNSW && match(V: B, P: m_APInt(Res&: C1)) && !C1->isAllOnes())
1524 return BinaryOperator::CreateSDiv(V1: A, V2: B);
1525 }
1526 if (!IsSigned && OB0HasNUW) {
1527 if (OB1HasNUW)
1528 return BinaryOperator::CreateUDiv(V1: A, V2: B);
1529 if (match(V: A, P: m_APInt(Res&: C1)) && match(V: B, P: m_APInt(Res&: C2)) && C2->ule(RHS: *C1))
1530 return BinaryOperator::CreateUDiv(V1: A, V2: B);
1531 }
1532 return nullptr;
1533 };
1534
1535 if (match(V: Op1, P: m_c_Mul(L: m_Specific(V: X), R: m_Value(V&: Z)))) {
1536 if (auto *Val = CreateDivOrNull(Y, Z))
1537 return Val;
1538 }
1539 if (match(V: Op1, P: m_c_Mul(L: m_Specific(V: Y), R: m_Value(V&: Z)))) {
1540 if (auto *Val = CreateDivOrNull(X, Z))
1541 return Val;
1542 }
1543 }
1544 return nullptr;
1545}
1546
1547Value *InstCombinerImpl::takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero,
1548 bool DoFold) {
1549 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1550 if (!DoFold)
1551 return reinterpret_cast<Value *>(-1);
1552 return Fn();
1553 };
1554
1555 // FIXME: assert that Op1 isn't/doesn't contain undef.
1556
1557 // log2(2^C) -> C
1558 if (match(V: Op, P: m_Power2()))
1559 return IfFold([&]() {
1560 Constant *C = ConstantExpr::getExactLogBase2(C: cast<Constant>(Val: Op));
1561 if (!C)
1562 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1563 return C;
1564 });
1565
1566 // The remaining tests are all recursive, so bail out if we hit the limit.
1567 if (Depth++ == MaxAnalysisRecursionDepth)
1568 return nullptr;
1569
1570 // log2(zext X) -> zext log2(X)
1571 // FIXME: Require one use?
1572 Value *X, *Y;
1573 if (match(V: Op, P: m_ZExt(Op: m_Value(V&: X))))
1574 if (Value *LogX = takeLog2(Op: X, Depth, AssumeNonZero, DoFold))
1575 return IfFold([&]() { return Builder.CreateZExt(V: LogX, DestTy: Op->getType()); });
1576
1577 // log2(trunc x) -> trunc log2(X)
1578 // FIXME: Require one use?
1579 if (match(V: Op, P: m_Trunc(Op: m_Value(V&: X)))) {
1580 auto *TI = cast<TruncInst>(Val: Op);
1581 if (AssumeNonZero || TI->hasNoUnsignedWrap())
1582 if (Value *LogX = takeLog2(Op: X, Depth, AssumeNonZero, DoFold))
1583 return IfFold([&]() {
1584 return Builder.CreateTrunc(V: LogX, DestTy: Op->getType(), Name: "",
1585 /*IsNUW=*/TI->hasNoUnsignedWrap());
1586 });
1587 }
1588
1589 // log2(X << Y) -> log2(X) + Y
1590 // FIXME: Require one use unless X is 1?
1591 if (match(V: Op, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
1592 auto *BO = cast<OverflowingBinaryOperator>(Val: Op);
1593 // nuw will be set if the `shl` is trivially non-zero.
1594 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1595 if (Value *LogX = takeLog2(Op: X, Depth, AssumeNonZero, DoFold))
1596 return IfFold([&]() { return Builder.CreateAdd(LHS: LogX, RHS: Y); });
1597 }
1598
1599 // log2(X >>u Y) -> log2(X) - Y
1600 // FIXME: Require one use?
1601 if (match(V: Op, P: m_LShr(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
1602 auto *PEO = cast<PossiblyExactOperator>(Val: Op);
1603 if (AssumeNonZero || PEO->isExact())
1604 if (Value *LogX = takeLog2(Op: X, Depth, AssumeNonZero, DoFold))
1605 return IfFold([&]() { return Builder.CreateSub(LHS: LogX, RHS: Y); });
1606 }
1607
1608 // log2(X & Y) -> either log2(X) or log2(Y)
1609 // This requires `AssumeNonZero` as `X & Y` may be zero when X != Y.
1610 if (AssumeNonZero && match(V: Op, P: m_And(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
1611 if (Value *LogX = takeLog2(Op: X, Depth, AssumeNonZero, DoFold))
1612 return IfFold([&]() { return LogX; });
1613 if (Value *LogY = takeLog2(Op: Y, Depth, AssumeNonZero, DoFold))
1614 return IfFold([&]() { return LogY; });
1615 }
1616
1617 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1618 // FIXME: Require one use?
1619 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op))
1620 if (Value *LogX = takeLog2(Op: SI->getOperand(i_nocapture: 1), Depth, AssumeNonZero, DoFold))
1621 if (Value *LogY =
1622 takeLog2(Op: SI->getOperand(i_nocapture: 2), Depth, AssumeNonZero, DoFold))
1623 return IfFold([&]() {
1624 return Builder.CreateSelect(C: SI->getOperand(i_nocapture: 0), True: LogX, False: LogY, Name: "",
1625 MDFrom: ProfcheckDisableMetadataFixes ? nullptr
1626 : SI);
1627 });
1628
1629 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1630 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1631 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op);
1632 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1633 // Use AssumeNonZero as false here. Otherwise we can hit case where
1634 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1635 if (Value *LogX = takeLog2(Op: MinMax->getLHS(), Depth,
1636 /*AssumeNonZero*/ false, DoFold))
1637 if (Value *LogY = takeLog2(Op: MinMax->getRHS(), Depth,
1638 /*AssumeNonZero*/ false, DoFold))
1639 return IfFold([&]() {
1640 return Builder.CreateBinaryIntrinsic(ID: MinMax->getIntrinsicID(), LHS: LogX,
1641 RHS: LogY);
1642 });
1643 }
1644
1645 return nullptr;
1646}
1647
1648/// If we have zero-extended operands of an unsigned div or rem, we may be able
1649/// to narrow the operation (sink the zext below the math).
1650static Instruction *narrowUDivURem(BinaryOperator &I,
1651 InstCombinerImpl &IC) {
1652 Instruction::BinaryOps Opcode = I.getOpcode();
1653 Value *N = I.getOperand(i_nocapture: 0);
1654 Value *D = I.getOperand(i_nocapture: 1);
1655 Type *Ty = I.getType();
1656 Value *X, *Y;
1657 if (match(V: N, P: m_ZExt(Op: m_Value(V&: X))) && match(V: D, P: m_ZExt(Op: m_Value(V&: Y))) &&
1658 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1659 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1660 // urem (zext X), (zext Y) --> zext (urem X, Y)
1661 Value *NarrowOp = IC.Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Y);
1662 return new ZExtInst(NarrowOp, Ty);
1663 }
1664
1665 Constant *C;
1666 auto &DL = IC.getDataLayout();
1667 if (isa<Instruction>(Val: N) && match(V: N, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) &&
1668 match(V: D, P: m_Constant(C))) {
1669 // If the constant is the same in the smaller type, use the narrow version.
1670 Constant *TruncC = getLosslessUnsignedTrunc(C, DestTy: X->getType(), DL);
1671 if (!TruncC)
1672 return nullptr;
1673
1674 // udiv (zext X), C --> zext (udiv X, C')
1675 // urem (zext X), C --> zext (urem X, C')
1676 return new ZExtInst(IC.Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: TruncC), Ty);
1677 }
1678 if (isa<Instruction>(Val: D) && match(V: D, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) &&
1679 match(V: N, P: m_Constant(C))) {
1680 // If the constant is the same in the smaller type, use the narrow version.
1681 Constant *TruncC = getLosslessUnsignedTrunc(C, DestTy: X->getType(), DL);
1682 if (!TruncC)
1683 return nullptr;
1684
1685 // udiv C, (zext X) --> zext (udiv C', X)
1686 // urem C, (zext X) --> zext (urem C', X)
1687 return new ZExtInst(IC.Builder.CreateBinOp(Opc: Opcode, LHS: TruncC, RHS: X), Ty);
1688 }
1689
1690 return nullptr;
1691}
1692
1693Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) {
1694 if (Value *V = simplifyUDivInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1), IsExact: I.isExact(),
1695 Q: SQ.getWithInstruction(I: &I)))
1696 return replaceInstUsesWith(I, V);
1697
1698 if (Instruction *X = foldVectorBinop(Inst&: I))
1699 return X;
1700
1701 // Handle the integer div common cases
1702 if (Instruction *Common = commonIDivTransforms(I))
1703 return Common;
1704
1705 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1706 Value *X;
1707 const APInt *C1, *C2;
1708 if (match(V: Op0, P: m_LShr(L: m_Value(V&: X), R: m_APInt(Res&: C1))) && match(V: Op1, P: m_APInt(Res&: C2))) {
1709 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1710 bool Overflow;
1711 APInt C2ShlC1 = C2->ushl_ov(Amt: *C1, Overflow);
1712 if (!Overflow) {
1713 bool IsExact = I.isExact() && match(V: Op0, P: m_Exact(SubPattern: m_Value()));
1714 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1715 V1: X, V2: ConstantInt::get(Ty: X->getType(), V: C2ShlC1));
1716 if (IsExact)
1717 BO->setIsExact();
1718 return BO;
1719 }
1720 }
1721
1722 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1723 // TODO: Could use isKnownNegative() to handle non-constant values.
1724 Type *Ty = I.getType();
1725 if (match(V: Op1, P: m_Negative())) {
1726 Value *Cmp = Builder.CreateICmpUGE(LHS: Op0, RHS: Op1);
1727 return CastInst::CreateZExtOrBitCast(S: Cmp, Ty);
1728 }
1729 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1730 if (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
1731 Value *Cmp = Builder.CreateICmpEQ(LHS: Op0, RHS: ConstantInt::getAllOnesValue(Ty));
1732 return CastInst::CreateZExtOrBitCast(S: Cmp, Ty);
1733 }
1734
1735 if (Instruction *NarrowDiv = narrowUDivURem(I, IC&: *this))
1736 return NarrowDiv;
1737
1738 Value *A, *B;
1739
1740 // Look through a right-shift to find the common factor:
1741 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1742 if (match(V: Op0, P: m_LShr(L: m_NUWMul(L: m_Specific(V: Op1), R: m_Value(V&: A)), R: m_Value(V&: B))) ||
1743 match(V: Op0, P: m_LShr(L: m_NUWMul(L: m_Value(V&: A), R: m_Specific(V: Op1)), R: m_Value(V&: B)))) {
1744 Instruction *Lshr = BinaryOperator::CreateLShr(V1: A, V2: B);
1745 if (I.isExact() && cast<PossiblyExactOperator>(Val: Op0)->isExact())
1746 Lshr->setIsExact();
1747 return Lshr;
1748 }
1749
1750 auto GetShiftableDenom = [&](Value *Denom) -> Value * {
1751 // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
1752 if (Value *Log2 = tryGetLog2(Op: Op1, /*AssumeNonZero=*/true))
1753 return Log2;
1754
1755 // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
1756 if (isKnownToBeAPowerOfTwo(V: Denom, /*OrZero=*/true, CxtI: &I))
1757 // This will increase instruction count but it's okay
1758 // since bitwise operations are substantially faster than
1759 // division.
1760 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: Denom,
1761 RHS: Builder.getTrue());
1762
1763 return nullptr;
1764 };
1765
1766 if (auto *Res = GetShiftableDenom(Op1))
1767 return replaceInstUsesWith(
1768 I, V: Builder.CreateLShr(LHS: Op0, RHS: Res, Name: I.getName(), isExact: I.isExact()));
1769
1770 return nullptr;
1771}
1772
1773Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
1774 if (Value *V = simplifySDivInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1), IsExact: I.isExact(),
1775 Q: SQ.getWithInstruction(I: &I)))
1776 return replaceInstUsesWith(I, V);
1777
1778 if (Instruction *X = foldVectorBinop(Inst&: I))
1779 return X;
1780
1781 // Handle the integer div common cases
1782 if (Instruction *Common = commonIDivTransforms(I))
1783 return Common;
1784
1785 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1786 Type *Ty = I.getType();
1787 Value *X;
1788 // sdiv Op0, -1 --> -Op0
1789 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1790 if (match(V: Op1, P: m_AllOnes()) ||
1791 (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)))
1792 return BinaryOperator::CreateNSWNeg(Op: Op0);
1793
1794 // X / INT_MIN --> X == INT_MIN
1795 if (match(V: Op1, P: m_SignMask()))
1796 return new ZExtInst(Builder.CreateICmpEQ(LHS: Op0, RHS: Op1), Ty);
1797
1798 if (I.isExact()) {
1799 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1800 if (match(V: Op1, P: m_Power2()) && match(V: Op1, P: m_NonNegative())) {
1801 Constant *C = ConstantExpr::getExactLogBase2(C: cast<Constant>(Val: Op1));
1802 return BinaryOperator::CreateExactAShr(V1: Op0, V2: C);
1803 }
1804
1805 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1806 Value *ShAmt;
1807 if (match(V: Op1, P: m_NSWShl(L: m_One(), R: m_Value(V&: ShAmt))))
1808 return BinaryOperator::CreateExactAShr(V1: Op0, V2: ShAmt);
1809
1810 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1811 if (match(V: Op1, P: m_NegatedPower2())) {
1812 Constant *NegPow2C = ConstantExpr::getNeg(C: cast<Constant>(Val: Op1));
1813 Constant *C = ConstantExpr::getExactLogBase2(C: NegPow2C);
1814 Value *Ashr = Builder.CreateAShr(LHS: Op0, RHS: C, Name: I.getName() + ".neg", isExact: true);
1815 return BinaryOperator::CreateNSWNeg(Op: Ashr);
1816 }
1817 }
1818
1819 const APInt *Op1C;
1820 if (match(V: Op1, P: m_APInt(Res&: Op1C))) {
1821 // If the dividend is sign-extended and the constant divisor is small enough
1822 // to fit in the source type, shrink the division to the narrower type:
1823 // (sext X) sdiv C --> sext (X sdiv C)
1824 Value *Op0Src;
1825 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: Op0Src)))) &&
1826 Op0Src->getType()->getScalarSizeInBits() >=
1827 Op1C->getSignificantBits()) {
1828
1829 // In the general case, we need to make sure that the dividend is not the
1830 // minimum signed value because dividing that by -1 is UB. But here, we
1831 // know that the -1 divisor case is already handled above.
1832
1833 Constant *NarrowDivisor =
1834 ConstantExpr::getTrunc(C: cast<Constant>(Val: Op1), Ty: Op0Src->getType());
1835 Value *NarrowOp = Builder.CreateSDiv(LHS: Op0Src, RHS: NarrowDivisor);
1836 return new SExtInst(NarrowOp, Ty);
1837 }
1838
1839 // -X / C --> X / -C (if the negation doesn't overflow).
1840 // TODO: This could be enhanced to handle arbitrary vector constants by
1841 // checking if all elements are not the min-signed-val.
1842 if (!Op1C->isMinSignedValue() && match(V: Op0, P: m_NSWNeg(V: m_Value(V&: X)))) {
1843 Constant *NegC = ConstantInt::get(Ty, V: -(*Op1C));
1844 Instruction *BO = BinaryOperator::CreateSDiv(V1: X, V2: NegC);
1845 BO->setIsExact(I.isExact());
1846 return BO;
1847 }
1848 }
1849
1850 // -X / Y --> -(X / Y)
1851 Value *Y;
1852 if (match(V: &I, P: m_SDiv(L: m_OneUse(SubPattern: m_NSWNeg(V: m_Value(V&: X))), R: m_Value(V&: Y))))
1853 return BinaryOperator::CreateNSWNeg(
1854 Op: Builder.CreateSDiv(LHS: X, RHS: Y, Name: I.getName(), isExact: I.isExact()));
1855
1856 // abs(X) / X --> X > -1 ? 1 : -1
1857 // X / abs(X) --> X > -1 ? 1 : -1
1858 if (match(V: &I, P: m_c_BinOp(
1859 L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X), Op1: m_One())),
1860 R: m_Deferred(V: X)))) {
1861 Value *Cond = Builder.CreateIsNotNeg(Arg: X);
1862 return createSelectInstWithUnknownProfile(C: Cond, S1: ConstantInt::get(Ty, V: 1),
1863 S2: ConstantInt::getAllOnesValue(Ty));
1864 }
1865
1866 KnownBits KnownDividend = computeKnownBits(V: Op0, CxtI: &I);
1867 if (!I.isExact() &&
1868 (match(V: Op1, P: m_Power2(V&: Op1C)) || match(V: Op1, P: m_NegatedPower2(V&: Op1C))) &&
1869 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1870 I.setIsExact();
1871 return &I;
1872 }
1873
1874 if (KnownDividend.isNonNegative()) {
1875 // If both operands are unsigned, turn this into a udiv.
1876 if (isKnownNonNegative(V: Op1, SQ: SQ.getWithInstruction(I: &I))) {
1877 auto *BO = BinaryOperator::CreateUDiv(V1: Op0, V2: Op1, Name: I.getName());
1878 BO->setIsExact(I.isExact());
1879 return BO;
1880 }
1881
1882 if (match(V: Op1, P: m_NegatedPower2())) {
1883 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1884 // -> -(X udiv (1 << C)) -> -(X u>> C)
1885 Constant *CNegLog2 = ConstantExpr::getExactLogBase2(
1886 C: ConstantExpr::getNeg(C: cast<Constant>(Val: Op1)));
1887 Value *Shr = Builder.CreateLShr(LHS: Op0, RHS: CNegLog2, Name: I.getName(), isExact: I.isExact());
1888 return BinaryOperator::CreateNeg(Op: Shr);
1889 }
1890
1891 if (isKnownToBeAPowerOfTwo(V: Op1, /*OrZero*/ true, CxtI: &I)) {
1892 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1893 // Safe because the only negative value (1 << Y) can take on is
1894 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1895 // the sign bit set.
1896 auto *BO = BinaryOperator::CreateUDiv(V1: Op0, V2: Op1, Name: I.getName());
1897 BO->setIsExact(I.isExact());
1898 return BO;
1899 }
1900 }
1901
1902 // -X / X --> X == INT_MIN ? 1 : -1
1903 if (isKnownNegation(X: Op0, Y: Op1)) {
1904 APInt MinVal = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
1905 Value *Cond = Builder.CreateICmpEQ(LHS: Op0, RHS: ConstantInt::get(Ty, V: MinVal));
1906 return createSelectInstWithUnknownProfile(C: Cond, S1: ConstantInt::get(Ty, V: 1),
1907 S2: ConstantInt::getAllOnesValue(Ty));
1908 }
1909 return nullptr;
1910}
1911
1912/// Remove negation and try to convert division into multiplication.
1913Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1914 Constant *C;
1915 if (!match(V: I.getOperand(i_nocapture: 1), P: m_Constant(C)))
1916 return nullptr;
1917
1918 // -X / C --> X / -C
1919 Value *X;
1920 const DataLayout &DL = I.getDataLayout();
1921 if (match(V: I.getOperand(i_nocapture: 0), P: m_FNeg(X: m_Value(V&: X))))
1922 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
1923 return BinaryOperator::CreateFDivFMF(V1: X, V2: NegC, FMFSource: &I);
1924
1925 // nnan X / +0.0 -> copysign(inf, X)
1926 // nnan nsz X / -0.0 -> copysign(inf, X)
1927 if (I.hasNoNaNs() &&
1928 (match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()) ||
1929 (I.hasNoSignedZeros() && match(V: I.getOperand(i_nocapture: 1), P: m_AnyZeroFP())))) {
1930 IRBuilder<> B(&I);
1931 CallInst *CopySign = B.CreateIntrinsic(
1932 ID: Intrinsic::copysign, Types: {C->getType()},
1933 Args: {ConstantFP::getInfinity(Ty: I.getType()), I.getOperand(i_nocapture: 0)}, FMFSource: &I);
1934 CopySign->takeName(V: &I);
1935 return replaceInstUsesWith(I, V: CopySign);
1936 }
1937
1938 // If the constant divisor has an exact inverse, this is always safe. If not,
1939 // then we can still create a reciprocal if fast-math-flags allow it and the
1940 // constant is a regular number (not zero, infinite, or denormal).
1941 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1942 return nullptr;
1943
1944 // Disallow denormal constants because we don't know what would happen
1945 // on all targets.
1946 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1947 // denorms are flushed?
1948 auto *RecipC = ConstantFoldBinaryOpOperands(
1949 Opcode: Instruction::FDiv, LHS: ConstantFP::get(Ty: I.getType(), V: 1.0), RHS: C, DL);
1950 if (!RecipC || !RecipC->isNormalFP())
1951 return nullptr;
1952
1953 // X / C --> X * (1 / C)
1954 return BinaryOperator::CreateFMulFMF(V1: I.getOperand(i_nocapture: 0), V2: RecipC, FMFSource: &I);
1955}
1956
1957/// Remove negation and try to reassociate constant math.
1958static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
1959 Constant *C;
1960 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Constant(C)))
1961 return nullptr;
1962
1963 // C / -X --> -C / X
1964 Value *X;
1965 const DataLayout &DL = I.getDataLayout();
1966 if (match(V: I.getOperand(i_nocapture: 1), P: m_FNeg(X: m_Value(V&: X))))
1967 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
1968 return BinaryOperator::CreateFDivFMF(V1: NegC, V2: X, FMFSource: &I);
1969
1970 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1971 return nullptr;
1972
1973 // Try to reassociate C / X expressions where X includes another constant.
1974 Constant *C2, *NewC = nullptr;
1975 if (match(V: I.getOperand(i_nocapture: 1), P: m_FMul(L: m_Value(V&: X), R: m_Constant(C&: C2)))) {
1976 // C / (X * C2) --> (C / C2) / X
1977 NewC = ConstantFoldBinaryOpOperands(Opcode: Instruction::FDiv, LHS: C, RHS: C2, DL);
1978 } else if (match(V: I.getOperand(i_nocapture: 1), P: m_FDiv(L: m_Value(V&: X), R: m_Constant(C&: C2)))) {
1979 // C / (X / C2) --> (C * C2) / X
1980 NewC = ConstantFoldBinaryOpOperands(Opcode: Instruction::FMul, LHS: C, RHS: C2, DL);
1981 }
1982 // Disallow denormal constants because we don't know what would happen
1983 // on all targets.
1984 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1985 // denorms are flushed?
1986 if (!NewC || !NewC->isNormalFP())
1987 return nullptr;
1988
1989 return BinaryOperator::CreateFDivFMF(V1: NewC, V2: X, FMFSource: &I);
1990}
1991
1992/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1993static Instruction *foldFDivPowDivisor(BinaryOperator &I,
1994 InstCombiner::BuilderTy &Builder) {
1995 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1996 auto *II = dyn_cast<IntrinsicInst>(Val: Op1);
1997 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1998 !I.hasAllowReciprocal())
1999 return nullptr;
2000
2001 // Z / pow(X, Y) --> Z * pow(X, -Y)
2002 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
2003 // In the general case, this creates an extra instruction, but fmul allows
2004 // for better canonicalization and optimization than fdiv.
2005 Intrinsic::ID IID = II->getIntrinsicID();
2006 SmallVector<Value *> Args;
2007 switch (IID) {
2008 case Intrinsic::pow:
2009 Args.push_back(Elt: II->getArgOperand(i: 0));
2010 Args.push_back(Elt: Builder.CreateFNegFMF(V: II->getArgOperand(i: 1), FMFSource: &I));
2011 break;
2012 case Intrinsic::powi: {
2013 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
2014 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
2015 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
2016 // non-standard results, so this corner case should be acceptable if the
2017 // code rules out INF values.
2018 if (!I.hasNoInfs())
2019 return nullptr;
2020 Args.push_back(Elt: II->getArgOperand(i: 0));
2021 Args.push_back(Elt: Builder.CreateNeg(V: II->getArgOperand(i: 1)));
2022 Type *Tys[] = {I.getType(), II->getArgOperand(i: 1)->getType()};
2023 Value *Pow = Builder.CreateIntrinsic(ID: IID, Types: Tys, Args, FMFSource: &I);
2024 return BinaryOperator::CreateFMulFMF(V1: Op0, V2: Pow, FMFSource: &I);
2025 }
2026 case Intrinsic::exp:
2027 case Intrinsic::exp2:
2028 Args.push_back(Elt: Builder.CreateFNegFMF(V: II->getArgOperand(i: 0), FMFSource: &I));
2029 break;
2030 default:
2031 return nullptr;
2032 }
2033 Value *Pow = Builder.CreateIntrinsic(ID: IID, Types: I.getType(), Args, FMFSource: &I);
2034 return BinaryOperator::CreateFMulFMF(V1: Op0, V2: Pow, FMFSource: &I);
2035}
2036
2037/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
2038/// instruction.
2039static Instruction *foldFDivSqrtDivisor(BinaryOperator &I,
2040 InstCombiner::BuilderTy &Builder) {
2041 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
2042 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2043 return nullptr;
2044 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2045 auto *II = dyn_cast<IntrinsicInst>(Val: Op1);
2046 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
2047 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
2048 return nullptr;
2049
2050 Value *Y, *Z;
2051 auto *DivOp = dyn_cast<Instruction>(Val: II->getOperand(i_nocapture: 0));
2052 if (!DivOp)
2053 return nullptr;
2054 if (!match(V: DivOp, P: m_FDiv(L: m_Value(V&: Y), R: m_Value(V&: Z))))
2055 return nullptr;
2056 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
2057 !DivOp->hasOneUse())
2058 return nullptr;
2059 Value *SwapDiv = Builder.CreateFDivFMF(L: Z, R: Y, FMFSource: DivOp);
2060 Value *NewSqrt =
2061 Builder.CreateUnaryIntrinsic(ID: II->getIntrinsicID(), V: SwapDiv, FMFSource: II);
2062 return BinaryOperator::CreateFMulFMF(V1: Op0, V2: NewSqrt, FMFSource: &I);
2063}
2064
2065// Change
2066// X = 1/sqrt(a)
2067// R1 = X * X
2068// R2 = a * X
2069//
2070// TO
2071//
2072// FDiv = 1/a
2073// FSqrt = sqrt(a)
2074// FMul = FDiv * FSqrt
2075// Replace Uses Of R1 With FDiv
2076// Replace Uses Of R2 With FSqrt
2077// Replace Uses Of X With FMul
2078static Instruction *
2079convertFSqrtDivIntoFMul(CallInst *CI, Instruction *X,
2080 const SmallPtrSetImpl<Instruction *> &R1,
2081 const SmallPtrSetImpl<Instruction *> &R2,
2082 InstCombiner::BuilderTy &B, InstCombinerImpl *IC) {
2083
2084 B.SetInsertPoint(X);
2085
2086 // Have an instruction that is representative of all of instructions in R1 and
2087 // get the most common fpmath metadata and fast-math flags on it.
2088 Value *SqrtOp = CI->getArgOperand(i: 0);
2089 auto *FDiv = cast<Instruction>(
2090 Val: B.CreateFDiv(L: ConstantFP::get(Ty: X->getType(), V: 1.0), R: SqrtOp));
2091 auto *R1FPMathMDNode = (*R1.begin())->getMetadata(KindID: LLVMContext::MD_fpmath);
2092 FastMathFlags R1FMF = (*R1.begin())->getFastMathFlags(); // Common FMF
2093 for (Instruction *I : R1) {
2094 R1FPMathMDNode = MDNode::getMostGenericFPMath(
2095 A: R1FPMathMDNode, B: I->getMetadata(KindID: LLVMContext::MD_fpmath));
2096 R1FMF &= I->getFastMathFlags();
2097 IC->replaceInstUsesWith(I&: *I, V: FDiv);
2098 IC->eraseInstFromFunction(I&: *I);
2099 }
2100 FDiv->setMetadata(KindID: LLVMContext::MD_fpmath, Node: R1FPMathMDNode);
2101 FDiv->copyFastMathFlags(FMF: R1FMF);
2102
2103 // Have a single sqrt call instruction that is representative of all of
2104 // instructions in R2 and get the most common fpmath metadata and fast-math
2105 // flags on it.
2106 auto *FSqrt = cast<CallInst>(Val: CI->clone());
2107 FSqrt->insertBefore(InsertPos: CI->getIterator());
2108 auto *R2FPMathMDNode = (*R2.begin())->getMetadata(KindID: LLVMContext::MD_fpmath);
2109 FastMathFlags R2FMF = (*R2.begin())->getFastMathFlags(); // Common FMF
2110 for (Instruction *I : R2) {
2111 R2FPMathMDNode = MDNode::getMostGenericFPMath(
2112 A: R2FPMathMDNode, B: I->getMetadata(KindID: LLVMContext::MD_fpmath));
2113 R2FMF &= I->getFastMathFlags();
2114 IC->replaceInstUsesWith(I&: *I, V: FSqrt);
2115 IC->eraseInstFromFunction(I&: *I);
2116 }
2117 FSqrt->setMetadata(KindID: LLVMContext::MD_fpmath, Node: R2FPMathMDNode);
2118 FSqrt->copyFastMathFlags(FMF: R2FMF);
2119
2120 Instruction *FMul;
2121 // If X = -1/sqrt(a) initially,then FMul = -(FDiv * FSqrt)
2122 if (match(V: X, P: m_FDiv(L: m_SpecificFP(V: -1.0), R: m_Specific(V: CI)))) {
2123 Value *Mul = B.CreateFMul(L: FDiv, R: FSqrt);
2124 FMul = cast<Instruction>(Val: B.CreateFNeg(V: Mul));
2125 } else
2126 FMul = cast<Instruction>(Val: B.CreateFMul(L: FDiv, R: FSqrt));
2127 FMul->copyMetadata(SrcInst: *X);
2128 FMul->copyFastMathFlags(FMF: FastMathFlags::intersectRewrite(LHS: R1FMF, RHS: R2FMF) |
2129 FastMathFlags::unionValue(LHS: R1FMF, RHS: R2FMF));
2130 return IC->replaceInstUsesWith(I&: *X, V: FMul);
2131}
2132
2133Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) {
2134 Module *M = I.getModule();
2135
2136 if (Value *V = simplifyFDivInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2137 FMF: I.getFastMathFlags(),
2138 Q: SQ.getWithInstruction(I: &I)))
2139 return replaceInstUsesWith(I, V);
2140
2141 if (Instruction *X = foldVectorBinop(Inst&: I))
2142 return X;
2143
2144 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2145 return Phi;
2146
2147 if (Instruction *R = foldFDivConstantDivisor(I))
2148 return R;
2149
2150 if (Instruction *R = foldFDivConstantDividend(I))
2151 return R;
2152
2153 if (Instruction *R = foldFPSignBitOps(I))
2154 return R;
2155
2156 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2157
2158 // Convert
2159 // x = 1.0/sqrt(a)
2160 // r1 = x * x;
2161 // r2 = a/sqrt(a);
2162 //
2163 // TO
2164 //
2165 // r1 = 1/a
2166 // r2 = sqrt(a)
2167 // x = r1 * r2
2168 SmallPtrSet<Instruction *, 2> R1, R2;
2169 if (isFSqrtDivToFMulLegal(X: &I, R1, R2)) {
2170 CallInst *CI = cast<CallInst>(Val: I.getOperand(i_nocapture: 1));
2171 if (Instruction *D = convertFSqrtDivIntoFMul(CI, X: &I, R1, R2, B&: Builder, IC: this))
2172 return D;
2173 }
2174
2175 if (isa<Constant>(Val: Op0))
2176 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
2177 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
2178 return R;
2179
2180 if (isa<Constant>(Val: Op1))
2181 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op0))
2182 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
2183 return R;
2184
2185 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
2186 Value *X, *Y;
2187 if (match(V: Op0, P: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
2188 (!isa<Constant>(Val: Y) || !isa<Constant>(Val: Op1))) {
2189 // (X / Y) / Z => X / (Y * Z)
2190 Value *YZ = Builder.CreateFMulFMF(L: Y, R: Op1, FMFSource: &I);
2191 return BinaryOperator::CreateFDivFMF(V1: X, V2: YZ, FMFSource: &I);
2192 }
2193 if (match(V: Op1, P: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
2194 (!isa<Constant>(Val: Y) || !isa<Constant>(Val: Op0))) {
2195 // Z / (X / Y) => (Y * Z) / X
2196 Value *YZ = Builder.CreateFMulFMF(L: Y, R: Op0, FMFSource: &I);
2197 return BinaryOperator::CreateFDivFMF(V1: YZ, V2: X, FMFSource: &I);
2198 }
2199 // Z / (1.0 / Y) => (Y * Z)
2200 //
2201 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
2202 // m_OneUse check is avoided because even in the case of the multiple uses
2203 // for 1.0/Y, the number of instructions remain the same and a division is
2204 // replaced by a multiplication.
2205 if (match(V: Op1, P: m_FDiv(L: m_SpecificFP(V: 1.0), R: m_Value(V&: Y))))
2206 return BinaryOperator::CreateFMulFMF(V1: Y, V2: Op0, FMFSource: &I);
2207 }
2208
2209 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
2210 // sin(X) / cos(X) -> tan(X)
2211 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
2212 Value *X;
2213 bool IsTan = match(V: Op0, P: m_Intrinsic<Intrinsic::sin>(Op0: m_Value(V&: X))) &&
2214 match(V: Op1, P: m_Intrinsic<Intrinsic::cos>(Op0: m_Specific(V: X)));
2215 bool IsCot =
2216 !IsTan && match(V: Op0, P: m_Intrinsic<Intrinsic::cos>(Op0: m_Value(V&: X))) &&
2217 match(V: Op1, P: m_Intrinsic<Intrinsic::sin>(Op0: m_Specific(V: X)));
2218
2219 if ((IsTan || IsCot) && hasFloatFn(M, TLI: &TLI, Ty: I.getType(), DoubleFn: LibFunc_tan,
2220 FloatFn: LibFunc_tanf, LongDoubleFn: LibFunc_tanl)) {
2221 IRBuilder<> B(&I);
2222 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
2223 B.setFastMathFlags(I.getFastMathFlags());
2224 AttributeList Attrs =
2225 cast<CallBase>(Val: Op0)->getCalledFunction()->getAttributes();
2226 Value *Res = emitUnaryFloatFnCall(Op: X, TLI: &TLI, DoubleFn: LibFunc_tan, FloatFn: LibFunc_tanf,
2227 LongDoubleFn: LibFunc_tanl, B, Attrs);
2228 if (IsCot)
2229 Res = B.CreateFDiv(L: ConstantFP::get(Ty: I.getType(), V: 1.0), R: Res);
2230 return replaceInstUsesWith(I, V: Res);
2231 }
2232 }
2233
2234 // X / (X * Y) --> 1.0 / Y
2235 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
2236 // We can ignore the possibility that X is infinity because INF/INF is NaN.
2237 Value *X, *Y;
2238 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
2239 match(V: Op1, P: m_c_FMul(L: m_Specific(V: Op0), R: m_Value(V&: Y)))) {
2240 replaceOperand(I, OpNum: 0, V: ConstantFP::get(Ty: I.getType(), V: 1.0));
2241 replaceOperand(I, OpNum: 1, V: Y);
2242 return &I;
2243 }
2244
2245 // X / fabs(X) -> copysign(1.0, X)
2246 // fabs(X) / X -> copysign(1.0, X)
2247 if (I.hasNoNaNs() && I.hasNoInfs() &&
2248 (match(V: &I, P: m_FDiv(L: m_Value(V&: X), R: m_FAbs(Op0: m_Deferred(V: X)))) ||
2249 match(V: &I, P: m_FDiv(L: m_FAbs(Op0: m_Value(V&: X)), R: m_Deferred(V: X))))) {
2250 Value *V = Builder.CreateBinaryIntrinsic(
2251 ID: Intrinsic::copysign, LHS: ConstantFP::get(Ty: I.getType(), V: 1.0), RHS: X, FMFSource: &I);
2252 return replaceInstUsesWith(I, V);
2253 }
2254
2255 if (Instruction *Mul = foldFDivPowDivisor(I, Builder))
2256 return Mul;
2257
2258 if (Instruction *Mul = foldFDivSqrtDivisor(I, Builder))
2259 return Mul;
2260
2261 // pow(X, Y) / X --> pow(X, Y-1)
2262 if (I.hasAllowReassoc() &&
2263 match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::pow>(Op0: m_Specific(V: Op1),
2264 Op1: m_Value(V&: Y))))) {
2265 Value *Y1 =
2266 Builder.CreateFAddFMF(L: Y, R: ConstantFP::get(Ty: I.getType(), V: -1.0), FMFSource: &I);
2267 Value *Pow = Builder.CreateBinaryIntrinsic(ID: Intrinsic::pow, LHS: Op1, RHS: Y1, FMFSource: &I);
2268 return replaceInstUsesWith(I, V: Pow);
2269 }
2270
2271 if (Instruction *FoldedPowi = foldPowiReassoc(I))
2272 return FoldedPowi;
2273
2274 return nullptr;
2275}
2276
2277// Variety of transform for:
2278// (urem/srem (mul X, Y), (mul X, Z))
2279// (urem/srem (shl X, Y), (shl X, Z))
2280// (urem/srem (shl Y, X), (shl Z, X))
2281// NB: The shift cases are really just extensions of the mul case. We treat
2282// shift as Val * (1 << Amt).
2283static Instruction *simplifyIRemMulShl(BinaryOperator &I,
2284 InstCombinerImpl &IC) {
2285 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *X = nullptr;
2286 APInt Y, Z;
2287 bool ShiftByX = false;
2288
2289 // If V is not nullptr, it will be matched using m_Specific.
2290 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C,
2291 bool &PreserveNSW) -> bool {
2292 const APInt *Tmp = nullptr;
2293 if ((!V && match(V: Op, P: m_Mul(L: m_Value(V), R: m_APInt(Res&: Tmp)))) ||
2294 (V && match(V: Op, P: m_Mul(L: m_Specific(V), R: m_APInt(Res&: Tmp)))))
2295 C = *Tmp;
2296 else if ((!V && match(V: Op, P: m_Shl(L: m_Value(V), R: m_APInt(Res&: Tmp)))) ||
2297 (V && match(V: Op, P: m_Shl(L: m_Specific(V), R: m_APInt(Res&: Tmp))))) {
2298 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
2299 // We cannot preserve NSW when shifting by BW - 1.
2300 PreserveNSW = Tmp->ult(RHS: Tmp->getBitWidth() - 1);
2301 }
2302 if (Tmp != nullptr)
2303 return true;
2304
2305 // Reset `V` so we don't start with specific value on next match attempt.
2306 V = nullptr;
2307 return false;
2308 };
2309
2310 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
2311 const APInt *Tmp = nullptr;
2312 if ((!V && match(V: Op, P: m_Shl(L: m_APInt(Res&: Tmp), R: m_Value(V)))) ||
2313 (V && match(V: Op, P: m_Shl(L: m_APInt(Res&: Tmp), R: m_Specific(V))))) {
2314 C = *Tmp;
2315 return true;
2316 }
2317
2318 // Reset `V` so we don't start with specific value on next match attempt.
2319 V = nullptr;
2320 return false;
2321 };
2322
2323 bool Op0PreserveNSW = true, Op1PreserveNSW = true;
2324 if (MatchShiftOrMulXC(Op0, X, Y, Op0PreserveNSW) &&
2325 MatchShiftOrMulXC(Op1, X, Z, Op1PreserveNSW)) {
2326 // pass
2327 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
2328 ShiftByX = true;
2329 } else {
2330 return nullptr;
2331 }
2332
2333 bool IsSRem = I.getOpcode() == Instruction::SRem;
2334
2335 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Val: Op0);
2336 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2337 // Z or Z >= Y.
2338 bool BO0HasNSW = Op0PreserveNSW && BO0->hasNoSignedWrap();
2339 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2340 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2341
2342 APInt RemYZ = IsSRem ? Y.srem(RHS: Z) : Y.urem(RHS: Z);
2343 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2344 // if (rem Y, Z) == 0
2345 // -> 0
2346 if (RemYZ.isZero() && BO0NoWrap)
2347 return IC.replaceInstUsesWith(I, V: ConstantInt::getNullValue(Ty: I.getType()));
2348
2349 // Helper function to emit either (RemSimplificationC << X) or
2350 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2351 // (shl V, X) or (mul V, X) respectively.
2352 auto CreateMulOrShift =
2353 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2354 Value *RemSimplification =
2355 ConstantInt::get(Ty: I.getType(), V: RemSimplificationC);
2356 return ShiftByX ? BinaryOperator::CreateShl(V1: RemSimplification, V2: X)
2357 : BinaryOperator::CreateMul(V1: X, V2: RemSimplification);
2358 };
2359
2360 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Val: Op1);
2361 bool BO1HasNSW = Op1PreserveNSW && BO1->hasNoSignedWrap();
2362 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2363 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2364 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2365 // if (rem Y, Z) == Y
2366 // -> (mul nuw/nsw X, Y)
2367 if (RemYZ == Y && BO1NoWrap) {
2368 BinaryOperator *BO = CreateMulOrShift(Y);
2369 // Copy any overflow flags from Op0.
2370 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2371 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2372 return BO;
2373 }
2374
2375 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2376 // if Y >= Z
2377 // -> (mul {nuw} nsw X, (rem Y, Z))
2378 if (Y.uge(RHS: Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2379 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2380 BO->setHasNoSignedWrap();
2381 BO->setHasNoUnsignedWrap(BO0HasNUW);
2382 return BO;
2383 }
2384
2385 return nullptr;
2386}
2387
2388/// This function implements the transforms common to both integer remainder
2389/// instructions (urem and srem). It is called by the visitors to those integer
2390/// remainder instructions.
2391/// Common integer remainder transforms
2392Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) {
2393 if (Instruction *Res = commonIDivRemTransforms(I))
2394 return Res;
2395
2396 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2397
2398 if (isa<Constant>(Val: Op1)) {
2399 if (Instruction *Op0I = dyn_cast<Instruction>(Val: Op0)) {
2400 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op0I)) {
2401 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
2402 return R;
2403 } else if (auto *PN = dyn_cast<PHINode>(Val: Op0I)) {
2404 const APInt *Op1Int;
2405 if (match(V: Op1, P: m_APInt(Res&: Op1Int)) && !Op1Int->isMinValue() &&
2406 (I.getOpcode() == Instruction::URem ||
2407 !Op1Int->isMinSignedValue())) {
2408 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2409 // predecessor blocks, so do this only if we know the srem or urem
2410 // will not fault.
2411 if (Instruction *NV = foldOpIntoPhi(I, PN))
2412 return NV;
2413 }
2414 }
2415
2416 // See if we can fold away this rem instruction.
2417 if (SimplifyDemandedInstructionBits(Inst&: I))
2418 return &I;
2419 }
2420 }
2421
2422 if (Instruction *R = simplifyIRemMulShl(I, IC&: *this))
2423 return R;
2424
2425 return nullptr;
2426}
2427
2428Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) {
2429 if (Value *V = simplifyURemInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2430 Q: SQ.getWithInstruction(I: &I)))
2431 return replaceInstUsesWith(I, V);
2432
2433 if (Instruction *X = foldVectorBinop(Inst&: I))
2434 return X;
2435
2436 if (Instruction *common = commonIRemTransforms(I))
2437 return common;
2438
2439 if (Instruction *NarrowRem = narrowUDivURem(I, IC&: *this))
2440 return NarrowRem;
2441
2442 // X urem Y -> X and Y-1, where Y is a power of 2,
2443 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2444 Type *Ty = I.getType();
2445 if (isKnownToBeAPowerOfTwo(V: Op1, /*OrZero*/ true, CxtI: &I)) {
2446 // This may increase instruction count, we don't enforce that Y is a
2447 // constant.
2448 Constant *N1 = Constant::getAllOnesValue(Ty);
2449 Value *Add = Builder.CreateAdd(LHS: Op1, RHS: N1);
2450 return BinaryOperator::CreateAnd(V1: Op0, V2: Add);
2451 }
2452
2453 // 1 urem X -> zext(X != 1)
2454 if (match(V: Op0, P: m_One())) {
2455 Value *Cmp = Builder.CreateICmpNE(LHS: Op1, RHS: ConstantInt::get(Ty, V: 1));
2456 return CastInst::CreateZExtOrBitCast(S: Cmp, Ty);
2457 }
2458
2459 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2460 // Op0 must be frozen because we are increasing its number of uses.
2461 if (match(V: Op1, P: m_Negative())) {
2462 Value *F0 = Op0;
2463 if (!isGuaranteedNotToBeUndef(V: Op0))
2464 F0 = Builder.CreateFreeze(V: Op0, Name: Op0->getName() + ".fr");
2465 Value *Cmp = Builder.CreateICmpULT(LHS: F0, RHS: Op1);
2466 Value *Sub = Builder.CreateSub(LHS: F0, RHS: Op1);
2467 return createSelectInstWithUnknownProfile(C: Cmp, S1: F0, S2: Sub);
2468 }
2469
2470 // If the divisor is a sext of a boolean, then the divisor must be max
2471 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2472 // max unsigned value. In that case, the remainder is 0:
2473 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2474 Value *X;
2475 if (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2476 Value *FrozenOp0 = Op0;
2477 if (!isGuaranteedNotToBeUndef(V: Op0))
2478 FrozenOp0 = Builder.CreateFreeze(V: Op0, Name: Op0->getName() + ".frozen");
2479 Value *Cmp =
2480 Builder.CreateICmpEQ(LHS: FrozenOp0, RHS: ConstantInt::getAllOnesValue(Ty));
2481 return createSelectInstWithUnknownProfile(
2482 C: Cmp, S1: ConstantInt::getNullValue(Ty), S2: FrozenOp0);
2483 }
2484
2485 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2486 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_One()))) {
2487 Value *Val =
2488 simplifyICmpInst(Pred: ICmpInst::ICMP_ULT, LHS: X, RHS: Op1, Q: SQ.getWithInstruction(I: &I));
2489 if (Val && match(V: Val, P: m_One())) {
2490 Value *FrozenOp0 = Op0;
2491 if (!isGuaranteedNotToBeUndef(V: Op0))
2492 FrozenOp0 = Builder.CreateFreeze(V: Op0, Name: Op0->getName() + ".frozen");
2493 Value *Cmp = Builder.CreateICmpEQ(LHS: FrozenOp0, RHS: Op1);
2494 return createSelectInstWithUnknownProfile(
2495 C: Cmp, S1: ConstantInt::getNullValue(Ty), S2: FrozenOp0);
2496 }
2497 }
2498
2499 return nullptr;
2500}
2501
2502Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) {
2503 if (Value *V = simplifySRemInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2504 Q: SQ.getWithInstruction(I: &I)))
2505 return replaceInstUsesWith(I, V);
2506
2507 if (Instruction *X = foldVectorBinop(Inst&: I))
2508 return X;
2509
2510 // Handle the integer rem common cases
2511 if (Instruction *Common = commonIRemTransforms(I))
2512 return Common;
2513
2514 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2515 {
2516 const APInt *Y;
2517 // X % -Y -> X % Y
2518 if (match(V: Op1, P: m_Negative(V&: Y)) && !Y->isMinSignedValue())
2519 return replaceOperand(I, OpNum: 1, V: ConstantInt::get(Ty: I.getType(), V: -*Y));
2520 }
2521
2522 // -X srem Y --> -(X srem Y)
2523 Value *X, *Y;
2524 if (match(V: &I, P: m_SRem(L: m_OneUse(SubPattern: m_NSWNeg(V: m_Value(V&: X))), R: m_Value(V&: Y))))
2525 return BinaryOperator::CreateNSWNeg(Op: Builder.CreateSRem(LHS: X, RHS: Y));
2526
2527 // If the sign bits of both operands are zero (i.e. we can prove they are
2528 // unsigned inputs), turn this into a urem.
2529 APInt Mask(APInt::getSignMask(BitWidth: I.getType()->getScalarSizeInBits()));
2530 if (MaskedValueIsZero(V: Op1, Mask, CxtI: &I) && MaskedValueIsZero(V: Op0, Mask, CxtI: &I)) {
2531 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2532 return BinaryOperator::CreateURem(V1: Op0, V2: Op1, Name: I.getName());
2533 }
2534
2535 // If it's a constant vector, flip any negative values positive.
2536 if (isa<ConstantVector>(Val: Op1) || isa<ConstantDataVector>(Val: Op1)) {
2537 Constant *C = cast<Constant>(Val: Op1);
2538 unsigned VWidth = cast<FixedVectorType>(Val: C->getType())->getNumElements();
2539
2540 bool hasNegative = false;
2541 bool hasMissing = false;
2542 for (unsigned i = 0; i != VWidth; ++i) {
2543 Constant *Elt = C->getAggregateElement(Elt: i);
2544 if (!Elt) {
2545 hasMissing = true;
2546 break;
2547 }
2548
2549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Val: Elt))
2550 if (RHS->isNegative())
2551 hasNegative = true;
2552 }
2553
2554 if (hasNegative && !hasMissing) {
2555 SmallVector<Constant *, 16> Elts(VWidth);
2556 for (unsigned i = 0; i != VWidth; ++i) {
2557 Elts[i] = C->getAggregateElement(Elt: i); // Handle undef, etc.
2558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Val: Elts[i])) {
2559 if (RHS->isNegative())
2560 Elts[i] = cast<ConstantInt>(Val: ConstantExpr::getNeg(C: RHS));
2561 }
2562 }
2563
2564 Constant *NewRHSV = ConstantVector::get(V: Elts);
2565 if (NewRHSV != C) // Don't loop on -MININT
2566 return replaceOperand(I, OpNum: 1, V: NewRHSV);
2567 }
2568 }
2569
2570 return nullptr;
2571}
2572
2573Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) {
2574 if (Value *V = simplifyFRemInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2575 FMF: I.getFastMathFlags(),
2576 Q: SQ.getWithInstruction(I: &I)))
2577 return replaceInstUsesWith(I, V);
2578
2579 if (Instruction *X = foldVectorBinop(Inst&: I))
2580 return X;
2581
2582 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2583 return Phi;
2584
2585 return nullptr;
2586}
2587