blob: d6adbec02ac1d126c02104fdbb0a31e1130b3b71 [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/SmallVector.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000019#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000020#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000029#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000030#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/Support/KnownBits.h"
35#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Dmitry Venikove5fbf592018-01-11 06:33:00 +000036#include "llvm/Transforms/Utils/BuildLibCalls.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000037#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41
Chris Lattnerdc054bf2010-01-05 06:09:35 +000042using namespace llvm;
43using namespace PatternMatch;
44
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "instcombine"
46
Sanjay Patel6eccf482015-09-09 15:24:36 +000047/// The specific integer value is used in a context where it is known to be
48/// non-zero. If this allows us to simplify the computation, do so and return
49/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000050static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000051 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000052 // If V has multiple uses, then we would have to do more analysis to determine
53 // if this is safe. For example, the use could be in dynamically unreached
54 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000055 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000056
Chris Lattner388cb8a2011-05-23 00:32:19 +000057 bool MadeChange = false;
58
Chris Lattner7c99f192011-05-22 18:18:41 +000059 // ((1 << A) >>u B) --> (1 << (A-B))
60 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000061 Value *A = nullptr, *B = nullptr, *One = nullptr;
62 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
63 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000064 A = IC.Builder.CreateSub(A, B);
65 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000066 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Chris Lattner388cb8a2011-05-23 00:32:19 +000068 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
69 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000070 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
71 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000072 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000073 // We know that this is an exact/nuw shift and that the input is a
74 // non-zero context as well.
75 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
76 I->setOperand(0, V2);
77 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000078 }
79
Sanjay Patela8ef4a52016-05-22 17:08:52 +000080 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
81 I->setIsExact();
82 MadeChange = true;
83 }
84
85 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
86 I->setHasNoUnsignedWrap();
87 MadeChange = true;
88 }
89 }
90
Chris Lattner162dfc32011-05-22 18:26:48 +000091 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000092 // If V is a phi node, we can call this on each of its operands.
93 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Craig Topperf40110f2014-04-25 05:29:35 +000095 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000096}
97
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000098/// A helper routine of InstCombiner::visitMul().
Rafael Espindola65281bf2013-05-31 14:27:15 +000099///
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000100/// If C is a scalar/vector of known powers of 2, then this function returns
101/// a new scalar/vector obtained from logBase2 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
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000108 if (!Ty->isVectorTy())
109 return nullptr;
110
111 SmallVector<Constant *, 4> Elts;
112 for (unsigned I = 0, E = Ty->getVectorNumElements(); I != E; ++I) {
113 Constant *Elt = C->getAggregateElement(I);
114 if (!Elt)
115 return nullptr;
116 if (isa<UndefValue>(Elt)) {
117 Elts.push_back(UndefValue::get(Ty->getScalarType()));
118 continue;
119 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000121 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000122 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000123 }
124
125 return ConstantVector::get(Elts);
126}
127
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000128Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000129 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
130 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000131 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000132
Sanjay Patel70043b72018-07-13 01:18:07 +0000133 if (SimplifyAssociativeOrCommutative(I))
134 return &I;
135
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000136 if (Instruction *X = foldShuffledBinop(I))
137 return X;
138
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000139 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000140 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000141
David Majnemer027bc802014-11-22 04:52:38 +0000142 // X * -1 == 0 - X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemer027bc802014-11-22 04:52:38 +0000144 if (match(Op1, m_AllOnes())) {
145 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
146 if (I.hasNoSignedWrap())
147 BO->setHasNoSignedWrap();
148 return BO;
149 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000150
Rafael Espindola65281bf2013-05-31 14:27:15 +0000151 // Also allow combining multiply instructions on vectors.
152 {
153 Value *NewOp;
154 Constant *C1, *C2;
155 const APInt *IVal;
156 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
157 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000158 match(C1, m_APInt(IVal))) {
159 // ((X << C2)*C1) == (X * (C1 << C2))
160 Constant *Shl = ConstantExpr::getShl(C1, C2);
161 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
162 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
163 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
164 BO->setHasNoUnsignedWrap();
165 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
166 Shl->isNotMinSignedValue())
167 BO->setHasNoSignedWrap();
168 return BO;
169 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000170
Rafael Espindola65281bf2013-05-31 14:27:15 +0000171 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000172 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
173 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
David Majnemer45951a62015-04-18 04:41:30 +0000174 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000175 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000176
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000177 if (I.hasNoUnsignedWrap())
178 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000179 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000180 const APInt *V;
181 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000182 Shl->setHasNoSignedWrap();
183 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000184
Rafael Espindola65281bf2013-05-31 14:27:15 +0000185 return Shl;
186 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000187 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Rafael Espindola65281bf2013-05-31 14:27:15 +0000190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000191 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
192 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
193 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000194 {
195 const APInt & Val = CI->getValue();
196 const APInt &PosVal = Val.abs();
197 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000199 if (Op0->hasOneUse()) {
200 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000201 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000202 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000203 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000204 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000205 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000206 if (Sub)
207 return
208 BinaryOperator::CreateMul(Sub,
209 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000210 }
211 }
212 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000213 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000214
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000215 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
216 return FoldedMul;
217
Chris Lattner6b657ae2011-02-10 05:36:31 +0000218 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000219 if (isa<Constant>(Op1)) {
Benjamin Kramer72196f32014-01-19 15:24:22 +0000220 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000221 Value *X;
222 Constant *C1;
223 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
224 Value *Mul = Builder.CreateMul(C1, Op1);
225 // Only go forward with the transform if C1*CI simplifies to a tidier
226 // constant.
227 if (!match(Mul, m_Mul(m_Value(), m_Value())))
228 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000229 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000230 }
231
Sanjay Patel604cb9e2018-02-14 16:50:55 +0000232 // -X * C --> X * -C
233 Value *X, *Y;
234 Constant *Op1C;
235 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
236 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
237
238 // -X * -Y --> X * Y
239 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
240 auto *NewMul = BinaryOperator::CreateMul(X, Y);
241 if (I.hasNoSignedWrap() &&
242 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
243 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
244 NewMul->setHasNoSignedWrap();
245 return NewMul;
David Majnemer8279a7502014-11-22 07:25:19 +0000246 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000247
248 // (X / Y) * Y = X - (X % Y)
249 // (X / Y) * -Y = (X % Y) - X
250 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000251 Value *Y = Op1;
252 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
253 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
254 Div->getOpcode() != Instruction::SDiv)) {
255 Y = Op0;
256 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000257 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000258 Value *Neg = dyn_castNegVal(Y);
259 if (Div && Div->hasOneUse() &&
260 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
261 (Div->getOpcode() == Instruction::UDiv ||
262 Div->getOpcode() == Instruction::SDiv)) {
263 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000264
Chris Lattner35315d02011-02-06 21:44:57 +0000265 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000266 if (Div->isExact()) {
267 if (DivOp1 == Y)
268 return replaceInstUsesWith(I, X);
269 return BinaryOperator::CreateNeg(X);
270 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000271
Sanjay Patela0a56822017-03-14 17:27:27 +0000272 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
273 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000274 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000275 if (DivOp1 == Y)
276 return BinaryOperator::CreateSub(X, Rem);
277 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000278 }
279 }
280
281 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000282 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000283 return BinaryOperator::CreateAnd(Op0, Op1);
284
285 // X*(1 << Y) --> X << Y
286 // (1 << Y)*X --> X << Y
287 {
288 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000289 BinaryOperator *BO = nullptr;
290 bool ShlNSW = false;
291 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
292 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000293 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000294 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000295 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000296 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000297 }
298 if (BO) {
299 if (I.hasNoUnsignedWrap())
300 BO->setHasNoUnsignedWrap();
301 if (I.hasNoSignedWrap() && ShlNSW)
302 BO->setHasNoSignedWrap();
303 return BO;
304 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000305 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000306
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000307 // (bool X) * Y --> X ? Y : 0
Sanjay Patel7558d862018-02-13 22:24:37 +0000308 // Y * (bool X) --> X ? Y : 0
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000309 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
310 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000311 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
312 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
313
Sanjay Patel7558d862018-02-13 22:24:37 +0000314 // (lshr X, 31) * Y --> (ashr X, 31) & Y
315 // Y * (lshr X, 31) --> (ashr X, 31) & Y
316 // TODO: We are not checking one-use because the elimination of the multiply
317 // is better for analysis?
318 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
319 // more similar to what we're doing above.
320 const APInt *C;
321 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
322 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
323 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
324 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325
David Majnemera1cfd7c2016-12-30 00:28:58 +0000326 // Check for (mul (sext x), y), see if we can merge this into an
327 // integer mul followed by a sext.
328 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
329 // (mul (sext x), cst) --> (sext (mul x, cst'))
330 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
331 if (Op0Conv->hasOneUse()) {
332 Constant *CI =
333 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
334 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000335 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000336 // Insert the new, smaller mul.
337 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000338 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000339 return new SExtInst(NewMul, I.getType());
340 }
341 }
342 }
343
344 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
345 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
346 // Only do this if x/y have the same type, if at last one of them has a
347 // single use (so we don't increase the number of sexts), and if the
348 // integer mul will not overflow.
349 if (Op0Conv->getOperand(0)->getType() ==
350 Op1Conv->getOperand(0)->getType() &&
351 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000352 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000353 Op1Conv->getOperand(0), I)) {
354 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000355 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000356 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
357 return new SExtInst(NewMul, I.getType());
358 }
359 }
360 }
361
362 // Check for (mul (zext x), y), see if we can merge this into an
363 // integer mul followed by a zext.
364 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
365 // (mul (zext x), cst) --> (zext (mul x, cst'))
366 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
367 if (Op0Conv->hasOneUse()) {
368 Constant *CI =
369 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
370 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000371 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000372 // Insert the new, smaller mul.
373 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000374 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000375 return new ZExtInst(NewMul, I.getType());
376 }
377 }
378 }
379
380 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
381 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
382 // Only do this if x/y have the same type, if at last one of them has a
383 // single use (so we don't increase the number of zexts), and if the
384 // integer mul will not overflow.
385 if (Op0Conv->getOperand(0)->getType() ==
386 Op1Conv->getOperand(0)->getType() &&
387 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000388 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
389 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000390 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000391 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000392 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
393 return new ZExtInst(NewMul, I.getType());
394 }
395 }
396 }
397
Sanjay Patel70043b72018-07-13 01:18:07 +0000398 bool Changed = false;
Craig Topper2b1fc322017-05-22 06:25:31 +0000399 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000400 Changed = true;
401 I.setHasNoSignedWrap(true);
402 }
403
Craig Topperbb973722017-05-15 02:44:08 +0000404 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000405 Changed = true;
406 I.setHasNoUnsignedWrap(true);
407 }
408
Craig Topperf40110f2014-04-25 05:29:35 +0000409 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000410}
411
412Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000413 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
414 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +0000415 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000416 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000417
Sanjay Patel70043b72018-07-13 01:18:07 +0000418 if (SimplifyAssociativeOrCommutative(I))
419 return &I;
420
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000421 if (Instruction *X = foldShuffledBinop(I))
422 return X;
423
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000424 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
425 return FoldedMul;
426
Sanjay Patele29375d2018-03-02 23:06:45 +0000427 // X * -1.0 --> -X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patele29375d2018-03-02 23:06:45 +0000429 if (match(Op1, m_SpecificFP(-1.0)))
430 return BinaryOperator::CreateFNegFMF(Op0, &I);
Sanjay Patel6b9c7a92018-02-23 17:14:28 +0000431
Sanjay Patele29375d2018-03-02 23:06:45 +0000432 // -X * -Y --> X * Y
433 Value *X, *Y;
434 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
435 return BinaryOperator::CreateFMulFMF(X, Y, &I);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000436
Sanjay Patele29375d2018-03-02 23:06:45 +0000437 // -X * C --> X * -C
438 Constant *C;
439 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
440 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000441
Sanjay Patele29375d2018-03-02 23:06:45 +0000442 // Sink negation: -X * Y --> -(X * Y)
443 if (match(Op0, m_OneUse(m_FNeg(m_Value(X)))))
444 return BinaryOperator::CreateFNegFMF(Builder.CreateFMulFMF(X, Op1, &I), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000445
Sanjay Patele29375d2018-03-02 23:06:45 +0000446 // Sink negation: Y * -X --> -(X * Y)
447 if (match(Op1, m_OneUse(m_FNeg(m_Value(X)))))
448 return BinaryOperator::CreateFNegFMF(Builder.CreateFMulFMF(X, Op0, &I), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000449
Sanjay Patele29375d2018-03-02 23:06:45 +0000450 // fabs(X) * fabs(X) -> X * X
451 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
452 return BinaryOperator::CreateFMulFMF(X, X, &I);
453
454 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
455 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
456 return replaceInstUsesWith(I, V);
457
Sanjay Patel81b3b102018-04-03 22:19:19 +0000458 if (I.hasAllowReassoc()) {
459 // Reassociate constant RHS with another constant to form constant
460 // expression.
461 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
462 Constant *C1;
463 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
464 // (C1 / X) * C --> (C * C1) / X
465 Constant *CC1 = ConstantExpr::getFMul(C, C1);
466 if (CC1->isNormalFP())
467 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
468 }
469 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
470 // (X / C1) * C --> X * (C / C1)
471 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
472 if (CDivC1->isNormalFP())
473 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
Sanjay Patel204edec2018-03-13 14:46:32 +0000474
Sanjay Patel81b3b102018-04-03 22:19:19 +0000475 // If the constant was a denormal, try reassociating differently.
476 // (X / C1) * C --> X / (C1 / C)
477 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
478 if (Op0->hasOneUse() && C1DivC->isNormalFP())
479 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
480 }
481
482 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
483 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
484 // further folds and (X * C) + C2 is 'fma'.
485 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
486 // (X + C1) * C --> (X * C) + (C * C1)
487 Constant *CC1 = ConstantExpr::getFMul(C, C1);
488 Value *XC = Builder.CreateFMulFMF(X, C, &I);
489 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
490 }
491 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
492 // (C1 - X) * C --> (C * C1) - (X * C)
493 Constant *CC1 = ConstantExpr::getFMul(C, C1);
494 Value *XC = Builder.CreateFMulFMF(X, C, &I);
495 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
496 }
Sanjay Patel204edec2018-03-13 14:46:32 +0000497 }
498
Sanjay Patel81b3b102018-04-03 22:19:19 +0000499 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
500 // nnan disallows the possibility of returning a number if both operands are
501 // negative (in that case, we should return NaN).
502 if (I.hasNoNaNs() &&
503 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
504 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
505 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
506 Value *Sqrt = Builder.CreateIntrinsic(Intrinsic::sqrt, { XY }, &I);
507 return replaceInstUsesWith(I, Sqrt);
Sanjay Patel4fd4fd62018-03-26 15:03:57 +0000508 }
Sanjay Patel81b3b102018-04-03 22:19:19 +0000509
510 // (X*Y) * X => (X*X) * Y where Y != X
511 // The purpose is two-fold:
512 // 1) to form a power expression (of X).
513 // 2) potentially shorten the critical path: After transformation, the
514 // latency of the instruction Y is amortized by the expression of X*X,
515 // and therefore Y is in a "less critical" position compared to what it
516 // was before the transformation.
517 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
518 Op1 != Y) {
519 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
520 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
521 }
522 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
523 Op0 != Y) {
524 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
525 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000526 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000527 }
528
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000529 // log2(X * 0.5) * Y = log2(X) * Y - Y
530 if (I.isFast()) {
531 IntrinsicInst *Log2 = nullptr;
532 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
533 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
534 Log2 = cast<IntrinsicInst>(Op0);
535 Y = Op1;
Pedro Artigasd8795042012-11-30 19:09:41 +0000536 }
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000537 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
538 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
539 Log2 = cast<IntrinsicInst>(Op1);
540 Y = Op0;
541 }
542 if (Log2) {
543 Log2->setArgOperand(0, X);
544 Log2->copyFastMathFlags(&I);
545 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
546 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
Pedro Artigasd8795042012-11-30 19:09:41 +0000547 }
548 }
549
Sanjay Patel70043b72018-07-13 01:18:07 +0000550 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000551}
552
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000553/// Fold a divide or remainder with a select instruction divisor when one of the
554/// select operands is zero. In that case, we can use the other select operand
555/// because div/rem by zero is undefined.
556bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
557 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
558 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000559 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000560
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000561 int NonNullOperand;
562 if (match(SI->getTrueValue(), m_Zero()))
563 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
564 NonNullOperand = 2;
565 else if (match(SI->getFalseValue(), m_Zero()))
566 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
567 NonNullOperand = 1;
568 else
569 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000570
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000571 // Change the div/rem to use 'Y' instead of the select.
572 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000573
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000574 // Okay, we know we replace the operand of the div/rem with 'Y' with no
575 // problem. However, the select, or the condition of the select may have
576 // multiple uses. Based on our knowledge that the operand must be non-zero,
577 // propagate the known value for the select into other uses of it, and
578 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000579
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000580 // If the select and condition only have a single use, don't bother with this,
581 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000582 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000583 if (SI->use_empty() && SelectCond->hasOneUse())
584 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000586 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000587 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000588 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000589 while (BBI != BBFront) {
590 --BBI;
Serguei Katkovd894fb42018-06-04 02:52:36 +0000591 // If we found an instruction that we can't assume will return, so
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000592 // information from below it cannot be propagated above it.
Serguei Katkovd894fb42018-06-04 02:52:36 +0000593 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000594 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000595
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000596 // Replace uses of the select or its condition with the known values.
597 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
598 I != E; ++I) {
599 if (*I == SI) {
600 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000601 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000602 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000603 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
604 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000605 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000606 }
607 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000608
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000609 // If we past the instruction, quit looking for it.
610 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000611 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000612 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000613 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000614
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000615 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000616 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000617 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000618
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000619 }
620 return true;
621}
622
Sanjay Patel1998cc62018-02-12 18:38:35 +0000623/// True if the multiply can not be expressed in an int this size.
624static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
625 bool IsSigned) {
626 bool Overflow;
627 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
628 return Overflow;
629}
630
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000631/// True if C1 is a multiple of C2. Quotient contains C1/C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000632static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
633 bool IsSigned) {
634 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
635
636 // Bail if we will divide by zero.
637 if (C2.isNullValue())
638 return false;
639
640 // Bail if we would divide INT_MIN by -1.
641 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
642 return false;
643
644 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
645 if (IsSigned)
646 APInt::sdivrem(C1, C2, Quotient, Remainder);
647 else
648 APInt::udivrem(C1, C2, Quotient, Remainder);
649
650 return Remainder.isMinValue();
651}
652
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000653/// This function implements the transforms common to both integer division
654/// instructions (udiv and sdiv). It is called by the visitors to those integer
655/// division instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000656/// Common integer divide transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000657Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000659 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000660 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000661
Chris Lattner7c99f192011-05-22 18:18:41 +0000662 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000664 I.setOperand(1, V);
665 return &I;
666 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000667
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000668 // Handle cases involving: [su]div X, (select Cond, Y, Z)
669 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000670 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000671 return &I;
672
Sanjay Patel1998cc62018-02-12 18:38:35 +0000673 const APInt *C2;
674 if (match(Op1, m_APInt(C2))) {
675 Value *X;
676 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000677
Sanjay Patel1998cc62018-02-12 18:38:35 +0000678 // (X / C1) / C2 -> X / (C1*C2)
679 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
680 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
681 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
682 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
683 return BinaryOperator::Create(I.getOpcode(), X,
684 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000686
687 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
688 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
689 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
690
691 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
692 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
693 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
694 ConstantInt::get(Ty, Quotient));
695 NewDiv->setIsExact(I.isExact());
696 return NewDiv;
697 }
698
699 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
700 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
701 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
702 ConstantInt::get(Ty, Quotient));
703 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
704 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
705 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
706 return Mul;
707 }
708 }
709
710 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
711 *C1 != C1->getBitWidth() - 1) ||
712 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
713 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
714 APInt C1Shifted = APInt::getOneBitSet(
715 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
716
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000717 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000718 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
719 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
720 ConstantInt::get(Ty, Quotient));
721 BO->setIsExact(I.isExact());
722 return BO;
723 }
724
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000725 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000726 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
727 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
728 ConstantInt::get(Ty, Quotient));
729 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
730 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
731 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
732 return Mul;
733 }
734 }
735
736 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000737 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
Sanjay Patel1998cc62018-02-12 18:38:35 +0000738 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000739 }
740
Craig Topper218a3592017-04-17 03:41:47 +0000741 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000742 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
743 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000744 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
745 // result is one, if Op1 is -1 then the result is minus one, otherwise
746 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000747 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000748 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
749 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000750 } else {
751 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
752 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000753 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000754 }
755 }
756
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000757 // See if we can fold away this div instruction.
758 if (SimplifyDemandedInstructionBits(I))
759 return &I;
760
Duncan Sands771e82a2011-01-28 16:51:11 +0000761 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000762 Value *X, *Z;
763 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
764 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
765 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000766 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000767
768 // (X << Y) / X -> 1 << Y
769 Value *Y;
770 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000771 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +0000772 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000773 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000774
Sanjay Patel510d6472018-02-11 17:20:32 +0000775 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
776 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
777 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
778 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
779 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000780 I.setOperand(0, ConstantInt::get(Ty, 1));
Sanjay Patel510d6472018-02-11 17:20:32 +0000781 I.setOperand(1, Y);
782 return &I;
783 }
784 }
785
Craig Topperf40110f2014-04-25 05:29:35 +0000786 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000787}
788
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000789static const unsigned MaxDepth = 6;
790
David Majnemer37f8f442013-07-04 21:17:49 +0000791namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000792
793using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
794 const BinaryOperator &I,
795 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +0000796
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000797/// Used to maintain state for visitUDivOperand().
David Majnemer37f8f442013-07-04 21:17:49 +0000798struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000799 /// Informs visitUDiv() how to fold this operand. This can be zero if this
800 /// action joins two actions together.
801 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +0000802
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000803 /// Which operand to fold.
804 Value *OperandToFold;
805
David Majnemer37f8f442013-07-04 21:17:49 +0000806 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000807 /// The instruction returned when FoldAction is invoked.
808 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +0000809
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000810 /// Stores the LHS action index if this action joins two actions together.
811 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +0000812 };
813
814 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000815 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000816 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
817 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
818};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000819
820} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +0000821
822// X udiv 2^C -> X >> C
823static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
824 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +0000825 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
826 if (!C1)
827 llvm_unreachable("Failed to constant fold udiv -> logbase2");
828 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000829 if (I.isExact())
830 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000831 return LShr;
832}
833
David Majnemer37f8f442013-07-04 21:17:49 +0000834// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000835// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +0000836static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
837 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000838 Value *ShiftLeft;
839 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
840 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +0000841
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000842 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000843 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000844 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000845 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000846 Constant *Log2Base = getLogBase2(N->getType(), CI);
847 if (!Log2Base)
848 llvm_unreachable("getLogBase2 should never fail here!");
849 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000850 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +0000851 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +0000852 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000853 if (I.isExact())
854 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000855 return LShr;
856}
857
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000858// Recursively visits the possible right hand operands of a udiv
David Majnemer37f8f442013-07-04 21:17:49 +0000859// instruction, seeing through select instructions, to determine if we can
860// replace the udiv with something simpler. If we find that an operand is not
861// able to simplify the udiv, we abort the entire transformation.
862static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
863 SmallVectorImpl<UDivFoldAction> &Actions,
864 unsigned Depth = 0) {
865 // Check to see if this is an unsigned division with an exact power of 2,
866 // if so, convert to a right shift.
867 if (match(Op1, m_Power2())) {
868 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
869 return Actions.size();
870 }
871
David Majnemer37f8f442013-07-04 21:17:49 +0000872 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
873 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
874 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
875 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
876 return Actions.size();
877 }
878
879 // The remaining tests are all recursive, so bail out if we hit the limit.
880 if (Depth++ == MaxDepth)
881 return 0;
882
883 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000884 if (size_t LHSIdx =
885 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
886 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
887 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000888 return Actions.size();
889 }
890
891 return 0;
892}
893
Sanjay Patelbb789382017-08-24 22:54:01 +0000894/// If we have zero-extended operands of an unsigned div or rem, we may be able
895/// to narrow the operation (sink the zext below the math).
896static Instruction *narrowUDivURem(BinaryOperator &I,
897 InstCombiner::BuilderTy &Builder) {
898 Instruction::BinaryOps Opcode = I.getOpcode();
899 Value *N = I.getOperand(0);
900 Value *D = I.getOperand(1);
901 Type *Ty = I.getType();
902 Value *X, *Y;
903 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
904 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
905 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
906 // urem (zext X), (zext Y) --> zext (urem X, Y)
907 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
908 return new ZExtInst(NarrowOp, Ty);
909 }
910
911 Constant *C;
912 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
913 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
914 // If the constant is the same in the smaller type, use the narrow version.
915 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
916 if (ConstantExpr::getZExt(TruncC, Ty) != C)
917 return nullptr;
918
919 // udiv (zext X), C --> zext (udiv X, C')
920 // urem (zext X), C --> zext (urem X, C')
921 // udiv C, (zext X) --> zext (udiv C', X)
922 // urem C, (zext X) --> zext (urem C', X)
923 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
924 : Builder.CreateBinOp(Opcode, TruncC, X);
925 return new ZExtInst(NarrowOp, Ty);
926 }
927
928 return nullptr;
929}
930
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000931Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000932 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
933 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000934 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +0000935
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000936 if (Instruction *X = foldShuffledBinop(I))
937 return X;
938
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000939 // Handle the integer div common cases
940 if (Instruction *Common = commonIDivTransforms(I))
941 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000942
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000943 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel38a86d32018-06-25 22:50:26 +0000944 Value *X;
945 const APInt *C1, *C2;
946 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
947 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
948 bool Overflow;
949 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
950 if (!Overflow) {
951 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
952 BinaryOperator *BO = BinaryOperator::CreateUDiv(
953 X, ConstantInt::get(X->getType(), C2ShlC1));
954 if (IsExact)
955 BO->setIsExact();
956 return BO;
David Majnemera2521382014-10-13 21:48:30 +0000957 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000958 }
959
Sanjay Patel38a86d32018-06-25 22:50:26 +0000960 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
961 // TODO: Could use isKnownNegative() to handle non-constant values.
Sanjay Patel7c45deb2018-06-26 12:41:15 +0000962 Type *Ty = I.getType();
Sanjay Patel38a86d32018-06-25 22:50:26 +0000963 if (match(Op1, m_Negative())) {
964 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
Sanjay Patel7c45deb2018-06-26 12:41:15 +0000965 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
966 }
967 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
968 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
969 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
970 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
Sanjay Patel38a86d32018-06-25 22:50:26 +0000971 }
972
Sanjay Patelbb789382017-08-24 22:54:01 +0000973 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
974 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000975
David Majnemer37f8f442013-07-04 21:17:49 +0000976 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
977 SmallVector<UDivFoldAction, 6> UDivActions;
978 if (visitUDivOperand(Op0, Op1, I, UDivActions))
979 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
980 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
981 Value *ActionOp1 = UDivActions[i].OperandToFold;
982 Instruction *Inst;
983 if (Action)
984 Inst = Action(Op0, ActionOp1, I, *this);
985 else {
986 // This action joins two actions together. The RHS of this action is
987 // simply the last action we processed, we saved the LHS action index in
988 // the joining action.
989 size_t SelectRHSIdx = i - 1;
990 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
991 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
992 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
993 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
994 SelectLHS, SelectRHS);
995 }
996
997 // If this is the last action to process, return it to the InstCombiner.
998 // Otherwise, we insert it before the UDiv and record it so that we may
999 // use it as part of a joining action (i.e., a SelectInst).
1000 if (e - i != 1) {
1001 Inst->insertBefore(&I);
1002 UDivActions[i].FoldResult = Inst;
1003 } else
1004 return Inst;
1005 }
1006
Craig Topperf40110f2014-04-25 05:29:35 +00001007 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001008}
1009
1010Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001011 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1012 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001013 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001014
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001015 if (Instruction *X = foldShuffledBinop(I))
1016 return X;
1017
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001018 // Handle the integer div common cases
1019 if (Instruction *Common = commonIDivTransforms(I))
1020 return Common;
1021
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel6a96d902018-06-25 21:39:41 +00001023 Value *X;
1024 // sdiv Op0, -1 --> -Op0
1025 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1026 if (match(Op1, m_AllOnes()) ||
1027 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1028 return BinaryOperator::CreateNeg(Op0);
1029
Sanjay Patelc6ada532016-06-27 17:25:57 +00001030 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001031 if (match(Op1, m_APInt(Op1C))) {
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001032 // sdiv exact X, C --> ashr exact X, log2(C)
1033 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1034 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1035 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1036 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001037
1038 // If the dividend is sign-extended and the constant divisor is small enough
1039 // to fit in the source type, shrink the division to the narrower type:
1040 // (sext X) sdiv C --> sext (X sdiv C)
1041 Value *Op0Src;
1042 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1043 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1044
1045 // In the general case, we need to make sure that the dividend is not the
1046 // minimum signed value because dividing that by -1 is UB. But here, we
1047 // know that the -1 divisor case is already handled above.
1048
1049 Constant *NarrowDivisor =
1050 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001051 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001052 return new SExtInst(NarrowOp, Op0->getType());
1053 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001054 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001055
Benjamin Kramer72196f32014-01-19 15:24:22 +00001056 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001057 // X/INT_MIN -> X == INT_MIN
1058 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001059 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001060
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001061 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001062 Value *X;
1063 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1064 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1065 BO->setIsExact(I.isExact());
1066 return BO;
1067 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001068 }
1069
1070 // If the sign bits of both operands are zero (i.e. we can prove they are
1071 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001072 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001073 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1074 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1075 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1076 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1077 BO->setIsExact(I.isExact());
1078 return BO;
1079 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080
Craig Topperd4039f72017-05-25 21:51:12 +00001081 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001082 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1083 // Safe because the only negative value (1 << Y) can take on is
1084 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1085 // the sign bit set.
1086 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1087 BO->setIsExact(I.isExact());
1088 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001089 }
1090 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001091
Craig Topperf40110f2014-04-25 05:29:35 +00001092 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001093}
1094
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001095/// Remove negation and try to convert division into multiplication.
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001096static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1097 Constant *C;
1098 if (!match(I.getOperand(1), m_Constant(C)))
Craig Topperf40110f2014-04-25 05:29:35 +00001099 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001100
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001101 // -X / C --> X / -C
1102 Value *X;
1103 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001104 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001105
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001106 // If the constant divisor has an exact inverse, this is always safe. If not,
1107 // then we can still create a reciprocal if fast-math-flags allow it and the
1108 // constant is a regular number (not zero, infinite, or denormal).
1109 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
Craig Topperf40110f2014-04-25 05:29:35 +00001110 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001111
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001112 // Disallow denormal constants because we don't know what would happen
1113 // on all targets.
1114 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1115 // denorms are flushed?
1116 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1117 if (!RecipC->isNormalFP())
1118 return nullptr;
1119
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001120 // X / C --> X * (1 / C)
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001121 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001122}
1123
Sanjay Patel6f716a72018-02-21 00:01:45 +00001124/// Remove negation and try to reassociate constant math.
Sanjay Patele4129542018-02-19 21:17:58 +00001125static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001126 Constant *C;
1127 if (!match(I.getOperand(0), m_Constant(C)))
Sanjay Patele4129542018-02-19 21:17:58 +00001128 return nullptr;
1129
Sanjay Patel6f716a72018-02-21 00:01:45 +00001130 // C / -X --> -C / X
Sanjay Patele4129542018-02-19 21:17:58 +00001131 Value *X;
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001132 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1133 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
Sanjay Patel6f716a72018-02-21 00:01:45 +00001134
1135 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1136 return nullptr;
1137
1138 // Try to reassociate C / X expressions where X includes another constant.
Sanjay Patele4129542018-02-19 21:17:58 +00001139 Constant *C2, *NewC = nullptr;
1140 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001141 // C / (X * C2) --> (C / C2) / X
1142 NewC = ConstantExpr::getFDiv(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001143 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001144 // C / (X / C2) --> (C * C2) / X
1145 NewC = ConstantExpr::getFMul(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001146 }
1147 // Disallow denormal constants because we don't know what would happen
1148 // on all targets.
1149 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1150 // denorms are flushed?
1151 if (!NewC || !NewC->isNormalFP())
1152 return nullptr;
1153
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001154 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
Sanjay Patele4129542018-02-19 21:17:58 +00001155}
1156
Frits van Bommel2a559512011-01-29 17:50:27 +00001157Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001158 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1159 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001160 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001161 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001162
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001163 if (Instruction *X = foldShuffledBinop(I))
1164 return X;
1165
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001166 if (Instruction *R = foldFDivConstantDivisor(I))
1167 return R;
Sanjay Patel28165602018-02-19 23:09:03 +00001168
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001169 if (Instruction *R = foldFDivConstantDividend(I))
1170 return R;
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001171
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Stephen Lina9b57f62013-07-20 07:13:13 +00001173 if (isa<Constant>(Op0))
1174 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1175 if (Instruction *R = FoldOpIntoSelect(I, SI))
1176 return R;
1177
Sanjay Patel29b98ae2018-02-20 17:14:53 +00001178 if (isa<Constant>(Op1))
Stephen Lina9b57f62013-07-20 07:13:13 +00001179 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1180 if (Instruction *R = FoldOpIntoSelect(I, SI))
1181 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001182
Sanjay Patel31a90462018-02-26 16:02:45 +00001183 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001184 Value *X, *Y;
Sanjay Patel91bb7752018-02-16 17:52:32 +00001185 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1186 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1187 // (X / Y) / Z => X / (Y * Z)
Sanjay Patel31a90462018-02-26 16:02:45 +00001188 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001189 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001190 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001191 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1192 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1193 // Z / (X / Y) => (Y * Z) / X
Sanjay Patel31a90462018-02-26 16:02:45 +00001194 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001195 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001196 }
1197 }
1198
Sanjay Patel339b4d32018-02-15 15:07:12 +00001199 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001200 // sin(X) / cos(X) -> tan(X)
1201 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1202 Value *X;
1203 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1204 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1205 bool IsCot =
1206 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1207 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001208
Sanjay Patel65da14d2018-02-16 16:13:20 +00001209 if ((IsTan || IsCot) && hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1210 LibFunc_tanf, LibFunc_tanl)) {
1211 IRBuilder<> B(&I);
1212 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1213 B.setFastMathFlags(I.getFastMathFlags());
1214 AttributeList Attrs = CallSite(Op0).getCalledFunction()->getAttributes();
1215 Value *Res = emitUnaryFloatFnCall(X, TLI.getName(LibFunc_tan), B, Attrs);
1216 if (IsCot)
1217 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1218 return replaceInstUsesWith(I, Res);
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001219 }
1220 }
1221
Sanjay Patel1998cc62018-02-12 18:38:35 +00001222 // -X / -Y -> X / Y
1223 Value *X, *Y;
1224 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
1225 I.setOperand(0, X);
1226 I.setOperand(1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001227 return &I;
1228 }
1229
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001230 // X / (X * Y) --> 1.0 / Y
1231 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1232 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1233 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1234 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1235 I.setOperand(0, ConstantFP::get(I.getType(), 1.0));
1236 I.setOperand(1, Y);
1237 return &I;
1238 }
1239
Craig Topperf40110f2014-04-25 05:29:35 +00001240 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001241}
1242
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001243/// This function implements the transforms common to both integer remainder
1244/// instructions (urem and srem). It is called by the visitors to those integer
1245/// remainder instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00001246/// Common integer remainder transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001247Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1249
Chris Lattner7c99f192011-05-22 18:18:41 +00001250 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001251 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001252 I.setOperand(1, V);
1253 return &I;
1254 }
1255
Duncan Sandsa3e36992011-05-02 16:27:02 +00001256 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001257 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001258 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259
Benjamin Kramer72196f32014-01-19 15:24:22 +00001260 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001261 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1262 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1263 if (Instruction *R = FoldOpIntoSelect(I, SI))
1264 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001265 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001266 const APInt *Op1Int;
1267 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1268 (I.getOpcode() == Instruction::URem ||
1269 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001270 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001271 // predecessor blocks, so do this only if we know the srem or urem
1272 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001273 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001274 return NV;
1275 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001276 }
1277
1278 // See if we can fold away this rem instruction.
1279 if (SimplifyDemandedInstructionBits(I))
1280 return &I;
1281 }
1282 }
1283
Craig Topperf40110f2014-04-25 05:29:35 +00001284 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001285}
1286
1287Instruction *InstCombiner::visitURem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001288 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1289 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001290 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001291
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001292 if (Instruction *X = foldShuffledBinop(I))
1293 return X;
1294
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001295 if (Instruction *common = commonIRemTransforms(I))
1296 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001297
Sanjay Patelbb789382017-08-24 22:54:01 +00001298 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1299 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001300
David Majnemer470b0772013-05-11 09:01:28 +00001301 // X urem Y -> X and Y-1, where Y is a power of 2,
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001303 Type *Ty = I.getType();
Craig Topperd4039f72017-05-25 21:51:12 +00001304 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001305 Constant *N1 = Constant::getAllOnesValue(Ty);
Craig Topperbb4069e2017-07-07 23:16:26 +00001306 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001307 return BinaryOperator::CreateAnd(Op0, Add);
1308 }
1309
Nick Lewycky7459be62013-07-13 01:16:47 +00001310 // 1 urem X -> zext(X != 1)
Sanjay Patel9adea012018-06-26 16:39:29 +00001311 if (match(Op0, m_One()))
1312 return CastInst::CreateZExtOrBitCast(Builder.CreateICmpNE(Op1, Op0), Ty);
Nick Lewycky7459be62013-07-13 01:16:47 +00001313
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001314 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001315 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001316 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1317 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001318 return SelectInst::Create(Cmp, Op0, Sub);
1319 }
1320
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001321 // If the divisor is a sext of a boolean, then the divisor must be max
1322 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1323 // max unsigned value. In that case, the remainder is 0:
1324 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1325 Value *X;
1326 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1327 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1328 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1329 }
1330
Craig Topperf40110f2014-04-25 05:29:35 +00001331 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001332}
1333
1334Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001335 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1336 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001337 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001338
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001339 if (Instruction *X = foldShuffledBinop(I))
1340 return X;
1341
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001342 // Handle the integer rem common cases
1343 if (Instruction *Common = commonIRemTransforms(I))
1344 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001345
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemerdb077302014-10-13 22:37:51 +00001347 {
1348 const APInt *Y;
1349 // X % -Y -> X % Y
Simon Pilgrima54e8e42018-02-08 19:00:45 +00001350 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001351 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001352 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001353 return &I;
1354 }
David Majnemerdb077302014-10-13 22:37:51 +00001355 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001356
1357 // If the sign bits of both operands are zero (i.e. we can prove they are
1358 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001359 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001360 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1361 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1362 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1363 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001364 }
1365
1366 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001367 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1368 Constant *C = cast<Constant>(Op1);
1369 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001370
1371 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001372 bool hasMissing = false;
1373 for (unsigned i = 0; i != VWidth; ++i) {
1374 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001375 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001376 hasMissing = true;
1377 break;
1378 }
1379
1380 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001381 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001382 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001383 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001384
Chris Lattner0256be92012-01-27 03:08:05 +00001385 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001386 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001387 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001388 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001389 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001390 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001391 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001392 }
1393 }
1394
1395 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001396 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001397 Worklist.AddValue(I.getOperand(1));
1398 I.setOperand(1, NewRHSV);
1399 return &I;
1400 }
1401 }
1402 }
1403
Craig Topperf40110f2014-04-25 05:29:35 +00001404 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001405}
1406
1407Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001408 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1409 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001410 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001411 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001412
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001413 if (Instruction *X = foldShuffledBinop(I))
1414 return X;
1415
Craig Topperf40110f2014-04-25 05:29:35 +00001416 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001417}