blob: cbbde9a1aeb828753b7bd5f7ccf789a14b708067 [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerdc054bf2010-01-05 06:09:35 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/SmallVector.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000018#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000026#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000028#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000029#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/KnownBits.h"
34#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Dmitry Venikove5fbf592018-01-11 06:33:00 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000036#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <utility>
40
Chris Lattnerdc054bf2010-01-05 06:09:35 +000041using namespace llvm;
42using namespace PatternMatch;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "instcombine"
45
Sanjay Patel6eccf482015-09-09 15:24:36 +000046/// The specific integer value is used in a context where it is known to be
47/// non-zero. If this allows us to simplify the computation, do so and return
48/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000049static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000051 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000054 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 bool MadeChange = false;
57
Chris Lattner7c99f192011-05-22 18:18:41 +000058 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000060 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000063 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000065 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000066
Chris Lattner388cb8a2011-05-23 00:32:19 +000067 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000069 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
70 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000071 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000072 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Nikita Popov4b35c812020-03-30 22:00:16 +020075 IC.replaceOperand(*I, 0, V2);
Sanjay Patela8ef4a52016-05-22 17:08:52 +000076 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000077 }
78
Sanjay Patela8ef4a52016-05-22 17:08:52 +000079 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
80 I->setIsExact();
81 MadeChange = true;
82 }
83
84 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
85 I->setHasNoUnsignedWrap();
86 MadeChange = true;
87 }
88 }
89
Chris Lattner162dfc32011-05-22 18:26:48 +000090 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000091 // If V is a phi node, we can call this on each of its operands.
92 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093
Craig Topperf40110f2014-04-25 05:29:35 +000094 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000095}
96
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000097/// A helper routine of InstCombiner::visitMul().
Rafael Espindola65281bf2013-05-31 14:27:15 +000098///
Christopher Tetreault855e02e2020-05-05 14:21:59 -070099/// If C is a scalar/fixed width vector of known powers of 2, then this
100/// function returns a new scalar/fixed width vector obtained from logBase2
101/// of C.
Rafael Espindola65281bf2013-05-31 14:27:15 +0000102/// Return a null pointer otherwise.
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000103static Constant *getLogBase2(Type *Ty, Constant *C) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000104 const APInt *IVal;
Simon Pilgrimbe0dd722018-02-13 13:16:26 +0000105 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
106 return ConstantInt::get(Ty, IVal->logBase2());
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107
Christopher Tetreault855e02e2020-05-05 14:21:59 -0700108 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
109 if (!isa<FixedVectorType>(Ty))
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000110 return nullptr;
111
112 SmallVector<Constant *, 4> Elts;
Christopher Tetreault855e02e2020-05-05 14:21:59 -0700113 for (unsigned I = 0, E = cast<FixedVectorType>(Ty)->getNumElements(); I != E;
Christopher Tetreault155740c2020-04-08 10:42:22 -0700114 ++I) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000115 Constant *Elt = C->getAggregateElement(I);
116 if (!Elt)
117 return nullptr;
118 if (isa<UndefValue>(Elt)) {
119 Elts.push_back(UndefValue::get(Ty->getScalarType()));
120 continue;
121 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000122 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000123 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000124 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000125 }
126
127 return ConstantVector::get(Elts);
128}
129
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000130// TODO: This is a specific form of a much more general pattern.
131// We could detect a select with any binop identity constant, or we
132// could use SimplifyBinOp to see if either arm of the select reduces.
133// But that needs to be done carefully and/or while removing potential
134// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
135static Value *foldMulSelectToNegate(BinaryOperator &I,
136 InstCombiner::BuilderTy &Builder) {
137 Value *Cond, *OtherOp;
138
139 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
140 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
141 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())),
142 m_Value(OtherOp))))
143 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp));
144
145 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
146 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
147 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())),
148 m_Value(OtherOp))))
149 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp);
150
151 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
152 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
153 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0),
154 m_SpecificFP(-1.0))),
155 m_Value(OtherOp)))) {
156 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
157 Builder.setFastMathFlags(I.getFastMathFlags());
158 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
159 }
160
161 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
162 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
163 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0),
164 m_SpecificFP(1.0))),
165 m_Value(OtherOp)))) {
166 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
167 Builder.setFastMathFlags(I.getFastMathFlags());
168 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
169 }
170
171 return nullptr;
172}
173
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000174Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000175 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
176 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000177 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000178
Sanjay Patel70043b72018-07-13 01:18:07 +0000179 if (SimplifyAssociativeOrCommutative(I))
180 return &I;
181
Sanjay Patel79dceb22018-10-03 15:20:58 +0000182 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000183 return X;
184
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000185 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000186 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000187
David Majnemer027bc802014-11-22 04:52:38 +0000188 // X * -1 == 0 - X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemer027bc802014-11-22 04:52:38 +0000190 if (match(Op1, m_AllOnes())) {
191 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
192 if (I.hasNoSignedWrap())
193 BO->setHasNoSignedWrap();
194 return BO;
195 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000196
Rafael Espindola65281bf2013-05-31 14:27:15 +0000197 // Also allow combining multiply instructions on vectors.
198 {
199 Value *NewOp;
200 Constant *C1, *C2;
201 const APInt *IVal;
202 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
203 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000204 match(C1, m_APInt(IVal))) {
205 // ((X << C2)*C1) == (X * (C1 << C2))
206 Constant *Shl = ConstantExpr::getShl(C1, C2);
207 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
208 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
209 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
210 BO->setHasNoUnsignedWrap();
211 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
212 Shl->isNotMinSignedValue())
213 BO->setHasNoSignedWrap();
214 return BO;
215 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216
Rafael Espindola65281bf2013-05-31 14:27:15 +0000217 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000218 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
219 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000220 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000221
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000222 if (I.hasNoUnsignedWrap())
223 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000224 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000225 const APInt *V;
Craig Topper4e63db82018-09-11 17:57:20 +0000226 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000227 Shl->setHasNoSignedWrap();
228 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000229
Rafael Espindola65281bf2013-05-31 14:27:15 +0000230 return Shl;
231 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000232 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000233 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000234
Rafael Espindola65281bf2013-05-31 14:27:15 +0000235 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000236 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
237 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
238 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000239 {
240 const APInt & Val = CI->getValue();
241 const APInt &PosVal = Val.abs();
242 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000243 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000244 if (Op0->hasOneUse()) {
245 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000246 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000247 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000248 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000249 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000250 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000251 if (Sub)
252 return
253 BinaryOperator::CreateMul(Sub,
254 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000255 }
256 }
257 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000258 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000259
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000260 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
261 return FoldedMul;
262
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000263 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
264 return replaceInstUsesWith(I, FoldedMul);
Sanjay Patel712b7c22019-09-30 17:02:26 +0000265
Chris Lattner6b657ae2011-02-10 05:36:31 +0000266 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000267 if (isa<Constant>(Op1)) {
Benjamin Kramer72196f32014-01-19 15:24:22 +0000268 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000269 Value *X;
270 Constant *C1;
271 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
272 Value *Mul = Builder.CreateMul(C1, Op1);
273 // Only go forward with the transform if C1*CI simplifies to a tidier
274 // constant.
275 if (!match(Mul, m_Mul(m_Value(), m_Value())))
276 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000277 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000278 }
279
Simon Pilgrim94006142020-05-04 15:21:52 +0100280 // abs(X) * abs(X) -> X * X
281 // nabs(X) * nabs(X) -> X * X
282 if (Op0 == Op1) {
283 Value *X, *Y;
284 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
285 if (SPF == SPF_ABS || SPF == SPF_NABS)
286 return BinaryOperator::CreateMul(X, X);
287 }
288
Sanjay Patel604cb9e2018-02-14 16:50:55 +0000289 // -X * C --> X * -C
290 Value *X, *Y;
291 Constant *Op1C;
292 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
293 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
294
295 // -X * -Y --> X * Y
296 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
297 auto *NewMul = BinaryOperator::CreateMul(X, Y);
298 if (I.hasNoSignedWrap() &&
299 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
300 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
301 NewMul->setHasNoSignedWrap();
302 return NewMul;
David Majnemer8279a7502014-11-22 07:25:19 +0000303 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000304
Chen Zheng4952e662019-01-01 01:09:20 +0000305 // -X * Y --> -(X * Y)
306 // X * -Y --> -(X * Y)
307 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))
308 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
309
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000310 // (X / Y) * Y = X - (X % Y)
311 // (X / Y) * -Y = (X % Y) - X
312 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000313 Value *Y = Op1;
314 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
315 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
316 Div->getOpcode() != Instruction::SDiv)) {
317 Y = Op0;
318 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000319 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000320 Value *Neg = dyn_castNegVal(Y);
321 if (Div && Div->hasOneUse() &&
322 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
323 (Div->getOpcode() == Instruction::UDiv ||
324 Div->getOpcode() == Instruction::SDiv)) {
325 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000326
Chris Lattner35315d02011-02-06 21:44:57 +0000327 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000328 if (Div->isExact()) {
329 if (DivOp1 == Y)
330 return replaceInstUsesWith(I, X);
331 return BinaryOperator::CreateNeg(X);
332 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333
Sanjay Patela0a56822017-03-14 17:27:27 +0000334 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
335 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000336 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000337 if (DivOp1 == Y)
338 return BinaryOperator::CreateSub(X, Rem);
339 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000340 }
341 }
342
343 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000344 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000345 return BinaryOperator::CreateAnd(Op0, Op1);
346
347 // X*(1 << Y) --> X << Y
348 // (1 << Y)*X --> X << Y
349 {
350 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000351 BinaryOperator *BO = nullptr;
352 bool ShlNSW = false;
353 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
354 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000355 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000356 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000357 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000358 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000359 }
360 if (BO) {
361 if (I.hasNoUnsignedWrap())
362 BO->setHasNoUnsignedWrap();
363 if (I.hasNoSignedWrap() && ShlNSW)
364 BO->setHasNoSignedWrap();
365 return BO;
366 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000367 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000368
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000369 // (bool X) * Y --> X ? Y : 0
Sanjay Patel7558d862018-02-13 22:24:37 +0000370 // Y * (bool X) --> X ? Y : 0
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000371 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
372 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000373 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
374 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
375
Sanjay Patel7558d862018-02-13 22:24:37 +0000376 // (lshr X, 31) * Y --> (ashr X, 31) & Y
377 // Y * (lshr X, 31) --> (ashr X, 31) & Y
378 // TODO: We are not checking one-use because the elimination of the multiply
379 // is better for analysis?
380 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
381 // more similar to what we're doing above.
382 const APInt *C;
383 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
384 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
385 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
386 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000387
Sanjay Patel90a36342018-09-14 22:23:35 +0000388 if (Instruction *Ext = narrowMathIfNoOverflow(I))
389 return Ext;
David Majnemera1cfd7c2016-12-30 00:28:58 +0000390
Sanjay Patel70043b72018-07-13 01:18:07 +0000391 bool Changed = false;
Craig Topper2b1fc322017-05-22 06:25:31 +0000392 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000393 Changed = true;
394 I.setHasNoSignedWrap(true);
395 }
396
Craig Topperbb973722017-05-15 02:44:08 +0000397 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000398 Changed = true;
399 I.setHasNoUnsignedWrap(true);
400 }
401
Craig Topperf40110f2014-04-25 05:29:35 +0000402 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000403}
404
Sanjay Patel7b201bf2020-06-20 11:47:00 -0400405static Instruction *foldFPSignBitOps(BinaryOperator &I) {
Sanjay Pateld84cdb82020-06-20 10:20:21 -0400406 BinaryOperator::BinaryOps Opcode = I.getOpcode();
Sanjay Patel7b201bf2020-06-20 11:47:00 -0400407 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
408 "Expected fmul or fdiv");
409
410 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Pateld84cdb82020-06-20 10:20:21 -0400411 Value *X, *Y;
412
413 // -X * -Y --> X * Y
414 // -X / -Y --> X / Y
415 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
416 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
417
418 // fabs(X) * fabs(X) -> X * X
419 // fabs(X) / fabs(X) -> X / X
420 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
421 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
422
423 return nullptr;
424}
425
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000426Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000427 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
428 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +0000429 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000430 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000431
Sanjay Patel70043b72018-07-13 01:18:07 +0000432 if (SimplifyAssociativeOrCommutative(I))
433 return &I;
434
Sanjay Patel79dceb22018-10-03 15:20:58 +0000435 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000436 return X;
437
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000438 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
439 return FoldedMul;
440
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000441 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
442 return replaceInstUsesWith(I, FoldedMul);
443
Sanjay Patel7b201bf2020-06-20 11:47:00 -0400444 if (Instruction *R = foldFPSignBitOps(I))
Sanjay Pateld84cdb82020-06-20 10:20:21 -0400445 return R;
446
Sanjay Patele29375d2018-03-02 23:06:45 +0000447 // X * -1.0 --> -X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000448 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patele29375d2018-03-02 23:06:45 +0000449 if (match(Op1, m_SpecificFP(-1.0)))
Simon Mollddd11272020-02-27 09:05:54 -0800450 return UnaryOperator::CreateFNegFMF(Op0, &I);
Sanjay Patel6b9c7a92018-02-23 17:14:28 +0000451
Sanjay Patele29375d2018-03-02 23:06:45 +0000452 // -X * C --> X * -C
Sanjay Pateld84cdb82020-06-20 10:20:21 -0400453 Value *X, *Y;
Sanjay Patele29375d2018-03-02 23:06:45 +0000454 Constant *C;
455 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
456 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000457
Sanjay Patele29375d2018-03-02 23:06:45 +0000458 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
459 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
460 return replaceInstUsesWith(I, V);
461
Sanjay Patel81b3b102018-04-03 22:19:19 +0000462 if (I.hasAllowReassoc()) {
463 // Reassociate constant RHS with another constant to form constant
464 // expression.
465 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
466 Constant *C1;
467 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
468 // (C1 / X) * C --> (C * C1) / X
469 Constant *CC1 = ConstantExpr::getFMul(C, C1);
470 if (CC1->isNormalFP())
471 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
472 }
473 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
474 // (X / C1) * C --> X * (C / C1)
475 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
476 if (CDivC1->isNormalFP())
477 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
Sanjay Patel204edec2018-03-13 14:46:32 +0000478
Sanjay Patel81b3b102018-04-03 22:19:19 +0000479 // If the constant was a denormal, try reassociating differently.
480 // (X / C1) * C --> X / (C1 / C)
481 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
482 if (Op0->hasOneUse() && C1DivC->isNormalFP())
483 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
484 }
485
486 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
487 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
488 // further folds and (X * C) + C2 is 'fma'.
489 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
490 // (X + C1) * C --> (X * C) + (C * C1)
491 Constant *CC1 = ConstantExpr::getFMul(C, C1);
492 Value *XC = Builder.CreateFMulFMF(X, C, &I);
493 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
494 }
495 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
496 // (C1 - X) * C --> (C * C1) - (X * C)
497 Constant *CC1 = ConstantExpr::getFMul(C, C1);
498 Value *XC = Builder.CreateFMulFMF(X, C, &I);
499 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
500 }
Sanjay Patel204edec2018-03-13 14:46:32 +0000501 }
502
Sanjay Patel5e13cd22019-04-15 13:23:38 +0000503 Value *Z;
504 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))),
505 m_Value(Z)))) {
506 // Sink division: (X / Y) * Z --> (X * Z) / Y
507 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
508 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
509 }
510
Sanjay Patel81b3b102018-04-03 22:19:19 +0000511 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
512 // nnan disallows the possibility of returning a number if both operands are
513 // negative (in that case, we should return NaN).
514 if (I.hasNoNaNs() &&
515 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
516 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
517 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
Neil Henning57f5d0a2018-10-08 10:32:33 +0000518 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
Sanjay Patel81b3b102018-04-03 22:19:19 +0000519 return replaceInstUsesWith(I, Sqrt);
Sanjay Patel4fd4fd62018-03-26 15:03:57 +0000520 }
Sanjay Patel81b3b102018-04-03 22:19:19 +0000521
Sanjay Patel773e04c2019-04-08 21:23:50 +0000522 // Like the similar transform in instsimplify, this requires 'nsz' because
523 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
524 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
525 Op0->hasNUses(2)) {
526 // Peek through fdiv to find squaring of square root:
527 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
528 if (match(Op0, m_FDiv(m_Value(X),
529 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
530 Value *XX = Builder.CreateFMulFMF(X, X, &I);
531 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
532 }
533 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
534 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)),
535 m_Value(X)))) {
536 Value *XX = Builder.CreateFMulFMF(X, X, &I);
537 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
538 }
539 }
540
Dmitry Venikov88176582019-01-31 06:28:10 +0000541 // exp(X) * exp(Y) -> exp(X + Y)
542 // Match as long as at least one of exp has only one use.
543 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
544 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) &&
545 (Op0->hasOneUse() || Op1->hasOneUse())) {
546 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
547 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
548 return replaceInstUsesWith(I, Exp);
549 }
550
551 // exp2(X) * exp2(Y) -> exp2(X + Y)
552 // Match as long as at least one of exp2 has only one use.
553 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
554 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) &&
555 (Op0->hasOneUse() || Op1->hasOneUse())) {
556 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
557 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
558 return replaceInstUsesWith(I, Exp2);
559 }
560
Sanjay Patel81b3b102018-04-03 22:19:19 +0000561 // (X*Y) * X => (X*X) * Y where Y != X
562 // The purpose is two-fold:
563 // 1) to form a power expression (of X).
564 // 2) potentially shorten the critical path: After transformation, the
565 // latency of the instruction Y is amortized by the expression of X*X,
566 // and therefore Y is in a "less critical" position compared to what it
567 // was before the transformation.
568 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
569 Op1 != Y) {
570 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
571 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
572 }
573 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
574 Op0 != Y) {
575 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
576 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000577 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000578 }
579
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000580 // log2(X * 0.5) * Y = log2(X) * Y - Y
581 if (I.isFast()) {
582 IntrinsicInst *Log2 = nullptr;
583 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
584 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
585 Log2 = cast<IntrinsicInst>(Op0);
586 Y = Op1;
Pedro Artigasd8795042012-11-30 19:09:41 +0000587 }
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000588 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
589 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
590 Log2 = cast<IntrinsicInst>(Op1);
591 Y = Op0;
592 }
593 if (Log2) {
Nikita Popov893c6302020-02-16 10:15:53 +0100594 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000595 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
596 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
Pedro Artigasd8795042012-11-30 19:09:41 +0000597 }
598 }
599
Sanjay Patel70043b72018-07-13 01:18:07 +0000600 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000601}
602
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000603/// Fold a divide or remainder with a select instruction divisor when one of the
604/// select operands is zero. In that case, we can use the other select operand
605/// because div/rem by zero is undefined.
606bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
607 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
608 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000609 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000610
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000611 int NonNullOperand;
612 if (match(SI->getTrueValue(), m_Zero()))
613 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
614 NonNullOperand = 2;
615 else if (match(SI->getFalseValue(), m_Zero()))
616 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
617 NonNullOperand = 1;
618 else
619 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000620
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000621 // Change the div/rem to use 'Y' instead of the select.
Nikita Popov4b35c812020-03-30 22:00:16 +0200622 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000623
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000624 // Okay, we know we replace the operand of the div/rem with 'Y' with no
625 // problem. However, the select, or the condition of the select may have
626 // multiple uses. Based on our knowledge that the operand must be non-zero,
627 // propagate the known value for the select into other uses of it, and
628 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000629
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000630 // If the select and condition only have a single use, don't bother with this,
631 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000632 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000633 if (SI->use_empty() && SelectCond->hasOneUse())
634 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000635
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000636 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000637 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000638 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000639 while (BBI != BBFront) {
640 --BBI;
Serguei Katkovd894fb42018-06-04 02:52:36 +0000641 // If we found an instruction that we can't assume will return, so
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000642 // information from below it cannot be propagated above it.
Serguei Katkovd894fb42018-06-04 02:52:36 +0000643 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000644 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000646 // Replace uses of the select or its condition with the known values.
647 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
648 I != E; ++I) {
649 if (*I == SI) {
Nikita Popov4b35c812020-03-30 22:00:16 +0200650 replaceUse(*I, SI->getOperand(NonNullOperand));
Nikita Popove6c9ab42020-01-30 22:32:46 +0100651 Worklist.push(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 } else if (*I == SelectCond) {
Nikita Popov4b35c812020-03-30 22:00:16 +0200653 replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
654 : ConstantInt::getFalse(CondTy));
Nikita Popove6c9ab42020-01-30 22:32:46 +0100655 Worklist.push(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000656 }
657 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000658
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000659 // If we past the instruction, quit looking for it.
660 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000661 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000662 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000663 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000664
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000665 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000666 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000668
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000669 }
670 return true;
671}
672
Sanjay Patel1998cc62018-02-12 18:38:35 +0000673/// True if the multiply can not be expressed in an int this size.
674static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
675 bool IsSigned) {
676 bool Overflow;
677 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
678 return Overflow;
679}
680
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000681/// True if C1 is a multiple of C2. Quotient contains C1/C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000682static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
683 bool IsSigned) {
684 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
685
686 // Bail if we will divide by zero.
687 if (C2.isNullValue())
688 return false;
689
690 // Bail if we would divide INT_MIN by -1.
691 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
692 return false;
693
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000694 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000695 if (IsSigned)
696 APInt::sdivrem(C1, C2, Quotient, Remainder);
697 else
698 APInt::udivrem(C1, C2, Quotient, Remainder);
699
700 return Remainder.isMinValue();
701}
702
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000703/// This function implements the transforms common to both integer division
704/// instructions (udiv and sdiv). It is called by the visitors to those integer
705/// division instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000706/// Common integer divide transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000707Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000709 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000710 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000711
Chris Lattner7c99f192011-05-22 18:18:41 +0000712 // The RHS is known non-zero.
Nikita Popov1e363022020-03-29 17:08:04 +0200713 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
714 return replaceOperand(I, 1, V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000715
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000716 // Handle cases involving: [su]div X, (select Cond, Y, Z)
717 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000718 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000719 return &I;
720
Sanjay Patel1998cc62018-02-12 18:38:35 +0000721 const APInt *C2;
722 if (match(Op1, m_APInt(C2))) {
723 Value *X;
724 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000725
Sanjay Patel1998cc62018-02-12 18:38:35 +0000726 // (X / C1) / C2 -> X / (C1*C2)
727 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
728 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000729 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000730 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
731 return BinaryOperator::Create(I.getOpcode(), X,
732 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000733 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000734
735 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
736 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000737 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000738
739 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
740 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
741 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
742 ConstantInt::get(Ty, Quotient));
743 NewDiv->setIsExact(I.isExact());
744 return NewDiv;
745 }
746
747 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
748 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
749 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
750 ConstantInt::get(Ty, Quotient));
751 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
752 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
753 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
754 return Mul;
755 }
756 }
757
758 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
759 *C1 != C1->getBitWidth() - 1) ||
760 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000761 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000762 APInt C1Shifted = APInt::getOneBitSet(
763 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
764
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000765 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000766 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
767 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
768 ConstantInt::get(Ty, Quotient));
769 BO->setIsExact(I.isExact());
770 return BO;
771 }
772
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000773 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000774 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
775 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
776 ConstantInt::get(Ty, Quotient));
777 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
778 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
779 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
780 return Mul;
781 }
782 }
783
784 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000785 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
Sanjay Patel1998cc62018-02-12 18:38:35 +0000786 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000787 }
788
Craig Topper218a3592017-04-17 03:41:47 +0000789 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000790 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
791 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000792 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
793 // result is one, if Op1 is -1 then the result is minus one, otherwise
794 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000795 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000796 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
797 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000798 } else {
799 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
800 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000801 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000802 }
803 }
804
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000805 // See if we can fold away this div instruction.
806 if (SimplifyDemandedInstructionBits(I))
807 return &I;
808
Duncan Sands771e82a2011-01-28 16:51:11 +0000809 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000810 Value *X, *Z;
811 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
812 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
813 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000814 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000815
816 // (X << Y) / X -> 1 << Y
817 Value *Y;
818 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000819 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +0000820 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000821 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000822
Sanjay Patel510d6472018-02-11 17:20:32 +0000823 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
824 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
825 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
826 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
827 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Nikita Popov1e363022020-03-29 17:08:04 +0200828 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
829 replaceOperand(I, 1, Y);
Sanjay Patel510d6472018-02-11 17:20:32 +0000830 return &I;
831 }
832 }
833
Craig Topperf40110f2014-04-25 05:29:35 +0000834 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000835}
836
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000837static const unsigned MaxDepth = 6;
838
David Majnemer37f8f442013-07-04 21:17:49 +0000839namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000840
841using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
842 const BinaryOperator &I,
843 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +0000844
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000845/// Used to maintain state for visitUDivOperand().
David Majnemer37f8f442013-07-04 21:17:49 +0000846struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000847 /// Informs visitUDiv() how to fold this operand. This can be zero if this
848 /// action joins two actions together.
849 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +0000850
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000851 /// Which operand to fold.
852 Value *OperandToFold;
853
David Majnemer37f8f442013-07-04 21:17:49 +0000854 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000855 /// The instruction returned when FoldAction is invoked.
856 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +0000857
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000858 /// Stores the LHS action index if this action joins two actions together.
859 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +0000860 };
861
862 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000863 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000864 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
865 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
866};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000867
868} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +0000869
870// X udiv 2^C -> X >> C
871static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
872 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +0000873 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
874 if (!C1)
875 llvm_unreachable("Failed to constant fold udiv -> logbase2");
876 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000877 if (I.isExact())
878 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000879 return LShr;
880}
881
David Majnemer37f8f442013-07-04 21:17:49 +0000882// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000883// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +0000884static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
885 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000886 Value *ShiftLeft;
887 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
888 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +0000889
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000890 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000891 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000892 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000893 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000894 Constant *Log2Base = getLogBase2(N->getType(), CI);
895 if (!Log2Base)
896 llvm_unreachable("getLogBase2 should never fail here!");
897 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000898 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +0000899 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +0000900 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000901 if (I.isExact())
902 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000903 return LShr;
904}
905
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000906// Recursively visits the possible right hand operands of a udiv
David Majnemer37f8f442013-07-04 21:17:49 +0000907// instruction, seeing through select instructions, to determine if we can
908// replace the udiv with something simpler. If we find that an operand is not
909// able to simplify the udiv, we abort the entire transformation.
910static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
911 SmallVectorImpl<UDivFoldAction> &Actions,
912 unsigned Depth = 0) {
913 // Check to see if this is an unsigned division with an exact power of 2,
914 // if so, convert to a right shift.
915 if (match(Op1, m_Power2())) {
916 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
917 return Actions.size();
918 }
919
David Majnemer37f8f442013-07-04 21:17:49 +0000920 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
921 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
922 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
923 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
924 return Actions.size();
925 }
926
927 // The remaining tests are all recursive, so bail out if we hit the limit.
928 if (Depth++ == MaxDepth)
929 return 0;
930
931 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000932 if (size_t LHSIdx =
933 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
934 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
935 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000936 return Actions.size();
937 }
938
939 return 0;
940}
941
Sanjay Patelbb789382017-08-24 22:54:01 +0000942/// If we have zero-extended operands of an unsigned div or rem, we may be able
943/// to narrow the operation (sink the zext below the math).
944static Instruction *narrowUDivURem(BinaryOperator &I,
945 InstCombiner::BuilderTy &Builder) {
946 Instruction::BinaryOps Opcode = I.getOpcode();
947 Value *N = I.getOperand(0);
948 Value *D = I.getOperand(1);
949 Type *Ty = I.getType();
950 Value *X, *Y;
951 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
952 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
953 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
954 // urem (zext X), (zext Y) --> zext (urem X, Y)
955 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
956 return new ZExtInst(NarrowOp, Ty);
957 }
958
959 Constant *C;
960 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
961 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
962 // If the constant is the same in the smaller type, use the narrow version.
963 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
964 if (ConstantExpr::getZExt(TruncC, Ty) != C)
965 return nullptr;
966
967 // udiv (zext X), C --> zext (udiv X, C')
968 // urem (zext X), C --> zext (urem X, C')
969 // udiv C, (zext X) --> zext (udiv C', X)
970 // urem C, (zext X) --> zext (urem C', X)
971 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
972 : Builder.CreateBinOp(Opcode, TruncC, X);
973 return new ZExtInst(NarrowOp, Ty);
974 }
975
976 return nullptr;
977}
978
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000979Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000980 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
981 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000982 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +0000983
Sanjay Patel79dceb22018-10-03 15:20:58 +0000984 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000985 return X;
986
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000987 // Handle the integer div common cases
988 if (Instruction *Common = commonIDivTransforms(I))
989 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000990
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel38a86d32018-06-25 22:50:26 +0000992 Value *X;
993 const APInt *C1, *C2;
994 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
995 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
996 bool Overflow;
997 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
998 if (!Overflow) {
999 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1000 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1001 X, ConstantInt::get(X->getType(), C2ShlC1));
1002 if (IsExact)
1003 BO->setIsExact();
1004 return BO;
David Majnemera2521382014-10-13 21:48:30 +00001005 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001006 }
1007
Sanjay Patel38a86d32018-06-25 22:50:26 +00001008 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1009 // TODO: Could use isKnownNegative() to handle non-constant values.
Sanjay Patel7c45deb2018-06-26 12:41:15 +00001010 Type *Ty = I.getType();
Sanjay Patel38a86d32018-06-25 22:50:26 +00001011 if (match(Op1, m_Negative())) {
1012 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
Sanjay Patel7c45deb2018-06-26 12:41:15 +00001013 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1014 }
1015 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1016 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1017 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1018 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
Sanjay Patel38a86d32018-06-25 22:50:26 +00001019 }
1020
Sanjay Patelbb789382017-08-24 22:54:01 +00001021 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1022 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001023
Sanjay Patel6d6eab62018-07-26 19:22:41 +00001024 // If the udiv operands are non-overflowing multiplies with a common operand,
1025 // then eliminate the common factor:
1026 // (A * B) / (A * X) --> B / X (and commuted variants)
1027 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1028 // TODO: If -reassociation handled this generally, we could remove this.
1029 Value *A, *B;
1030 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1031 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1032 match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1033 return BinaryOperator::CreateUDiv(B, X);
1034 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1035 match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1036 return BinaryOperator::CreateUDiv(A, X);
1037 }
1038
David Majnemer37f8f442013-07-04 21:17:49 +00001039 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1040 SmallVector<UDivFoldAction, 6> UDivActions;
1041 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1042 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1043 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1044 Value *ActionOp1 = UDivActions[i].OperandToFold;
1045 Instruction *Inst;
1046 if (Action)
1047 Inst = Action(Op0, ActionOp1, I, *this);
1048 else {
1049 // This action joins two actions together. The RHS of this action is
1050 // simply the last action we processed, we saved the LHS action index in
1051 // the joining action.
1052 size_t SelectRHSIdx = i - 1;
1053 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1054 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1055 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1056 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1057 SelectLHS, SelectRHS);
1058 }
1059
1060 // If this is the last action to process, return it to the InstCombiner.
1061 // Otherwise, we insert it before the UDiv and record it so that we may
1062 // use it as part of a joining action (i.e., a SelectInst).
1063 if (e - i != 1) {
1064 Inst->insertBefore(&I);
1065 UDivActions[i].FoldResult = Inst;
1066 } else
1067 return Inst;
1068 }
1069
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001071}
1072
1073Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001074 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1075 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001076 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001077
Sanjay Patel79dceb22018-10-03 15:20:58 +00001078 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001079 return X;
1080
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001081 // Handle the integer div common cases
1082 if (Instruction *Common = commonIDivTransforms(I))
1083 return Common;
1084
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel6a96d902018-06-25 21:39:41 +00001086 Value *X;
1087 // sdiv Op0, -1 --> -Op0
1088 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1089 if (match(Op1, m_AllOnes()) ||
1090 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1091 return BinaryOperator::CreateNeg(Op0);
1092
Sanjay Patel49d9d172019-04-09 15:13:03 +00001093 // X / INT_MIN --> X == INT_MIN
1094 if (match(Op1, m_SignMask()))
1095 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1096
Sanjay Patelc6ada532016-06-27 17:25:57 +00001097 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001098 if (match(Op1, m_APInt(Op1C))) {
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001099 // sdiv exact X, C --> ashr exact X, log2(C)
1100 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1101 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1102 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1103 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001104
1105 // If the dividend is sign-extended and the constant divisor is small enough
1106 // to fit in the source type, shrink the division to the narrower type:
1107 // (sext X) sdiv C --> sext (X sdiv C)
1108 Value *Op0Src;
1109 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1110 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1111
1112 // In the general case, we need to make sure that the dividend is not the
1113 // minimum signed value because dividing that by -1 is UB. But here, we
1114 // know that the -1 divisor case is already handled above.
1115
1116 Constant *NarrowDivisor =
1117 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001118 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001119 return new SExtInst(NarrowOp, Op0->getType());
1120 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001121
Sanjay Patel49d9d172019-04-09 15:13:03 +00001122 // -X / C --> X / -C (if the negation doesn't overflow).
1123 // TODO: This could be enhanced to handle arbitrary vector constants by
1124 // checking if all elements are not the min-signed-val.
1125 if (!Op1C->isMinSignedValue() &&
1126 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1127 Constant *NegC = ConstantInt::get(I.getType(), -(*Op1C));
1128 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
David Majnemerfa4699e2014-11-22 20:00:34 +00001129 BO->setIsExact(I.isExact());
1130 return BO;
1131 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001132 }
1133
Chen Zheng5e13ff12019-04-10 06:52:09 +00001134 // -X / Y --> -(X / Y)
1135 Value *Y;
1136 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1137 return BinaryOperator::CreateNSWNeg(
1138 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1139
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001140 // If the sign bits of both operands are zero (i.e. we can prove they are
1141 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001142 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001143 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1144 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1145 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1146 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1147 BO->setIsExact(I.isExact());
1148 return BO;
1149 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001150
Craig Topperd4039f72017-05-25 21:51:12 +00001151 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001152 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1153 // Safe because the only negative value (1 << Y) can take on is
1154 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1155 // the sign bit set.
1156 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1157 BO->setIsExact(I.isExact());
1158 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001159 }
1160 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001161
Craig Topperf40110f2014-04-25 05:29:35 +00001162 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001163}
1164
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001165/// Remove negation and try to convert division into multiplication.
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001166static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1167 Constant *C;
1168 if (!match(I.getOperand(1), m_Constant(C)))
Craig Topperf40110f2014-04-25 05:29:35 +00001169 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001170
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001171 // -X / C --> X / -C
1172 Value *X;
1173 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001174 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001175
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001176 // If the constant divisor has an exact inverse, this is always safe. If not,
1177 // then we can still create a reciprocal if fast-math-flags allow it and the
1178 // constant is a regular number (not zero, infinite, or denormal).
1179 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
Craig Topperf40110f2014-04-25 05:29:35 +00001180 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001181
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001182 // Disallow denormal constants because we don't know what would happen
1183 // on all targets.
1184 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1185 // denorms are flushed?
1186 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1187 if (!RecipC->isNormalFP())
1188 return nullptr;
1189
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001190 // X / C --> X * (1 / C)
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001191 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001192}
1193
Sanjay Patel6f716a72018-02-21 00:01:45 +00001194/// Remove negation and try to reassociate constant math.
Sanjay Patele4129542018-02-19 21:17:58 +00001195static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001196 Constant *C;
1197 if (!match(I.getOperand(0), m_Constant(C)))
Sanjay Patele4129542018-02-19 21:17:58 +00001198 return nullptr;
1199
Sanjay Patel6f716a72018-02-21 00:01:45 +00001200 // C / -X --> -C / X
Sanjay Patele4129542018-02-19 21:17:58 +00001201 Value *X;
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001202 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1203 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
Sanjay Patel6f716a72018-02-21 00:01:45 +00001204
1205 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1206 return nullptr;
1207
1208 // Try to reassociate C / X expressions where X includes another constant.
Sanjay Patele4129542018-02-19 21:17:58 +00001209 Constant *C2, *NewC = nullptr;
1210 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001211 // C / (X * C2) --> (C / C2) / X
1212 NewC = ConstantExpr::getFDiv(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001213 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001214 // C / (X / C2) --> (C * C2) / X
1215 NewC = ConstantExpr::getFMul(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001216 }
1217 // Disallow denormal constants because we don't know what would happen
1218 // on all targets.
1219 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1220 // denorms are flushed?
1221 if (!NewC || !NewC->isNormalFP())
1222 return nullptr;
1223
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001224 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
Sanjay Patele4129542018-02-19 21:17:58 +00001225}
1226
Frits van Bommel2a559512011-01-29 17:50:27 +00001227Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001228 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1229 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001230 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001231 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001232
Sanjay Patel79dceb22018-10-03 15:20:58 +00001233 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001234 return X;
1235
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001236 if (Instruction *R = foldFDivConstantDivisor(I))
1237 return R;
Sanjay Patel28165602018-02-19 23:09:03 +00001238
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001239 if (Instruction *R = foldFDivConstantDividend(I))
1240 return R;
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001241
Sanjay Patel7b201bf2020-06-20 11:47:00 -04001242 if (Instruction *R = foldFPSignBitOps(I))
Sanjay Pateld84cdb82020-06-20 10:20:21 -04001243 return R;
1244
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Stephen Lina9b57f62013-07-20 07:13:13 +00001246 if (isa<Constant>(Op0))
1247 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1248 if (Instruction *R = FoldOpIntoSelect(I, SI))
1249 return R;
1250
Sanjay Patel29b98ae2018-02-20 17:14:53 +00001251 if (isa<Constant>(Op1))
Stephen Lina9b57f62013-07-20 07:13:13 +00001252 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1253 if (Instruction *R = FoldOpIntoSelect(I, SI))
1254 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001255
Sanjay Patel31a90462018-02-26 16:02:45 +00001256 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001257 Value *X, *Y;
Sanjay Patel91bb7752018-02-16 17:52:32 +00001258 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1259 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1260 // (X / Y) / Z => X / (Y * Z)
Sanjay Patel31a90462018-02-26 16:02:45 +00001261 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001262 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001263 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001264 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1265 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1266 // Z / (X / Y) => (Y * Z) / X
Sanjay Patel31a90462018-02-26 16:02:45 +00001267 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001268 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001269 }
@raghesh (Raghesh Aloor)6c04ef42020-01-09 10:52:39 -05001270 // Z / (1.0 / Y) => (Y * Z)
1271 //
1272 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1273 // m_OneUse check is avoided because even in the case of the multiple uses
1274 // for 1.0/Y, the number of instructions remain the same and a division is
1275 // replaced by a multiplication.
1276 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1277 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001278 }
1279
Sanjay Patel339b4d32018-02-15 15:07:12 +00001280 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001281 // sin(X) / cos(X) -> tan(X)
1282 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1283 Value *X;
1284 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1285 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1286 bool IsCot =
1287 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1288 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001289
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001290 if ((IsTan || IsCot) &&
1291 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001292 IRBuilder<> B(&I);
1293 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1294 B.setFastMathFlags(I.getFastMathFlags());
Craig Topperc1892ec2019-01-31 17:23:29 +00001295 AttributeList Attrs =
1296 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
Mikael Holmene3605d02018-10-18 06:27:53 +00001297 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1298 LibFunc_tanl, B, Attrs);
Sanjay Patel65da14d2018-02-16 16:13:20 +00001299 if (IsCot)
1300 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1301 return replaceInstUsesWith(I, Res);
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001302 }
1303 }
1304
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001305 // X / (X * Y) --> 1.0 / Y
1306 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1307 // We can ignore the possibility that X is infinity because INF/INF is NaN.
Sanjay Pateld84cdb82020-06-20 10:20:21 -04001308 Value *X, *Y;
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001309 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1310 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
Nikita Popov1e363022020-03-29 17:08:04 +02001311 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1312 replaceOperand(I, 1, Y);
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001313 return &I;
1314 }
1315
David Bolvansky20d37fa2019-08-12 13:43:35 +00001316 // X / fabs(X) -> copysign(1.0, X)
1317 // fabs(X) / X -> copysign(1.0, X)
1318 if (I.hasNoNaNs() && I.hasNoInfs() &&
1319 (match(&I,
1320 m_FDiv(m_Value(X), m_Intrinsic<Intrinsic::fabs>(m_Deferred(X)))) ||
1321 match(&I, m_FDiv(m_Intrinsic<Intrinsic::fabs>(m_Value(X)),
1322 m_Deferred(X))))) {
1323 Value *V = Builder.CreateBinaryIntrinsic(
1324 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1325 return replaceInstUsesWith(I, V);
1326 }
Craig Topperf40110f2014-04-25 05:29:35 +00001327 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001328}
1329
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001330/// This function implements the transforms common to both integer remainder
1331/// instructions (urem and srem). It is called by the visitors to those integer
1332/// remainder instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00001333/// Common integer remainder transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001334Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1336
Chris Lattner7c99f192011-05-22 18:18:41 +00001337 // The RHS is known non-zero.
Nikita Popov1e363022020-03-29 17:08:04 +02001338 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1339 return replaceOperand(I, 1, V);
Chris Lattner7c99f192011-05-22 18:18:41 +00001340
Duncan Sandsa3e36992011-05-02 16:27:02 +00001341 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001342 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001343 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001344
Benjamin Kramer72196f32014-01-19 15:24:22 +00001345 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001346 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1347 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1348 if (Instruction *R = FoldOpIntoSelect(I, SI))
1349 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001350 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001351 const APInt *Op1Int;
1352 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1353 (I.getOpcode() == Instruction::URem ||
1354 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001355 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001356 // predecessor blocks, so do this only if we know the srem or urem
1357 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001358 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001359 return NV;
1360 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001361 }
1362
1363 // See if we can fold away this rem instruction.
1364 if (SimplifyDemandedInstructionBits(I))
1365 return &I;
1366 }
1367 }
1368
Craig Topperf40110f2014-04-25 05:29:35 +00001369 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001370}
1371
1372Instruction *InstCombiner::visitURem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001373 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1374 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001375 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001376
Sanjay Patel79dceb22018-10-03 15:20:58 +00001377 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001378 return X;
1379
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001380 if (Instruction *common = commonIRemTransforms(I))
1381 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001382
Sanjay Patelbb789382017-08-24 22:54:01 +00001383 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1384 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001385
David Majnemer470b0772013-05-11 09:01:28 +00001386 // X urem Y -> X and Y-1, where Y is a power of 2,
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001387 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001388 Type *Ty = I.getType();
Craig Topperd4039f72017-05-25 21:51:12 +00001389 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Roman Lebedevbe612ea2019-07-30 15:28:22 +00001390 // This may increase instruction count, we don't enforce that Y is a
1391 // constant.
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001392 Constant *N1 = Constant::getAllOnesValue(Ty);
Craig Topperbb4069e2017-07-07 23:16:26 +00001393 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001394 return BinaryOperator::CreateAnd(Op0, Add);
1395 }
1396
Nick Lewycky7459be62013-07-13 01:16:47 +00001397 // 1 urem X -> zext(X != 1)
Sanjay Patelaf4e5992019-12-02 12:10:05 -05001398 if (match(Op0, m_One())) {
1399 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1400 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1401 }
Nick Lewycky7459be62013-07-13 01:16:47 +00001402
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001403 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001404 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001405 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1406 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001407 return SelectInst::Create(Cmp, Op0, Sub);
1408 }
1409
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001410 // If the divisor is a sext of a boolean, then the divisor must be max
1411 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1412 // max unsigned value. In that case, the remainder is 0:
1413 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1414 Value *X;
1415 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1416 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1417 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1418 }
1419
Craig Topperf40110f2014-04-25 05:29:35 +00001420 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001421}
1422
1423Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001424 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1425 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001426 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001427
Sanjay Patel79dceb22018-10-03 15:20:58 +00001428 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001429 return X;
1430
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001431 // Handle the integer rem common cases
1432 if (Instruction *Common = commonIRemTransforms(I))
1433 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001434
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemerdb077302014-10-13 22:37:51 +00001436 {
1437 const APInt *Y;
1438 // X % -Y -> X % Y
Nikita Popov878cb382020-01-31 22:23:33 +01001439 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1440 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
David Majnemerdb077302014-10-13 22:37:51 +00001441 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001442
Chen Zheng87dd0e02019-04-13 09:21:22 +00001443 // -X srem Y --> -(X srem Y)
1444 Value *X, *Y;
1445 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1446 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1447
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001448 // If the sign bits of both operands are zero (i.e. we can prove they are
1449 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001450 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001451 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1452 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1453 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1454 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001455 }
1456
1457 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001458 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1459 Constant *C = cast<Constant>(Op1);
Christopher Tetreault155740c2020-04-08 10:42:22 -07001460 unsigned VWidth = cast<VectorType>(C->getType())->getNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001461
1462 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001463 bool hasMissing = false;
1464 for (unsigned i = 0; i != VWidth; ++i) {
1465 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001466 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001467 hasMissing = true;
1468 break;
1469 }
1470
1471 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001472 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001473 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001474 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001475
Chris Lattner0256be92012-01-27 03:08:05 +00001476 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001477 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001478 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001479 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001481 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001482 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001483 }
1484 }
1485
1486 Constant *NewRHSV = ConstantVector::get(Elts);
Nikita Popov878cb382020-01-31 22:23:33 +01001487 if (NewRHSV != C) // Don't loop on -MININT
1488 return replaceOperand(I, 1, NewRHSV);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001489 }
1490 }
1491
Craig Topperf40110f2014-04-25 05:29:35 +00001492 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001493}
1494
1495Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001496 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1497 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001498 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001499 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001500
Sanjay Patel79dceb22018-10-03 15:20:58 +00001501 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001502 return X;
1503
Craig Topperf40110f2014-04-25 05:29:35 +00001504 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001505}