1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10 // srem, urem, frem.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
35 #include "llvm/Transforms/Utils/BuildLibCalls.h"
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <utility>
40
41 using namespace llvm;
42 using namespace PatternMatch;
43
44 #define DEBUG_TYPE "instcombine"
45
46 /// The specific integer value is used in a context where it is known to be
47 /// non-zero. If this allows us to simplify the computation, do so and return
48 /// the new operand, otherwise return null.
simplifyValueKnownNonZero(Value * V,InstCombiner & IC,Instruction & CxtI)49 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
50 Instruction &CxtI) {
51 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
54 if (!V->hasOneUse()) return nullptr;
55
56 bool MadeChange = false;
57
58 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
60 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
63 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
65 }
66
67 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
69 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
70 if (I && I->isLogicalShift() &&
71 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
72 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
75 IC.replaceOperand(*I, 0, V2);
76 MadeChange = true;
77 }
78
79 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
80 I->setIsExact();
81 MadeChange = true;
82 }
83
84 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
85 I->setHasNoUnsignedWrap();
86 MadeChange = true;
87 }
88 }
89
90 // TODO: Lots more we could do here:
91 // If V is a phi node, we can call this on each of its operands.
92 // "select cond, X, 0" can simplify to "X".
93
94 return MadeChange ? V : nullptr;
95 }
96
97 /// A helper routine of InstCombiner::visitMul().
98 ///
99 /// If C is a scalar/fixed width vector of known powers of 2, then this
100 /// function returns a new scalar/fixed width vector obtained from logBase2
101 /// of C.
102 /// Return a null pointer otherwise.
getLogBase2(Type * Ty,Constant * C)103 static Constant *getLogBase2(Type *Ty, Constant *C) {
104 const APInt *IVal;
105 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
106 return ConstantInt::get(Ty, IVal->logBase2());
107
108 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
109 if (!isa<FixedVectorType>(Ty))
110 return nullptr;
111
112 SmallVector<Constant *, 4> Elts;
113 for (unsigned I = 0, E = cast<FixedVectorType>(Ty)->getNumElements(); I != E;
114 ++I) {
115 Constant *Elt = C->getAggregateElement(I);
116 if (!Elt)
117 return nullptr;
118 if (isa<UndefValue>(Elt)) {
119 Elts.push_back(UndefValue::get(Ty->getScalarType()));
120 continue;
121 }
122 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
123 return nullptr;
124 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
125 }
126
127 return ConstantVector::get(Elts);
128 }
129
130 // TODO: This is a specific form of a much more general pattern.
131 // We could detect a select with any binop identity constant, or we
132 // could use SimplifyBinOp to see if either arm of the select reduces.
133 // But that needs to be done carefully and/or while removing potential
134 // reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
foldMulSelectToNegate(BinaryOperator & I,InstCombiner::BuilderTy & Builder)135 static Value *foldMulSelectToNegate(BinaryOperator &I,
136 InstCombiner::BuilderTy &Builder) {
137 Value *Cond, *OtherOp;
138
139 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
140 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
141 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())),
142 m_Value(OtherOp))))
143 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp));
144
145 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
146 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
147 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())),
148 m_Value(OtherOp))))
149 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp);
150
151 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
152 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
153 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0),
154 m_SpecificFP(-1.0))),
155 m_Value(OtherOp)))) {
156 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
157 Builder.setFastMathFlags(I.getFastMathFlags());
158 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
159 }
160
161 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
162 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
163 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0),
164 m_SpecificFP(1.0))),
165 m_Value(OtherOp)))) {
166 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
167 Builder.setFastMathFlags(I.getFastMathFlags());
168 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
169 }
170
171 return nullptr;
172 }
173
visitMul(BinaryOperator & I)174 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
175 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
176 SQ.getWithInstruction(&I)))
177 return replaceInstUsesWith(I, V);
178
179 if (SimplifyAssociativeOrCommutative(I))
180 return &I;
181
182 if (Instruction *X = foldVectorBinop(I))
183 return X;
184
185 if (Value *V = SimplifyUsingDistributiveLaws(I))
186 return replaceInstUsesWith(I, V);
187
188 // X * -1 == 0 - X
189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
190 if (match(Op1, m_AllOnes())) {
191 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
192 if (I.hasNoSignedWrap())
193 BO->setHasNoSignedWrap();
194 return BO;
195 }
196
197 // Also allow combining multiply instructions on vectors.
198 {
199 Value *NewOp;
200 Constant *C1, *C2;
201 const APInt *IVal;
202 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
203 m_Constant(C1))) &&
204 match(C1, m_APInt(IVal))) {
205 // ((X << C2)*C1) == (X * (C1 << C2))
206 Constant *Shl = ConstantExpr::getShl(C1, C2);
207 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
208 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
209 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
210 BO->setHasNoUnsignedWrap();
211 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
212 Shl->isNotMinSignedValue())
213 BO->setHasNoSignedWrap();
214 return BO;
215 }
216
217 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
218 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
219 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
220 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
221
222 if (I.hasNoUnsignedWrap())
223 Shl->setHasNoUnsignedWrap();
224 if (I.hasNoSignedWrap()) {
225 const APInt *V;
226 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
227 Shl->setHasNoSignedWrap();
228 }
229
230 return Shl;
231 }
232 }
233 }
234
235 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
236 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
237 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
238 // The "* (2**n)" thus becomes a potential shifting opportunity.
239 {
240 const APInt & Val = CI->getValue();
241 const APInt &PosVal = Val.abs();
242 if (Val.isNegative() && PosVal.isPowerOf2()) {
243 Value *X = nullptr, *Y = nullptr;
244 if (Op0->hasOneUse()) {
245 ConstantInt *C1;
246 Value *Sub = nullptr;
247 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
248 Sub = Builder.CreateSub(X, Y, "suba");
249 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
250 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
251 if (Sub)
252 return
253 BinaryOperator::CreateMul(Sub,
254 ConstantInt::get(Y->getType(), PosVal));
255 }
256 }
257 }
258 }
259
260 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
261 return FoldedMul;
262
263 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
264 return replaceInstUsesWith(I, FoldedMul);
265
266 // Simplify mul instructions with a constant RHS.
267 if (isa<Constant>(Op1)) {
268 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
269 Value *X;
270 Constant *C1;
271 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
272 Value *Mul = Builder.CreateMul(C1, Op1);
273 // Only go forward with the transform if C1*CI simplifies to a tidier
274 // constant.
275 if (!match(Mul, m_Mul(m_Value(), m_Value())))
276 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
277 }
278 }
279
280 // abs(X) * abs(X) -> X * X
281 // nabs(X) * nabs(X) -> X * X
282 if (Op0 == Op1) {
283 Value *X, *Y;
284 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
285 if (SPF == SPF_ABS || SPF == SPF_NABS)
286 return BinaryOperator::CreateMul(X, X);
287 }
288
289 // -X * C --> X * -C
290 Value *X, *Y;
291 Constant *Op1C;
292 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
293 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
294
295 // -X * -Y --> X * Y
296 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
297 auto *NewMul = BinaryOperator::CreateMul(X, Y);
298 if (I.hasNoSignedWrap() &&
299 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
300 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
301 NewMul->setHasNoSignedWrap();
302 return NewMul;
303 }
304
305 // -X * Y --> -(X * Y)
306 // X * -Y --> -(X * Y)
307 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))
308 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
309
310 // (X / Y) * Y = X - (X % Y)
311 // (X / Y) * -Y = (X % Y) - X
312 {
313 Value *Y = Op1;
314 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
315 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
316 Div->getOpcode() != Instruction::SDiv)) {
317 Y = Op0;
318 Div = dyn_cast<BinaryOperator>(Op1);
319 }
320 Value *Neg = dyn_castNegVal(Y);
321 if (Div && Div->hasOneUse() &&
322 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
323 (Div->getOpcode() == Instruction::UDiv ||
324 Div->getOpcode() == Instruction::SDiv)) {
325 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
326
327 // If the division is exact, X % Y is zero, so we end up with X or -X.
328 if (Div->isExact()) {
329 if (DivOp1 == Y)
330 return replaceInstUsesWith(I, X);
331 return BinaryOperator::CreateNeg(X);
332 }
333
334 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
335 : Instruction::SRem;
336 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
337 if (DivOp1 == Y)
338 return BinaryOperator::CreateSub(X, Rem);
339 return BinaryOperator::CreateSub(Rem, X);
340 }
341 }
342
343 /// i1 mul -> i1 and.
344 if (I.getType()->isIntOrIntVectorTy(1))
345 return BinaryOperator::CreateAnd(Op0, Op1);
346
347 // X*(1 << Y) --> X << Y
348 // (1 << Y)*X --> X << Y
349 {
350 Value *Y;
351 BinaryOperator *BO = nullptr;
352 bool ShlNSW = false;
353 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
354 BO = BinaryOperator::CreateShl(Op1, Y);
355 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
356 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
357 BO = BinaryOperator::CreateShl(Op0, Y);
358 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
359 }
360 if (BO) {
361 if (I.hasNoUnsignedWrap())
362 BO->setHasNoUnsignedWrap();
363 if (I.hasNoSignedWrap() && ShlNSW)
364 BO->setHasNoSignedWrap();
365 return BO;
366 }
367 }
368
369 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
370 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
371 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
372 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
373 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
374 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
375 (Op0->hasOneUse() || Op1->hasOneUse())) {
376 Value *And = Builder.CreateAnd(X, Y, "mulbool");
377 return CastInst::Create(Instruction::ZExt, And, I.getType());
378 }
379 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
380 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
381 // Note: -1 * 1 == 1 * -1 == -1
382 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
383 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
384 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
385 (Op0->hasOneUse() || Op1->hasOneUse())) {
386 Value *And = Builder.CreateAnd(X, Y, "mulbool");
387 return CastInst::Create(Instruction::SExt, And, I.getType());
388 }
389
390 // (bool X) * Y --> X ? Y : 0
391 // Y * (bool X) --> X ? Y : 0
392 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
393 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
394 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
395 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
396
397 // (lshr X, 31) * Y --> (ashr X, 31) & Y
398 // Y * (lshr X, 31) --> (ashr X, 31) & Y
399 // TODO: We are not checking one-use because the elimination of the multiply
400 // is better for analysis?
401 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
402 // more similar to what we're doing above.
403 const APInt *C;
404 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
405 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
406 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
407 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
408
409 if (Instruction *Ext = narrowMathIfNoOverflow(I))
410 return Ext;
411
412 bool Changed = false;
413 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
414 Changed = true;
415 I.setHasNoSignedWrap(true);
416 }
417
418 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
419 Changed = true;
420 I.setHasNoUnsignedWrap(true);
421 }
422
423 return Changed ? &I : nullptr;
424 }
425
foldFPSignBitOps(BinaryOperator & I)426 Instruction *InstCombiner::foldFPSignBitOps(BinaryOperator &I) {
427 BinaryOperator::BinaryOps Opcode = I.getOpcode();
428 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
429 "Expected fmul or fdiv");
430
431 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
432 Value *X, *Y;
433
434 // -X * -Y --> X * Y
435 // -X / -Y --> X / Y
436 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
437 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
438
439 // fabs(X) * fabs(X) -> X * X
440 // fabs(X) / fabs(X) -> X / X
441 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
442 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
443
444 // fabs(X) * fabs(Y) --> fabs(X * Y)
445 // fabs(X) / fabs(Y) --> fabs(X / Y)
446 if (match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))) &&
447 match(Op1, m_Intrinsic<Intrinsic::fabs>(m_Value(Y))) &&
448 (Op0->hasOneUse() || Op1->hasOneUse())) {
449 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
450 Builder.setFastMathFlags(I.getFastMathFlags());
451 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
452 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
453 Fabs->takeName(&I);
454 return replaceInstUsesWith(I, Fabs);
455 }
456
457 return nullptr;
458 }
459
visitFMul(BinaryOperator & I)460 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
461 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
462 I.getFastMathFlags(),
463 SQ.getWithInstruction(&I)))
464 return replaceInstUsesWith(I, V);
465
466 if (SimplifyAssociativeOrCommutative(I))
467 return &I;
468
469 if (Instruction *X = foldVectorBinop(I))
470 return X;
471
472 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
473 return FoldedMul;
474
475 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
476 return replaceInstUsesWith(I, FoldedMul);
477
478 if (Instruction *R = foldFPSignBitOps(I))
479 return R;
480
481 // X * -1.0 --> -X
482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
483 if (match(Op1, m_SpecificFP(-1.0)))
484 return UnaryOperator::CreateFNegFMF(Op0, &I);
485
486 // -X * C --> X * -C
487 Value *X, *Y;
488 Constant *C;
489 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
490 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
491
492 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
493 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
494 return replaceInstUsesWith(I, V);
495
496 if (I.hasAllowReassoc()) {
497 // Reassociate constant RHS with another constant to form constant
498 // expression.
499 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
500 Constant *C1;
501 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
502 // (C1 / X) * C --> (C * C1) / X
503 Constant *CC1 = ConstantExpr::getFMul(C, C1);
504 if (CC1->isNormalFP())
505 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
506 }
507 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
508 // (X / C1) * C --> X * (C / C1)
509 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
510 if (CDivC1->isNormalFP())
511 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
512
513 // If the constant was a denormal, try reassociating differently.
514 // (X / C1) * C --> X / (C1 / C)
515 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
516 if (Op0->hasOneUse() && C1DivC->isNormalFP())
517 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
518 }
519
520 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
521 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
522 // further folds and (X * C) + C2 is 'fma'.
523 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
524 // (X + C1) * C --> (X * C) + (C * C1)
525 Constant *CC1 = ConstantExpr::getFMul(C, C1);
526 Value *XC = Builder.CreateFMulFMF(X, C, &I);
527 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
528 }
529 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
530 // (C1 - X) * C --> (C * C1) - (X * C)
531 Constant *CC1 = ConstantExpr::getFMul(C, C1);
532 Value *XC = Builder.CreateFMulFMF(X, C, &I);
533 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
534 }
535 }
536
537 Value *Z;
538 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))),
539 m_Value(Z)))) {
540 // Sink division: (X / Y) * Z --> (X * Z) / Y
541 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
542 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
543 }
544
545 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
546 // nnan disallows the possibility of returning a number if both operands are
547 // negative (in that case, we should return NaN).
548 if (I.hasNoNaNs() &&
549 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
550 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
551 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
552 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
553 return replaceInstUsesWith(I, Sqrt);
554 }
555
556 // Like the similar transform in instsimplify, this requires 'nsz' because
557 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
558 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
559 Op0->hasNUses(2)) {
560 // Peek through fdiv to find squaring of square root:
561 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
562 if (match(Op0, m_FDiv(m_Value(X),
563 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
564 Value *XX = Builder.CreateFMulFMF(X, X, &I);
565 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
566 }
567 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
568 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)),
569 m_Value(X)))) {
570 Value *XX = Builder.CreateFMulFMF(X, X, &I);
571 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
572 }
573 }
574
575 // exp(X) * exp(Y) -> exp(X + Y)
576 // Match as long as at least one of exp has only one use.
577 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
578 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) &&
579 (Op0->hasOneUse() || Op1->hasOneUse())) {
580 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
581 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
582 return replaceInstUsesWith(I, Exp);
583 }
584
585 // exp2(X) * exp2(Y) -> exp2(X + Y)
586 // Match as long as at least one of exp2 has only one use.
587 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
588 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) &&
589 (Op0->hasOneUse() || Op1->hasOneUse())) {
590 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
591 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
592 return replaceInstUsesWith(I, Exp2);
593 }
594
595 // (X*Y) * X => (X*X) * Y where Y != X
596 // The purpose is two-fold:
597 // 1) to form a power expression (of X).
598 // 2) potentially shorten the critical path: After transformation, the
599 // latency of the instruction Y is amortized by the expression of X*X,
600 // and therefore Y is in a "less critical" position compared to what it
601 // was before the transformation.
602 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
603 Op1 != Y) {
604 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
605 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
606 }
607 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
608 Op0 != Y) {
609 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
610 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
611 }
612 }
613
614 // log2(X * 0.5) * Y = log2(X) * Y - Y
615 if (I.isFast()) {
616 IntrinsicInst *Log2 = nullptr;
617 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
618 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
619 Log2 = cast<IntrinsicInst>(Op0);
620 Y = Op1;
621 }
622 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
623 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
624 Log2 = cast<IntrinsicInst>(Op1);
625 Y = Op0;
626 }
627 if (Log2) {
628 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
629 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
630 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
631 }
632 }
633
634 return nullptr;
635 }
636
637 /// Fold a divide or remainder with a select instruction divisor when one of the
638 /// select operands is zero. In that case, we can use the other select operand
639 /// because div/rem by zero is undefined.
simplifyDivRemOfSelectWithZeroOp(BinaryOperator & I)640 bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
641 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
642 if (!SI)
643 return false;
644
645 int NonNullOperand;
646 if (match(SI->getTrueValue(), m_Zero()))
647 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
648 NonNullOperand = 2;
649 else if (match(SI->getFalseValue(), m_Zero()))
650 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
651 NonNullOperand = 1;
652 else
653 return false;
654
655 // Change the div/rem to use 'Y' instead of the select.
656 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
657
658 // Okay, we know we replace the operand of the div/rem with 'Y' with no
659 // problem. However, the select, or the condition of the select may have
660 // multiple uses. Based on our knowledge that the operand must be non-zero,
661 // propagate the known value for the select into other uses of it, and
662 // propagate a known value of the condition into its other users.
663
664 // If the select and condition only have a single use, don't bother with this,
665 // early exit.
666 Value *SelectCond = SI->getCondition();
667 if (SI->use_empty() && SelectCond->hasOneUse())
668 return true;
669
670 // Scan the current block backward, looking for other uses of SI.
671 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
672 Type *CondTy = SelectCond->getType();
673 while (BBI != BBFront) {
674 --BBI;
675 // If we found an instruction that we can't assume will return, so
676 // information from below it cannot be propagated above it.
677 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
678 break;
679
680 // Replace uses of the select or its condition with the known values.
681 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
682 I != E; ++I) {
683 if (*I == SI) {
684 replaceUse(*I, SI->getOperand(NonNullOperand));
685 Worklist.push(&*BBI);
686 } else if (*I == SelectCond) {
687 replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
688 : ConstantInt::getFalse(CondTy));
689 Worklist.push(&*BBI);
690 }
691 }
692
693 // If we past the instruction, quit looking for it.
694 if (&*BBI == SI)
695 SI = nullptr;
696 if (&*BBI == SelectCond)
697 SelectCond = nullptr;
698
699 // If we ran out of things to eliminate, break out of the loop.
700 if (!SelectCond && !SI)
701 break;
702
703 }
704 return true;
705 }
706
707 /// True if the multiply can not be expressed in an int this size.
multiplyOverflows(const APInt & C1,const APInt & C2,APInt & Product,bool IsSigned)708 static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
709 bool IsSigned) {
710 bool Overflow;
711 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
712 return Overflow;
713 }
714
715 /// True if C1 is a multiple of C2. Quotient contains C1/C2.
isMultiple(const APInt & C1,const APInt & C2,APInt & Quotient,bool IsSigned)716 static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
717 bool IsSigned) {
718 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
719
720 // Bail if we will divide by zero.
721 if (C2.isNullValue())
722 return false;
723
724 // Bail if we would divide INT_MIN by -1.
725 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
726 return false;
727
728 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
729 if (IsSigned)
730 APInt::sdivrem(C1, C2, Quotient, Remainder);
731 else
732 APInt::udivrem(C1, C2, Quotient, Remainder);
733
734 return Remainder.isMinValue();
735 }
736
737 /// This function implements the transforms common to both integer division
738 /// instructions (udiv and sdiv). It is called by the visitors to those integer
739 /// division instructions.
740 /// Common integer divide transforms
commonIDivTransforms(BinaryOperator & I)741 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
743 bool IsSigned = I.getOpcode() == Instruction::SDiv;
744 Type *Ty = I.getType();
745
746 // The RHS is known non-zero.
747 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
748 return replaceOperand(I, 1, V);
749
750 // Handle cases involving: [su]div X, (select Cond, Y, Z)
751 // This does not apply for fdiv.
752 if (simplifyDivRemOfSelectWithZeroOp(I))
753 return &I;
754
755 const APInt *C2;
756 if (match(Op1, m_APInt(C2))) {
757 Value *X;
758 const APInt *C1;
759
760 // (X / C1) / C2 -> X / (C1*C2)
761 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
762 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
763 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
764 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
765 return BinaryOperator::Create(I.getOpcode(), X,
766 ConstantInt::get(Ty, Product));
767 }
768
769 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
770 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
771 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
772
773 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
774 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
775 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
776 ConstantInt::get(Ty, Quotient));
777 NewDiv->setIsExact(I.isExact());
778 return NewDiv;
779 }
780
781 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
782 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
783 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
784 ConstantInt::get(Ty, Quotient));
785 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
786 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
787 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
788 return Mul;
789 }
790 }
791
792 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
793 *C1 != C1->getBitWidth() - 1) ||
794 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
795 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
796 APInt C1Shifted = APInt::getOneBitSet(
797 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
798
799 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
800 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
801 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
802 ConstantInt::get(Ty, Quotient));
803 BO->setIsExact(I.isExact());
804 return BO;
805 }
806
807 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
808 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
809 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
810 ConstantInt::get(Ty, Quotient));
811 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
812 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
813 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
814 return Mul;
815 }
816 }
817
818 if (!C2->isNullValue()) // avoid X udiv 0
819 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
820 return FoldedDiv;
821 }
822
823 if (match(Op0, m_One())) {
824 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
825 if (IsSigned) {
826 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
827 // result is one, if Op1 is -1 then the result is minus one, otherwise
828 // it's zero.
829 Value *Inc = Builder.CreateAdd(Op1, Op0);
830 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
831 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
832 } else {
833 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
834 // result is one, otherwise it's zero.
835 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
836 }
837 }
838
839 // See if we can fold away this div instruction.
840 if (SimplifyDemandedInstructionBits(I))
841 return &I;
842
843 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
844 Value *X, *Z;
845 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
846 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
847 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
848 return BinaryOperator::Create(I.getOpcode(), X, Op1);
849
850 // (X << Y) / X -> 1 << Y
851 Value *Y;
852 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
853 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
854 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
855 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
856
857 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
858 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
859 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
860 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
861 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
862 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
863 replaceOperand(I, 1, Y);
864 return &I;
865 }
866 }
867
868 return nullptr;
869 }
870
871 static const unsigned MaxDepth = 6;
872
873 namespace {
874
875 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
876 const BinaryOperator &I,
877 InstCombiner &IC);
878
879 /// Used to maintain state for visitUDivOperand().
880 struct UDivFoldAction {
881 /// Informs visitUDiv() how to fold this operand. This can be zero if this
882 /// action joins two actions together.
883 FoldUDivOperandCb FoldAction;
884
885 /// Which operand to fold.
886 Value *OperandToFold;
887
888 union {
889 /// The instruction returned when FoldAction is invoked.
890 Instruction *FoldResult;
891
892 /// Stores the LHS action index if this action joins two actions together.
893 size_t SelectLHSIdx;
894 };
895
UDivFoldAction__anon5dbe3a360111::UDivFoldAction896 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
897 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
UDivFoldAction__anon5dbe3a360111::UDivFoldAction898 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
899 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
900 };
901
902 } // end anonymous namespace
903
904 // X udiv 2^C -> X >> C
foldUDivPow2Cst(Value * Op0,Value * Op1,const BinaryOperator & I,InstCombiner & IC)905 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
906 const BinaryOperator &I, InstCombiner &IC) {
907 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
908 if (!C1)
909 llvm_unreachable("Failed to constant fold udiv -> logbase2");
910 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
911 if (I.isExact())
912 LShr->setIsExact();
913 return LShr;
914 }
915
916 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
917 // X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
foldUDivShl(Value * Op0,Value * Op1,const BinaryOperator & I,InstCombiner & IC)918 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
919 InstCombiner &IC) {
920 Value *ShiftLeft;
921 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
922 ShiftLeft = Op1;
923
924 Constant *CI;
925 Value *N;
926 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
927 llvm_unreachable("match should never fail here!");
928 Constant *Log2Base = getLogBase2(N->getType(), CI);
929 if (!Log2Base)
930 llvm_unreachable("getLogBase2 should never fail here!");
931 N = IC.Builder.CreateAdd(N, Log2Base);
932 if (Op1 != ShiftLeft)
933 N = IC.Builder.CreateZExt(N, Op1->getType());
934 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
935 if (I.isExact())
936 LShr->setIsExact();
937 return LShr;
938 }
939
940 // Recursively visits the possible right hand operands of a udiv
941 // instruction, seeing through select instructions, to determine if we can
942 // replace the udiv with something simpler. If we find that an operand is not
943 // able to simplify the udiv, we abort the entire transformation.
visitUDivOperand(Value * Op0,Value * Op1,const BinaryOperator & I,SmallVectorImpl<UDivFoldAction> & Actions,unsigned Depth=0)944 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
945 SmallVectorImpl<UDivFoldAction> &Actions,
946 unsigned Depth = 0) {
947 // Check to see if this is an unsigned division with an exact power of 2,
948 // if so, convert to a right shift.
949 if (match(Op1, m_Power2())) {
950 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
951 return Actions.size();
952 }
953
954 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
955 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
956 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
957 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
958 return Actions.size();
959 }
960
961 // The remaining tests are all recursive, so bail out if we hit the limit.
962 if (Depth++ == MaxDepth)
963 return 0;
964
965 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
966 if (size_t LHSIdx =
967 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
968 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
969 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
970 return Actions.size();
971 }
972
973 return 0;
974 }
975
976 /// If we have zero-extended operands of an unsigned div or rem, we may be able
977 /// to narrow the operation (sink the zext below the math).
narrowUDivURem(BinaryOperator & I,InstCombiner::BuilderTy & Builder)978 static Instruction *narrowUDivURem(BinaryOperator &I,
979 InstCombiner::BuilderTy &Builder) {
980 Instruction::BinaryOps Opcode = I.getOpcode();
981 Value *N = I.getOperand(0);
982 Value *D = I.getOperand(1);
983 Type *Ty = I.getType();
984 Value *X, *Y;
985 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
986 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
987 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
988 // urem (zext X), (zext Y) --> zext (urem X, Y)
989 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
990 return new ZExtInst(NarrowOp, Ty);
991 }
992
993 Constant *C;
994 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
995 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
996 // If the constant is the same in the smaller type, use the narrow version.
997 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
998 if (ConstantExpr::getZExt(TruncC, Ty) != C)
999 return nullptr;
1000
1001 // udiv (zext X), C --> zext (udiv X, C')
1002 // urem (zext X), C --> zext (urem X, C')
1003 // udiv C, (zext X) --> zext (udiv C', X)
1004 // urem C, (zext X) --> zext (urem C', X)
1005 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1006 : Builder.CreateBinOp(Opcode, TruncC, X);
1007 return new ZExtInst(NarrowOp, Ty);
1008 }
1009
1010 return nullptr;
1011 }
1012
visitUDiv(BinaryOperator & I)1013 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1014 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
1015 SQ.getWithInstruction(&I)))
1016 return replaceInstUsesWith(I, V);
1017
1018 if (Instruction *X = foldVectorBinop(I))
1019 return X;
1020
1021 // Handle the integer div common cases
1022 if (Instruction *Common = commonIDivTransforms(I))
1023 return Common;
1024
1025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1026 Value *X;
1027 const APInt *C1, *C2;
1028 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1029 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1030 bool Overflow;
1031 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1032 if (!Overflow) {
1033 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1034 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1035 X, ConstantInt::get(X->getType(), C2ShlC1));
1036 if (IsExact)
1037 BO->setIsExact();
1038 return BO;
1039 }
1040 }
1041
1042 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1043 // TODO: Could use isKnownNegative() to handle non-constant values.
1044 Type *Ty = I.getType();
1045 if (match(Op1, m_Negative())) {
1046 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1047 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1048 }
1049 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1050 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1051 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1052 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1053 }
1054
1055 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1056 return NarrowDiv;
1057
1058 // If the udiv operands are non-overflowing multiplies with a common operand,
1059 // then eliminate the common factor:
1060 // (A * B) / (A * X) --> B / X (and commuted variants)
1061 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1062 // TODO: If -reassociation handled this generally, we could remove this.
1063 Value *A, *B;
1064 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1065 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1066 match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1067 return BinaryOperator::CreateUDiv(B, X);
1068 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1069 match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1070 return BinaryOperator::CreateUDiv(A, X);
1071 }
1072
1073 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1074 SmallVector<UDivFoldAction, 6> UDivActions;
1075 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1076 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1077 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1078 Value *ActionOp1 = UDivActions[i].OperandToFold;
1079 Instruction *Inst;
1080 if (Action)
1081 Inst = Action(Op0, ActionOp1, I, *this);
1082 else {
1083 // This action joins two actions together. The RHS of this action is
1084 // simply the last action we processed, we saved the LHS action index in
1085 // the joining action.
1086 size_t SelectRHSIdx = i - 1;
1087 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1088 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1089 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1090 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1091 SelectLHS, SelectRHS);
1092 }
1093
1094 // If this is the last action to process, return it to the InstCombiner.
1095 // Otherwise, we insert it before the UDiv and record it so that we may
1096 // use it as part of a joining action (i.e., a SelectInst).
1097 if (e - i != 1) {
1098 Inst->insertBefore(&I);
1099 UDivActions[i].FoldResult = Inst;
1100 } else
1101 return Inst;
1102 }
1103
1104 return nullptr;
1105 }
1106
visitSDiv(BinaryOperator & I)1107 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1108 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1109 SQ.getWithInstruction(&I)))
1110 return replaceInstUsesWith(I, V);
1111
1112 if (Instruction *X = foldVectorBinop(I))
1113 return X;
1114
1115 // Handle the integer div common cases
1116 if (Instruction *Common = commonIDivTransforms(I))
1117 return Common;
1118
1119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1120 Value *X;
1121 // sdiv Op0, -1 --> -Op0
1122 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1123 if (match(Op1, m_AllOnes()) ||
1124 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1125 return BinaryOperator::CreateNeg(Op0);
1126
1127 // X / INT_MIN --> X == INT_MIN
1128 if (match(Op1, m_SignMask()))
1129 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1130
1131 const APInt *Op1C;
1132 if (match(Op1, m_APInt(Op1C))) {
1133 // sdiv exact X, C --> ashr exact X, log2(C)
1134 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1135 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1136 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1137 }
1138
1139 // If the dividend is sign-extended and the constant divisor is small enough
1140 // to fit in the source type, shrink the division to the narrower type:
1141 // (sext X) sdiv C --> sext (X sdiv C)
1142 Value *Op0Src;
1143 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1144 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1145
1146 // In the general case, we need to make sure that the dividend is not the
1147 // minimum signed value because dividing that by -1 is UB. But here, we
1148 // know that the -1 divisor case is already handled above.
1149
1150 Constant *NarrowDivisor =
1151 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1152 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1153 return new SExtInst(NarrowOp, Op0->getType());
1154 }
1155
1156 // -X / C --> X / -C (if the negation doesn't overflow).
1157 // TODO: This could be enhanced to handle arbitrary vector constants by
1158 // checking if all elements are not the min-signed-val.
1159 if (!Op1C->isMinSignedValue() &&
1160 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1161 Constant *NegC = ConstantInt::get(I.getType(), -(*Op1C));
1162 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1163 BO->setIsExact(I.isExact());
1164 return BO;
1165 }
1166 }
1167
1168 // -X / Y --> -(X / Y)
1169 Value *Y;
1170 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1171 return BinaryOperator::CreateNSWNeg(
1172 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1173
1174 // If the sign bits of both operands are zero (i.e. we can prove they are
1175 // unsigned inputs), turn this into a udiv.
1176 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1177 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1178 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1179 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1180 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1181 BO->setIsExact(I.isExact());
1182 return BO;
1183 }
1184
1185 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1186 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1187 // Safe because the only negative value (1 << Y) can take on is
1188 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1189 // the sign bit set.
1190 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1191 BO->setIsExact(I.isExact());
1192 return BO;
1193 }
1194 }
1195
1196 return nullptr;
1197 }
1198
1199 /// Remove negation and try to convert division into multiplication.
foldFDivConstantDivisor(BinaryOperator & I)1200 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1201 Constant *C;
1202 if (!match(I.getOperand(1), m_Constant(C)))
1203 return nullptr;
1204
1205 // -X / C --> X / -C
1206 Value *X;
1207 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1208 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
1209
1210 // If the constant divisor has an exact inverse, this is always safe. If not,
1211 // then we can still create a reciprocal if fast-math-flags allow it and the
1212 // constant is a regular number (not zero, infinite, or denormal).
1213 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1214 return nullptr;
1215
1216 // Disallow denormal constants because we don't know what would happen
1217 // on all targets.
1218 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1219 // denorms are flushed?
1220 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1221 if (!RecipC->isNormalFP())
1222 return nullptr;
1223
1224 // X / C --> X * (1 / C)
1225 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1226 }
1227
1228 /// Remove negation and try to reassociate constant math.
foldFDivConstantDividend(BinaryOperator & I)1229 static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
1230 Constant *C;
1231 if (!match(I.getOperand(0), m_Constant(C)))
1232 return nullptr;
1233
1234 // C / -X --> -C / X
1235 Value *X;
1236 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1237 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
1238
1239 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1240 return nullptr;
1241
1242 // Try to reassociate C / X expressions where X includes another constant.
1243 Constant *C2, *NewC = nullptr;
1244 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1245 // C / (X * C2) --> (C / C2) / X
1246 NewC = ConstantExpr::getFDiv(C, C2);
1247 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1248 // C / (X / C2) --> (C * C2) / X
1249 NewC = ConstantExpr::getFMul(C, C2);
1250 }
1251 // Disallow denormal constants because we don't know what would happen
1252 // on all targets.
1253 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1254 // denorms are flushed?
1255 if (!NewC || !NewC->isNormalFP())
1256 return nullptr;
1257
1258 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1259 }
1260
visitFDiv(BinaryOperator & I)1261 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1262 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1263 I.getFastMathFlags(),
1264 SQ.getWithInstruction(&I)))
1265 return replaceInstUsesWith(I, V);
1266
1267 if (Instruction *X = foldVectorBinop(I))
1268 return X;
1269
1270 if (Instruction *R = foldFDivConstantDivisor(I))
1271 return R;
1272
1273 if (Instruction *R = foldFDivConstantDividend(I))
1274 return R;
1275
1276 if (Instruction *R = foldFPSignBitOps(I))
1277 return R;
1278
1279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1280 if (isa<Constant>(Op0))
1281 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1282 if (Instruction *R = FoldOpIntoSelect(I, SI))
1283 return R;
1284
1285 if (isa<Constant>(Op1))
1286 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1287 if (Instruction *R = FoldOpIntoSelect(I, SI))
1288 return R;
1289
1290 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1291 Value *X, *Y;
1292 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1293 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1294 // (X / Y) / Z => X / (Y * Z)
1295 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1296 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1297 }
1298 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1299 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1300 // Z / (X / Y) => (Y * Z) / X
1301 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1302 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1303 }
1304 // Z / (1.0 / Y) => (Y * Z)
1305 //
1306 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1307 // m_OneUse check is avoided because even in the case of the multiple uses
1308 // for 1.0/Y, the number of instructions remain the same and a division is
1309 // replaced by a multiplication.
1310 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1311 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1312 }
1313
1314 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1315 // sin(X) / cos(X) -> tan(X)
1316 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1317 Value *X;
1318 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1319 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1320 bool IsCot =
1321 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1322 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1323
1324 if ((IsTan || IsCot) &&
1325 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
1326 IRBuilder<> B(&I);
1327 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1328 B.setFastMathFlags(I.getFastMathFlags());
1329 AttributeList Attrs =
1330 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1331 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1332 LibFunc_tanl, B, Attrs);
1333 if (IsCot)
1334 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1335 return replaceInstUsesWith(I, Res);
1336 }
1337 }
1338
1339 // X / (X * Y) --> 1.0 / Y
1340 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1341 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1342 Value *X, *Y;
1343 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1344 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1345 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1346 replaceOperand(I, 1, Y);
1347 return &I;
1348 }
1349
1350 // X / fabs(X) -> copysign(1.0, X)
1351 // fabs(X) / X -> copysign(1.0, X)
1352 if (I.hasNoNaNs() && I.hasNoInfs() &&
1353 (match(&I,
1354 m_FDiv(m_Value(X), m_Intrinsic<Intrinsic::fabs>(m_Deferred(X)))) ||
1355 match(&I, m_FDiv(m_Intrinsic<Intrinsic::fabs>(m_Value(X)),
1356 m_Deferred(X))))) {
1357 Value *V = Builder.CreateBinaryIntrinsic(
1358 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1359 return replaceInstUsesWith(I, V);
1360 }
1361 return nullptr;
1362 }
1363
1364 /// This function implements the transforms common to both integer remainder
1365 /// instructions (urem and srem). It is called by the visitors to those integer
1366 /// remainder instructions.
1367 /// Common integer remainder transforms
commonIRemTransforms(BinaryOperator & I)1368 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1370
1371 // The RHS is known non-zero.
1372 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1373 return replaceOperand(I, 1, V);
1374
1375 // Handle cases involving: rem X, (select Cond, Y, Z)
1376 if (simplifyDivRemOfSelectWithZeroOp(I))
1377 return &I;
1378
1379 if (isa<Constant>(Op1)) {
1380 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1381 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1382 if (Instruction *R = FoldOpIntoSelect(I, SI))
1383 return R;
1384 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1385 const APInt *Op1Int;
1386 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1387 (I.getOpcode() == Instruction::URem ||
1388 !Op1Int->isMinSignedValue())) {
1389 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1390 // predecessor blocks, so do this only if we know the srem or urem
1391 // will not fault.
1392 if (Instruction *NV = foldOpIntoPhi(I, PN))
1393 return NV;
1394 }
1395 }
1396
1397 // See if we can fold away this rem instruction.
1398 if (SimplifyDemandedInstructionBits(I))
1399 return &I;
1400 }
1401 }
1402
1403 return nullptr;
1404 }
1405
visitURem(BinaryOperator & I)1406 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1407 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1408 SQ.getWithInstruction(&I)))
1409 return replaceInstUsesWith(I, V);
1410
1411 if (Instruction *X = foldVectorBinop(I))
1412 return X;
1413
1414 if (Instruction *common = commonIRemTransforms(I))
1415 return common;
1416
1417 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1418 return NarrowRem;
1419
1420 // X urem Y -> X and Y-1, where Y is a power of 2,
1421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1422 Type *Ty = I.getType();
1423 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1424 // This may increase instruction count, we don't enforce that Y is a
1425 // constant.
1426 Constant *N1 = Constant::getAllOnesValue(Ty);
1427 Value *Add = Builder.CreateAdd(Op1, N1);
1428 return BinaryOperator::CreateAnd(Op0, Add);
1429 }
1430
1431 // 1 urem X -> zext(X != 1)
1432 if (match(Op0, m_One())) {
1433 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1434 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1435 }
1436
1437 // X urem C -> X < C ? X : X - C, where C >= signbit.
1438 if (match(Op1, m_Negative())) {
1439 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1440 Value *Sub = Builder.CreateSub(Op0, Op1);
1441 return SelectInst::Create(Cmp, Op0, Sub);
1442 }
1443
1444 // If the divisor is a sext of a boolean, then the divisor must be max
1445 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1446 // max unsigned value. In that case, the remainder is 0:
1447 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1448 Value *X;
1449 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1450 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1451 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1452 }
1453
1454 return nullptr;
1455 }
1456
visitSRem(BinaryOperator & I)1457 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1458 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1459 SQ.getWithInstruction(&I)))
1460 return replaceInstUsesWith(I, V);
1461
1462 if (Instruction *X = foldVectorBinop(I))
1463 return X;
1464
1465 // Handle the integer rem common cases
1466 if (Instruction *Common = commonIRemTransforms(I))
1467 return Common;
1468
1469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1470 {
1471 const APInt *Y;
1472 // X % -Y -> X % Y
1473 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1474 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
1475 }
1476
1477 // -X srem Y --> -(X srem Y)
1478 Value *X, *Y;
1479 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1480 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1481
1482 // If the sign bits of both operands are zero (i.e. we can prove they are
1483 // unsigned inputs), turn this into a urem.
1484 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1485 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1486 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1487 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1488 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1489 }
1490
1491 // If it's a constant vector, flip any negative values positive.
1492 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1493 Constant *C = cast<Constant>(Op1);
1494 unsigned VWidth = cast<VectorType>(C->getType())->getNumElements();
1495
1496 bool hasNegative = false;
1497 bool hasMissing = false;
1498 for (unsigned i = 0; i != VWidth; ++i) {
1499 Constant *Elt = C->getAggregateElement(i);
1500 if (!Elt) {
1501 hasMissing = true;
1502 break;
1503 }
1504
1505 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1506 if (RHS->isNegative())
1507 hasNegative = true;
1508 }
1509
1510 if (hasNegative && !hasMissing) {
1511 SmallVector<Constant *, 16> Elts(VWidth);
1512 for (unsigned i = 0; i != VWidth; ++i) {
1513 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1515 if (RHS->isNegative())
1516 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1517 }
1518 }
1519
1520 Constant *NewRHSV = ConstantVector::get(Elts);
1521 if (NewRHSV != C) // Don't loop on -MININT
1522 return replaceOperand(I, 1, NewRHSV);
1523 }
1524 }
1525
1526 return nullptr;
1527 }
1528
visitFRem(BinaryOperator & I)1529 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1530 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1531 I.getFastMathFlags(),
1532 SQ.getWithInstruction(&I)))
1533 return replaceInstUsesWith(I, V);
1534
1535 if (Instruction *X = foldVectorBinop(I))
1536 return X;
1537
1538 return nullptr;
1539 }
1540