blob: 5a4e12d142c22b4eae4b4e7921dde7332262d585 [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
Rafael Espindola65281bf2013-05-31 14:27:15 +000098/// \brief A helper routine of InstCombiner::visitMul().
99///
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
David Majnemer54c2ca22014-12-26 09:10:14 +0000128/// \brief Return true if we can prove that:
129/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000130bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
131 const Value *RHS,
132 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000133 // Multiplying n * m significant bits yields a result of n + m significant
134 // bits. If the total number of significant bits does not exceed the
135 // result bit width (minus 1), there is no overflow.
136 // This means if we have enough leading sign bits in the operands
137 // we can guarantee that the result does not overflow.
138 // Ref: "Hacker's Delight" by Henry Warren
139 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
140
141 // Note that underestimating the number of sign bits gives a more
142 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 unsigned SignBits =
144 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000145
146 // First handle the easy case: if we have enough sign bits there's
147 // definitely no overflow.
148 if (SignBits > BitWidth + 1)
149 return true;
150
151 // There are two ambiguous cases where there can be no overflow:
152 // SignBits == BitWidth + 1 and
153 // SignBits == BitWidth
154 // The second case is difficult to check, therefore we only handle the
155 // first case.
156 if (SignBits == BitWidth + 1) {
157 // It overflows only when both arguments are negative and the true
158 // product is exactly the minimum negative number.
159 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
160 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000161 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
162 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
163 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000164 return true;
165 }
166 return false;
167}
168
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000169Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000170 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
172
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000173 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000174 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000175
Craig Toppera4205622017-06-09 03:21:29 +0000176 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000177 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000178
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000179 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000180 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000181
David Majnemer027bc802014-11-22 04:52:38 +0000182 // X * -1 == 0 - X
183 if (match(Op1, m_AllOnes())) {
184 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
185 if (I.hasNoSignedWrap())
186 BO->setHasNoSignedWrap();
187 return BO;
188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Rafael Espindola65281bf2013-05-31 14:27:15 +0000190 // Also allow combining multiply instructions on vectors.
191 {
192 Value *NewOp;
193 Constant *C1, *C2;
194 const APInt *IVal;
195 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
196 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000197 match(C1, m_APInt(IVal))) {
198 // ((X << C2)*C1) == (X * (C1 << C2))
199 Constant *Shl = ConstantExpr::getShl(C1, C2);
200 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
201 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
202 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
203 BO->setHasNoUnsignedWrap();
204 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
205 Shl->isNotMinSignedValue())
206 BO->setHasNoSignedWrap();
207 return BO;
208 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000209
Rafael Espindola65281bf2013-05-31 14:27:15 +0000210 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000211 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
212 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
David Majnemer45951a62015-04-18 04:41:30 +0000213 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000214 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000215
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000216 if (I.hasNoUnsignedWrap())
217 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000218 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000219 const APInt *V;
220 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000221 Shl->setHasNoSignedWrap();
222 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000223
Rafael Espindola65281bf2013-05-31 14:27:15 +0000224 return Shl;
225 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000226 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000227 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000228
Rafael Espindola65281bf2013-05-31 14:27:15 +0000229 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000230 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
231 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
232 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000233 {
234 const APInt & Val = CI->getValue();
235 const APInt &PosVal = Val.abs();
236 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000237 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000238 if (Op0->hasOneUse()) {
239 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000240 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000241 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000242 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000243 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000244 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000245 if (Sub)
246 return
247 BinaryOperator::CreateMul(Sub,
248 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000249 }
250 }
251 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000252 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000253
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000254 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
255 return FoldedMul;
256
Chris Lattner6b657ae2011-02-10 05:36:31 +0000257 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000258 if (isa<Constant>(Op1)) {
Benjamin Kramer72196f32014-01-19 15:24:22 +0000259 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000260 Value *X;
261 Constant *C1;
262 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
263 Value *Mul = Builder.CreateMul(C1, Op1);
264 // Only go forward with the transform if C1*CI simplifies to a tidier
265 // constant.
266 if (!match(Mul, m_Mul(m_Value(), m_Value())))
267 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000268 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000269 }
270
Sanjay Patel604cb9e2018-02-14 16:50:55 +0000271 // -X * C --> X * -C
272 Value *X, *Y;
273 Constant *Op1C;
274 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
275 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
276
277 // -X * -Y --> X * Y
278 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
279 auto *NewMul = BinaryOperator::CreateMul(X, Y);
280 if (I.hasNoSignedWrap() &&
281 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
282 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
283 NewMul->setHasNoSignedWrap();
284 return NewMul;
David Majnemer8279a7502014-11-22 07:25:19 +0000285 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000286
287 // (X / Y) * Y = X - (X % Y)
288 // (X / Y) * -Y = (X % Y) - X
289 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000290 Value *Y = Op1;
291 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
292 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
293 Div->getOpcode() != Instruction::SDiv)) {
294 Y = Op0;
295 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000296 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000297 Value *Neg = dyn_castNegVal(Y);
298 if (Div && Div->hasOneUse() &&
299 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
300 (Div->getOpcode() == Instruction::UDiv ||
301 Div->getOpcode() == Instruction::SDiv)) {
302 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303
Chris Lattner35315d02011-02-06 21:44:57 +0000304 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000305 if (Div->isExact()) {
306 if (DivOp1 == Y)
307 return replaceInstUsesWith(I, X);
308 return BinaryOperator::CreateNeg(X);
309 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000310
Sanjay Patela0a56822017-03-14 17:27:27 +0000311 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
312 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000313 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000314 if (DivOp1 == Y)
315 return BinaryOperator::CreateSub(X, Rem);
316 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000317 }
318 }
319
320 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000321 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000322 return BinaryOperator::CreateAnd(Op0, Op1);
323
324 // X*(1 << Y) --> X << Y
325 // (1 << Y)*X --> X << Y
326 {
327 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000328 BinaryOperator *BO = nullptr;
329 bool ShlNSW = false;
330 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
331 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000332 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000333 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000334 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000335 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000336 }
337 if (BO) {
338 if (I.hasNoUnsignedWrap())
339 BO->setHasNoUnsignedWrap();
340 if (I.hasNoSignedWrap() && ShlNSW)
341 BO->setHasNoSignedWrap();
342 return BO;
343 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000344 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000345
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000346 // (bool X) * Y --> X ? Y : 0
Sanjay Patel7558d862018-02-13 22:24:37 +0000347 // Y * (bool X) --> X ? Y : 0
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000348 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
349 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000350 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
351 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
352
Sanjay Patel7558d862018-02-13 22:24:37 +0000353 // (lshr X, 31) * Y --> (ashr X, 31) & Y
354 // Y * (lshr X, 31) --> (ashr X, 31) & Y
355 // TODO: We are not checking one-use because the elimination of the multiply
356 // is better for analysis?
357 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
358 // more similar to what we're doing above.
359 const APInt *C;
360 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
361 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
362 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
363 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000364
David Majnemera1cfd7c2016-12-30 00:28:58 +0000365 // Check for (mul (sext x), y), see if we can merge this into an
366 // integer mul followed by a sext.
367 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
368 // (mul (sext x), cst) --> (sext (mul x, cst'))
369 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
370 if (Op0Conv->hasOneUse()) {
371 Constant *CI =
372 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
373 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000374 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000375 // Insert the new, smaller mul.
376 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000377 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000378 return new SExtInst(NewMul, I.getType());
379 }
380 }
381 }
382
383 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
384 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
385 // Only do this if x/y have the same type, if at last one of them has a
386 // single use (so we don't increase the number of sexts), and if the
387 // integer mul will not overflow.
388 if (Op0Conv->getOperand(0)->getType() ==
389 Op1Conv->getOperand(0)->getType() &&
390 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000391 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000392 Op1Conv->getOperand(0), I)) {
393 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000394 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000395 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
396 return new SExtInst(NewMul, I.getType());
397 }
398 }
399 }
400
401 // Check for (mul (zext x), y), see if we can merge this into an
402 // integer mul followed by a zext.
403 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
404 // (mul (zext x), cst) --> (zext (mul x, cst'))
405 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
406 if (Op0Conv->hasOneUse()) {
407 Constant *CI =
408 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
409 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000410 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000411 // Insert the new, smaller mul.
412 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000413 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000414 return new ZExtInst(NewMul, I.getType());
415 }
416 }
417 }
418
419 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
420 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
421 // Only do this if x/y have the same type, if at last one of them has a
422 // single use (so we don't increase the number of zexts), and if the
423 // integer mul will not overflow.
424 if (Op0Conv->getOperand(0)->getType() ==
425 Op1Conv->getOperand(0)->getType() &&
426 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000427 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
428 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000429 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000430 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000431 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
432 return new ZExtInst(NewMul, I.getType());
433 }
434 }
435 }
436
Craig Topper2b1fc322017-05-22 06:25:31 +0000437 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000438 Changed = true;
439 I.setHasNoSignedWrap(true);
440 }
441
Craig Topperbb973722017-05-15 02:44:08 +0000442 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000443 Changed = true;
444 I.setHasNoUnsignedWrap(true);
445 }
446
Craig Topperf40110f2014-04-25 05:29:35 +0000447 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000448}
449
450Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000451 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
453
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000454 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000455 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000456
Craig Toppera4205622017-06-09 03:21:29 +0000457 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
458 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000459 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000460
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000461 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
462 return FoldedMul;
463
Sanjay Patele29375d2018-03-02 23:06:45 +0000464 // X * -1.0 --> -X
465 if (match(Op1, m_SpecificFP(-1.0)))
466 return BinaryOperator::CreateFNegFMF(Op0, &I);
Sanjay Patel6b9c7a92018-02-23 17:14:28 +0000467
Sanjay Patele29375d2018-03-02 23:06:45 +0000468 // -X * -Y --> X * Y
469 Value *X, *Y;
470 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
471 return BinaryOperator::CreateFMulFMF(X, Y, &I);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000472
Sanjay Patele29375d2018-03-02 23:06:45 +0000473 // -X * C --> X * -C
474 Constant *C;
475 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
476 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000477
Sanjay Patele29375d2018-03-02 23:06:45 +0000478 // Sink negation: -X * Y --> -(X * Y)
479 if (match(Op0, m_OneUse(m_FNeg(m_Value(X)))))
480 return BinaryOperator::CreateFNegFMF(Builder.CreateFMulFMF(X, Op1, &I), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000481
Sanjay Patele29375d2018-03-02 23:06:45 +0000482 // Sink negation: Y * -X --> -(X * Y)
483 if (match(Op1, m_OneUse(m_FNeg(m_Value(X)))))
484 return BinaryOperator::CreateFNegFMF(Builder.CreateFMulFMF(X, Op0, &I), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000485
Sanjay Patele29375d2018-03-02 23:06:45 +0000486 // fabs(X) * fabs(X) -> X * X
487 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
488 return BinaryOperator::CreateFMulFMF(X, X, &I);
489
490 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
491 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
492 return replaceInstUsesWith(I, V);
493
Sanjay Patel81b3b102018-04-03 22:19:19 +0000494 if (I.hasAllowReassoc()) {
495 // Reassociate constant RHS with another constant to form constant
496 // expression.
497 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
498 Constant *C1;
499 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
500 // (C1 / X) * C --> (C * C1) / X
501 Constant *CC1 = ConstantExpr::getFMul(C, C1);
502 if (CC1->isNormalFP())
503 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
504 }
505 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
506 // (X / C1) * C --> X * (C / C1)
507 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
508 if (CDivC1->isNormalFP())
509 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
Sanjay Patel204edec2018-03-13 14:46:32 +0000510
Sanjay Patel81b3b102018-04-03 22:19:19 +0000511 // If the constant was a denormal, try reassociating differently.
512 // (X / C1) * C --> X / (C1 / C)
513 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
514 if (Op0->hasOneUse() && C1DivC->isNormalFP())
515 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
516 }
517
518 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
519 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
520 // further folds and (X * C) + C2 is 'fma'.
521 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
522 // (X + C1) * C --> (X * C) + (C * C1)
523 Constant *CC1 = ConstantExpr::getFMul(C, C1);
524 Value *XC = Builder.CreateFMulFMF(X, C, &I);
525 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
526 }
527 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
528 // (C1 - X) * C --> (C * C1) - (X * C)
529 Constant *CC1 = ConstantExpr::getFMul(C, C1);
530 Value *XC = Builder.CreateFMulFMF(X, C, &I);
531 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
532 }
Sanjay Patel204edec2018-03-13 14:46:32 +0000533 }
534
Sanjay Patel81b3b102018-04-03 22:19:19 +0000535 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
536 // nnan disallows the possibility of returning a number if both operands are
537 // negative (in that case, we should return NaN).
538 if (I.hasNoNaNs() &&
539 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
540 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
541 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
542 Value *Sqrt = Builder.CreateIntrinsic(Intrinsic::sqrt, { XY }, &I);
543 return replaceInstUsesWith(I, Sqrt);
Sanjay Patel4fd4fd62018-03-26 15:03:57 +0000544 }
Sanjay Patel81b3b102018-04-03 22:19:19 +0000545
546 // (X*Y) * X => (X*X) * Y where Y != X
547 // The purpose is two-fold:
548 // 1) to form a power expression (of X).
549 // 2) potentially shorten the critical path: After transformation, the
550 // latency of the instruction Y is amortized by the expression of X*X,
551 // and therefore Y is in a "less critical" position compared to what it
552 // was before the transformation.
553 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
554 Op1 != Y) {
555 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
556 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
557 }
558 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
559 Op0 != Y) {
560 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
561 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000562 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000563 }
564
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000565 // log2(X * 0.5) * Y = log2(X) * Y - Y
566 if (I.isFast()) {
567 IntrinsicInst *Log2 = nullptr;
568 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
569 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
570 Log2 = cast<IntrinsicInst>(Op0);
571 Y = Op1;
Pedro Artigasd8795042012-11-30 19:09:41 +0000572 }
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000573 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
574 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
575 Log2 = cast<IntrinsicInst>(Op1);
576 Y = Op0;
577 }
578 if (Log2) {
579 Log2->setArgOperand(0, X);
580 Log2->copyFastMathFlags(&I);
581 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
582 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
Pedro Artigasd8795042012-11-30 19:09:41 +0000583 }
584 }
585
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000587}
588
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000589/// Fold a divide or remainder with a select instruction divisor when one of the
590/// select operands is zero. In that case, we can use the other select operand
591/// because div/rem by zero is undefined.
592bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
593 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
594 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000595 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000597 int NonNullOperand;
598 if (match(SI->getTrueValue(), m_Zero()))
599 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
600 NonNullOperand = 2;
601 else if (match(SI->getFalseValue(), m_Zero()))
602 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
603 NonNullOperand = 1;
604 else
605 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000606
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000607 // Change the div/rem to use 'Y' instead of the select.
608 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000609
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000610 // Okay, we know we replace the operand of the div/rem with 'Y' with no
611 // problem. However, the select, or the condition of the select may have
612 // multiple uses. Based on our knowledge that the operand must be non-zero,
613 // propagate the known value for the select into other uses of it, and
614 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000615
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000616 // If the select and condition only have a single use, don't bother with this,
617 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000618 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000619 if (SI->use_empty() && SelectCond->hasOneUse())
620 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000621
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000622 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000623 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000624 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000625 while (BBI != BBFront) {
626 --BBI;
627 // If we found a call to a function, we can't assume it will return, so
628 // information from below it cannot be propagated above it.
629 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
630 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000631
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000632 // Replace uses of the select or its condition with the known values.
633 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
634 I != E; ++I) {
635 if (*I == SI) {
636 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000637 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000638 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000639 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
640 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000641 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000642 }
643 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000644
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000645 // If we past the instruction, quit looking for it.
646 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000647 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000648 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000649 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000650
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000651 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000652 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000653 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000654
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000655 }
656 return true;
657}
658
Sanjay Patel1998cc62018-02-12 18:38:35 +0000659/// True if the multiply can not be expressed in an int this size.
660static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
661 bool IsSigned) {
662 bool Overflow;
663 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
664 return Overflow;
665}
666
667/// True if C2 is a multiple of C1. Quotient contains C2/C1.
668static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
669 bool IsSigned) {
670 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
671
672 // Bail if we will divide by zero.
673 if (C2.isNullValue())
674 return false;
675
676 // Bail if we would divide INT_MIN by -1.
677 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
678 return false;
679
680 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
681 if (IsSigned)
682 APInt::sdivrem(C1, C2, Quotient, Remainder);
683 else
684 APInt::udivrem(C1, C2, Quotient, Remainder);
685
686 return Remainder.isMinValue();
687}
688
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000689/// This function implements the transforms common to both integer division
690/// instructions (udiv and sdiv). It is called by the visitors to those integer
691/// division instructions.
692/// @brief Common integer divide transforms
693Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000695 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000696 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697
Chris Lattner7c99f192011-05-22 18:18:41 +0000698 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000700 I.setOperand(1, V);
701 return &I;
702 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000704 // Handle cases involving: [su]div X, (select Cond, Y, Z)
705 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000706 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000707 return &I;
708
Sanjay Patel1998cc62018-02-12 18:38:35 +0000709 const APInt *C2;
710 if (match(Op1, m_APInt(C2))) {
711 Value *X;
712 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000713
Sanjay Patel1998cc62018-02-12 18:38:35 +0000714 // (X / C1) / C2 -> X / (C1*C2)
715 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
716 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
717 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
718 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
719 return BinaryOperator::Create(I.getOpcode(), X,
720 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000721 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000722
723 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
724 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
725 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
726
727 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
728 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
729 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
730 ConstantInt::get(Ty, Quotient));
731 NewDiv->setIsExact(I.isExact());
732 return NewDiv;
733 }
734
735 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
736 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
737 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
738 ConstantInt::get(Ty, Quotient));
739 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
740 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
741 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
742 return Mul;
743 }
744 }
745
746 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
747 *C1 != C1->getBitWidth() - 1) ||
748 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
749 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
750 APInt C1Shifted = APInt::getOneBitSet(
751 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
752
753 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
754 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
755 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
756 ConstantInt::get(Ty, Quotient));
757 BO->setIsExact(I.isExact());
758 return BO;
759 }
760
761 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
762 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
763 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
764 ConstantInt::get(Ty, Quotient));
765 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
766 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
767 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
768 return Mul;
769 }
770 }
771
772 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000773 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
Sanjay Patel1998cc62018-02-12 18:38:35 +0000774 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000775 }
776
Craig Topper218a3592017-04-17 03:41:47 +0000777 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000778 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
779 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000780 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
781 // result is one, if Op1 is -1 then the result is minus one, otherwise
782 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000783 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000784 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
785 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000786 } else {
787 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
788 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000789 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000790 }
791 }
792
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000793 // See if we can fold away this div instruction.
794 if (SimplifyDemandedInstructionBits(I))
795 return &I;
796
Duncan Sands771e82a2011-01-28 16:51:11 +0000797 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000798 Value *X, *Z;
799 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
800 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
801 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000802 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000803
804 // (X << Y) / X -> 1 << Y
805 Value *Y;
806 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000807 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +0000808 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000809 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000810
Sanjay Patel510d6472018-02-11 17:20:32 +0000811 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
812 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
813 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
814 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
815 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000816 I.setOperand(0, ConstantInt::get(Ty, 1));
Sanjay Patel510d6472018-02-11 17:20:32 +0000817 I.setOperand(1, Y);
818 return &I;
819 }
820 }
821
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000823}
824
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000825static const unsigned MaxDepth = 6;
826
David Majnemer37f8f442013-07-04 21:17:49 +0000827namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000828
829using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
830 const BinaryOperator &I,
831 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +0000832
833/// \brief Used to maintain state for visitUDivOperand().
834struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000835 /// Informs visitUDiv() how to fold this operand. This can be zero if this
836 /// action joins two actions together.
837 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +0000838
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000839 /// Which operand to fold.
840 Value *OperandToFold;
841
David Majnemer37f8f442013-07-04 21:17:49 +0000842 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000843 /// The instruction returned when FoldAction is invoked.
844 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +0000845
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000846 /// Stores the LHS action index if this action joins two actions together.
847 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +0000848 };
849
850 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000851 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000852 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
853 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
854};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000855
856} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +0000857
858// X udiv 2^C -> X >> C
859static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
860 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +0000861 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
862 if (!C1)
863 llvm_unreachable("Failed to constant fold udiv -> logbase2");
864 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000865 if (I.isExact())
866 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000867 return LShr;
868}
869
870// X udiv C, where C >= signbit
871static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
872 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim9620f4b2018-02-09 10:43:59 +0000873 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<Constant>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +0000874 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
875 ConstantInt::get(I.getType(), 1));
876}
877
878// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000879// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +0000880static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
881 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000882 Value *ShiftLeft;
883 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
884 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +0000885
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000886 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000887 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000888 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000889 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000890 Constant *Log2Base = getLogBase2(N->getType(), CI);
891 if (!Log2Base)
892 llvm_unreachable("getLogBase2 should never fail here!");
893 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000894 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +0000895 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +0000896 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000897 if (I.isExact())
898 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000899 return LShr;
900}
901
902// \brief Recursively visits the possible right hand operands of a udiv
903// instruction, seeing through select instructions, to determine if we can
904// replace the udiv with something simpler. If we find that an operand is not
905// able to simplify the udiv, we abort the entire transformation.
906static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
907 SmallVectorImpl<UDivFoldAction> &Actions,
908 unsigned Depth = 0) {
909 // Check to see if this is an unsigned division with an exact power of 2,
910 // if so, convert to a right shift.
911 if (match(Op1, m_Power2())) {
912 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
913 return Actions.size();
914 }
915
Simon Pilgrim9620f4b2018-02-09 10:43:59 +0000916 // X udiv C, where C >= signbit
917 if (match(Op1, m_Negative())) {
918 Actions.push_back(UDivFoldAction(foldUDivNegCst, Op1));
919 return Actions.size();
920 }
David Majnemer37f8f442013-07-04 21:17:49 +0000921
922 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
923 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
924 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
925 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
926 return Actions.size();
927 }
928
929 // The remaining tests are all recursive, so bail out if we hit the limit.
930 if (Depth++ == MaxDepth)
931 return 0;
932
933 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000934 if (size_t LHSIdx =
935 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
936 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
937 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000938 return Actions.size();
939 }
940
941 return 0;
942}
943
Sanjay Patelbb789382017-08-24 22:54:01 +0000944/// If we have zero-extended operands of an unsigned div or rem, we may be able
945/// to narrow the operation (sink the zext below the math).
946static Instruction *narrowUDivURem(BinaryOperator &I,
947 InstCombiner::BuilderTy &Builder) {
948 Instruction::BinaryOps Opcode = I.getOpcode();
949 Value *N = I.getOperand(0);
950 Value *D = I.getOperand(1);
951 Type *Ty = I.getType();
952 Value *X, *Y;
953 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
954 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
955 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
956 // urem (zext X), (zext Y) --> zext (urem X, Y)
957 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
958 return new ZExtInst(NarrowOp, Ty);
959 }
960
961 Constant *C;
962 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
963 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
964 // If the constant is the same in the smaller type, use the narrow version.
965 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
966 if (ConstantExpr::getZExt(TruncC, Ty) != C)
967 return nullptr;
968
969 // udiv (zext X), C --> zext (udiv X, C')
970 // urem (zext X), C --> zext (urem X, C')
971 // udiv C, (zext X) --> zext (udiv C', X)
972 // urem C, (zext X) --> zext (urem C', X)
973 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
974 : Builder.CreateBinOp(Opcode, TruncC, X);
975 return new ZExtInst(NarrowOp, Ty);
976 }
977
978 return nullptr;
979}
980
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000981Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
983
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000984 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000985 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000986
Craig Toppera4205622017-06-09 03:21:29 +0000987 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000988 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +0000989
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000990 // Handle the integer div common cases
991 if (Instruction *Common = commonIDivTransforms(I))
992 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000993
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000994 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000995 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000996 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000997 const APInt *C1, *C2;
998 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
999 match(Op1, m_APInt(C2))) {
1000 bool Overflow;
1001 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001002 if (!Overflow) {
1003 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1004 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001005 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001006 if (IsExact)
1007 BO->setIsExact();
1008 return BO;
1009 }
David Majnemera2521382014-10-13 21:48:30 +00001010 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001011 }
1012
Sanjay Patelbb789382017-08-24 22:54:01 +00001013 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1014 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001015
David Majnemer37f8f442013-07-04 21:17:49 +00001016 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1017 SmallVector<UDivFoldAction, 6> UDivActions;
1018 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1019 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1020 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1021 Value *ActionOp1 = UDivActions[i].OperandToFold;
1022 Instruction *Inst;
1023 if (Action)
1024 Inst = Action(Op0, ActionOp1, I, *this);
1025 else {
1026 // This action joins two actions together. The RHS of this action is
1027 // simply the last action we processed, we saved the LHS action index in
1028 // the joining action.
1029 size_t SelectRHSIdx = i - 1;
1030 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1031 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1032 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1033 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1034 SelectLHS, SelectRHS);
1035 }
1036
1037 // If this is the last action to process, return it to the InstCombiner.
1038 // Otherwise, we insert it before the UDiv and record it so that we may
1039 // use it as part of a joining action (i.e., a SelectInst).
1040 if (e - i != 1) {
1041 Inst->insertBefore(&I);
1042 UDivActions[i].FoldResult = Inst;
1043 } else
1044 return Inst;
1045 }
1046
Craig Topperf40110f2014-04-25 05:29:35 +00001047 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001048}
1049
1050Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1051 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1052
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001053 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001054 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001055
Craig Toppera4205622017-06-09 03:21:29 +00001056 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001057 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001058
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001059 // Handle the integer div common cases
1060 if (Instruction *Common = commonIDivTransforms(I))
1061 return Common;
1062
Sanjay Patelc6ada532016-06-27 17:25:57 +00001063 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001064 if (match(Op1, m_APInt(Op1C))) {
1065 // sdiv X, -1 == -X
1066 if (Op1C->isAllOnesValue())
1067 return BinaryOperator::CreateNeg(Op0);
1068
1069 // sdiv exact X, C --> ashr exact X, log2(C)
1070 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1071 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1072 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1073 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001074
1075 // If the dividend is sign-extended and the constant divisor is small enough
1076 // to fit in the source type, shrink the division to the narrower type:
1077 // (sext X) sdiv C --> sext (X sdiv C)
1078 Value *Op0Src;
1079 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1080 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1081
1082 // In the general case, we need to make sure that the dividend is not the
1083 // minimum signed value because dividing that by -1 is UB. But here, we
1084 // know that the -1 divisor case is already handled above.
1085
1086 Constant *NarrowDivisor =
1087 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001088 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001089 return new SExtInst(NarrowOp, Op0->getType());
1090 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001091 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001092
Benjamin Kramer72196f32014-01-19 15:24:22 +00001093 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001094 // X/INT_MIN -> X == INT_MIN
1095 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001096 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001097
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001098 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001099 Value *X;
1100 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1101 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1102 BO->setIsExact(I.isExact());
1103 return BO;
1104 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001105 }
1106
1107 // If the sign bits of both operands are zero (i.e. we can prove they are
1108 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001109 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001110 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1111 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1112 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1113 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1114 BO->setIsExact(I.isExact());
1115 return BO;
1116 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001117
Craig Topperd4039f72017-05-25 21:51:12 +00001118 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001119 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1120 // Safe because the only negative value (1 << Y) can take on is
1121 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1122 // the sign bit set.
1123 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1124 BO->setIsExact(I.isExact());
1125 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001126 }
1127 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001128
Craig Topperf40110f2014-04-25 05:29:35 +00001129 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001130}
1131
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001132/// Remove negation and try to convert division into multiplication.
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001133static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1134 Constant *C;
1135 if (!match(I.getOperand(1), m_Constant(C)))
Craig Topperf40110f2014-04-25 05:29:35 +00001136 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001137
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001138 // -X / C --> X / -C
1139 Value *X;
1140 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001141 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001142
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001143 // If the constant divisor has an exact inverse, this is always safe. If not,
1144 // then we can still create a reciprocal if fast-math-flags allow it and the
1145 // constant is a regular number (not zero, infinite, or denormal).
1146 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
Craig Topperf40110f2014-04-25 05:29:35 +00001147 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001149 // Disallow denormal constants because we don't know what would happen
1150 // on all targets.
1151 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1152 // denorms are flushed?
1153 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1154 if (!RecipC->isNormalFP())
1155 return nullptr;
1156
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001157 // X / C --> X * (1 / C)
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001158 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001159}
1160
Sanjay Patel6f716a72018-02-21 00:01:45 +00001161/// Remove negation and try to reassociate constant math.
Sanjay Patele4129542018-02-19 21:17:58 +00001162static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001163 Constant *C;
1164 if (!match(I.getOperand(0), m_Constant(C)))
Sanjay Patele4129542018-02-19 21:17:58 +00001165 return nullptr;
1166
Sanjay Patel6f716a72018-02-21 00:01:45 +00001167 // C / -X --> -C / X
Sanjay Patele4129542018-02-19 21:17:58 +00001168 Value *X;
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001169 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1170 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
Sanjay Patel6f716a72018-02-21 00:01:45 +00001171
1172 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1173 return nullptr;
1174
1175 // Try to reassociate C / X expressions where X includes another constant.
Sanjay Patele4129542018-02-19 21:17:58 +00001176 Constant *C2, *NewC = nullptr;
1177 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001178 // C / (X * C2) --> (C / C2) / X
1179 NewC = ConstantExpr::getFDiv(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001180 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001181 // C / (X / C2) --> (C * C2) / X
1182 NewC = ConstantExpr::getFMul(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001183 }
1184 // Disallow denormal constants because we don't know what would happen
1185 // on all targets.
1186 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1187 // denorms are flushed?
1188 if (!NewC || !NewC->isNormalFP())
1189 return nullptr;
1190
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001191 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
Sanjay Patele4129542018-02-19 21:17:58 +00001192}
1193
Frits van Bommel2a559512011-01-29 17:50:27 +00001194Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1196
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001197 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001198 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001199
Craig Toppera4205622017-06-09 03:21:29 +00001200 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1201 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001202 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001203
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001204 if (Instruction *R = foldFDivConstantDivisor(I))
1205 return R;
Sanjay Patel28165602018-02-19 23:09:03 +00001206
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001207 if (Instruction *R = foldFDivConstantDividend(I))
1208 return R;
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001209
Stephen Lina9b57f62013-07-20 07:13:13 +00001210 if (isa<Constant>(Op0))
1211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1212 if (Instruction *R = FoldOpIntoSelect(I, SI))
1213 return R;
1214
Sanjay Patel29b98ae2018-02-20 17:14:53 +00001215 if (isa<Constant>(Op1))
Stephen Lina9b57f62013-07-20 07:13:13 +00001216 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1217 if (Instruction *R = FoldOpIntoSelect(I, SI))
1218 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001219
Sanjay Patel31a90462018-02-26 16:02:45 +00001220 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001221 Value *X, *Y;
Sanjay Patel91bb7752018-02-16 17:52:32 +00001222 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1223 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1224 // (X / Y) / Z => X / (Y * Z)
Sanjay Patel31a90462018-02-26 16:02:45 +00001225 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001226 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001227 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001228 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1229 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1230 // Z / (X / Y) => (Y * Z) / X
Sanjay Patel31a90462018-02-26 16:02:45 +00001231 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001232 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001233 }
1234 }
1235
Sanjay Patel339b4d32018-02-15 15:07:12 +00001236 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001237 // sin(X) / cos(X) -> tan(X)
1238 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1239 Value *X;
1240 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1241 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1242 bool IsCot =
1243 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1244 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001245
Sanjay Patel65da14d2018-02-16 16:13:20 +00001246 if ((IsTan || IsCot) && hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1247 LibFunc_tanf, LibFunc_tanl)) {
1248 IRBuilder<> B(&I);
1249 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1250 B.setFastMathFlags(I.getFastMathFlags());
1251 AttributeList Attrs = CallSite(Op0).getCalledFunction()->getAttributes();
1252 Value *Res = emitUnaryFloatFnCall(X, TLI.getName(LibFunc_tan), B, Attrs);
1253 if (IsCot)
1254 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1255 return replaceInstUsesWith(I, Res);
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001256 }
1257 }
1258
Sanjay Patel1998cc62018-02-12 18:38:35 +00001259 // -X / -Y -> X / Y
1260 Value *X, *Y;
1261 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
1262 I.setOperand(0, X);
1263 I.setOperand(1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001264 return &I;
1265 }
1266
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001267 // X / (X * Y) --> 1.0 / Y
1268 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1269 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1270 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1271 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1272 I.setOperand(0, ConstantFP::get(I.getType(), 1.0));
1273 I.setOperand(1, Y);
1274 return &I;
1275 }
1276
Craig Topperf40110f2014-04-25 05:29:35 +00001277 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001278}
1279
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001280/// This function implements the transforms common to both integer remainder
1281/// instructions (urem and srem). It is called by the visitors to those integer
1282/// remainder instructions.
1283/// @brief Common integer remainder transforms
1284Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1286
Chris Lattner7c99f192011-05-22 18:18:41 +00001287 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001288 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001289 I.setOperand(1, V);
1290 return &I;
1291 }
1292
Duncan Sandsa3e36992011-05-02 16:27:02 +00001293 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001294 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001295 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001296
Benjamin Kramer72196f32014-01-19 15:24:22 +00001297 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001298 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1299 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1300 if (Instruction *R = FoldOpIntoSelect(I, SI))
1301 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001302 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001303 const APInt *Op1Int;
1304 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1305 (I.getOpcode() == Instruction::URem ||
1306 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001307 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001308 // predecessor blocks, so do this only if we know the srem or urem
1309 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001310 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001311 return NV;
1312 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001313 }
1314
1315 // See if we can fold away this rem instruction.
1316 if (SimplifyDemandedInstructionBits(I))
1317 return &I;
1318 }
1319 }
1320
Craig Topperf40110f2014-04-25 05:29:35 +00001321 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001322}
1323
1324Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1325 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1326
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001327 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001329
Craig Toppera4205622017-06-09 03:21:29 +00001330 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001331 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001332
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001333 if (Instruction *common = commonIRemTransforms(I))
1334 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001335
Sanjay Patelbb789382017-08-24 22:54:01 +00001336 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1337 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001338
David Majnemer470b0772013-05-11 09:01:28 +00001339 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001340 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001341 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001342 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001343 return BinaryOperator::CreateAnd(Op0, Add);
1344 }
1345
Nick Lewycky7459be62013-07-13 01:16:47 +00001346 // 1 urem X -> zext(X != 1)
1347 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001348 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1349 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001350 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001351 }
1352
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001353 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001354 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001355 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1356 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001357 return SelectInst::Create(Cmp, Op0, Sub);
1358 }
1359
Craig Topperf40110f2014-04-25 05:29:35 +00001360 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001361}
1362
1363Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1364 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1365
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001366 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001367 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001368
Craig Toppera4205622017-06-09 03:21:29 +00001369 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001370 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001371
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001372 // Handle the integer rem common cases
1373 if (Instruction *Common = commonIRemTransforms(I))
1374 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001375
David Majnemerdb077302014-10-13 22:37:51 +00001376 {
1377 const APInt *Y;
1378 // X % -Y -> X % Y
Simon Pilgrima54e8e42018-02-08 19:00:45 +00001379 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001380 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001381 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001382 return &I;
1383 }
David Majnemerdb077302014-10-13 22:37:51 +00001384 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001385
1386 // If the sign bits of both operands are zero (i.e. we can prove they are
1387 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001388 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001389 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1390 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1391 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1392 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001393 }
1394
1395 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001396 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1397 Constant *C = cast<Constant>(Op1);
1398 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001399
1400 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001401 bool hasMissing = false;
1402 for (unsigned i = 0; i != VWidth; ++i) {
1403 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001404 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001405 hasMissing = true;
1406 break;
1407 }
1408
1409 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001410 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001411 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001412 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001413
Chris Lattner0256be92012-01-27 03:08:05 +00001414 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001415 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001416 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001417 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001418 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001419 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001420 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001421 }
1422 }
1423
1424 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001425 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001426 Worklist.AddValue(I.getOperand(1));
1427 I.setOperand(1, NewRHSV);
1428 return &I;
1429 }
1430 }
1431 }
1432
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001434}
1435
1436Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001438
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001439 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001440 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001441
Craig Toppera4205622017-06-09 03:21:29 +00001442 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1443 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001444 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001445
Craig Topperf40110f2014-04-25 05:29:35 +00001446 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001447}