LLVM 19.0.0git
InstCombineMulDivRem.cpp
Go to the documentation of this file.
1//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
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"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
29#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
35#include <cassert>
36
37#define DEBUG_TYPE "instcombine"
39
40using namespace llvm;
41using namespace PatternMatch;
42
43/// The specific integer value is used in a context where it is known to be
44/// non-zero. If this allows us to simplify the computation, do so and return
45/// the new operand, otherwise return null.
47 Instruction &CxtI) {
48 // If V has multiple uses, then we would have to do more analysis to determine
49 // if this is safe. For example, the use could be in dynamically unreached
50 // code.
51 if (!V->hasOneUse()) return nullptr;
52
53 bool MadeChange = false;
54
55 // ((1 << A) >>u B) --> (1 << (A-B))
56 // Because V cannot be zero, we know that B is less than A.
57 Value *A = nullptr, *B = nullptr, *One = nullptr;
58 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
59 match(One, m_One())) {
60 A = IC.Builder.CreateSub(A, B);
61 return IC.Builder.CreateShl(One, A);
62 }
63
64 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
65 // inexact. Similarly for <<.
66 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
67 if (I && I->isLogicalShift() &&
68 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
69 // We know that this is an exact/nuw shift and that the input is a
70 // non-zero context as well.
71 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
72 IC.replaceOperand(*I, 0, V2);
73 MadeChange = true;
74 }
75
76 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
77 I->setIsExact();
78 MadeChange = true;
79 }
80
81 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
82 I->setHasNoUnsignedWrap();
83 MadeChange = true;
84 }
85 }
86
87 // TODO: Lots more we could do here:
88 // If V is a phi node, we can call this on each of its operands.
89 // "select cond, X, 0" can simplify to "X".
90
91 return MadeChange ? V : nullptr;
92}
93
94// TODO: This is a specific form of a much more general pattern.
95// We could detect a select with any binop identity constant, or we
96// could use SimplifyBinOp to see if either arm of the select reduces.
97// But that needs to be done carefully and/or while removing potential
98// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
100 InstCombiner::BuilderTy &Builder) {
101 Value *Cond, *OtherOp;
102
103 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
104 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
106 m_Value(OtherOp)))) {
107 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
108 Value *Neg = Builder.CreateNeg(OtherOp, "", false, HasAnyNoWrap);
109 return Builder.CreateSelect(Cond, OtherOp, Neg);
110 }
111 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
112 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
114 m_Value(OtherOp)))) {
115 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
116 Value *Neg = Builder.CreateNeg(OtherOp, "", false, HasAnyNoWrap);
117 return Builder.CreateSelect(Cond, Neg, OtherOp);
118 }
119
120 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
121 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
123 m_SpecificFP(-1.0))),
124 m_Value(OtherOp)))) {
125 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
126 Builder.setFastMathFlags(I.getFastMathFlags());
127 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
128 }
129
130 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
131 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
133 m_SpecificFP(1.0))),
134 m_Value(OtherOp)))) {
135 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
136 Builder.setFastMathFlags(I.getFastMathFlags());
137 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
138 }
139
140 return nullptr;
141}
142
143/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
144/// Callers are expected to call this twice to handle commuted patterns.
145static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
146 InstCombiner::BuilderTy &Builder) {
147 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
148 if (CommuteOperands)
149 std::swap(X, Y);
150
151 const bool HasNSW = Mul.hasNoSignedWrap();
152 const bool HasNUW = Mul.hasNoUnsignedWrap();
153
154 // X * (1 << Z) --> X << Z
155 Value *Z;
156 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
157 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
158 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
159 }
160
161 // Similar to above, but an increment of the shifted value becomes an add:
162 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
163 // This increases uses of X, so it may require a freeze, but that is still
164 // expected to be an improvement because it removes the multiply.
165 BinaryOperator *Shift;
166 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
167 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
168 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
169 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
170 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
171 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
172 }
173
174 // Similar to above, but a decrement of the shifted value is disguised as
175 // 'not' and becomes a sub:
176 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
177 // This increases uses of X, so it may require a freeze, but that is still
178 // expected to be an improvement because it removes the multiply.
180 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
181 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
182 return Builder.CreateSub(Shl, FrX, Mul.getName());
183 }
184
185 return nullptr;
186}
187
188static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
189 bool AssumeNonZero, bool DoFold);
190
192 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
193 if (Value *V =
194 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
196 return replaceInstUsesWith(I, V);
197
199 return &I;
200
202 return X;
203
205 return Phi;
206
208 return replaceInstUsesWith(I, V);
209
210 Type *Ty = I.getType();
211 const unsigned BitWidth = Ty->getScalarSizeInBits();
212 const bool HasNSW = I.hasNoSignedWrap();
213 const bool HasNUW = I.hasNoUnsignedWrap();
214
215 // X * -1 --> 0 - X
216 if (match(Op1, m_AllOnes())) {
217 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
219 }
220
221 // Also allow combining multiply instructions on vectors.
222 {
223 Value *NewOp;
224 Constant *C1, *C2;
225 const APInt *IVal;
226 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
227 m_Constant(C1))) &&
228 match(C1, m_APInt(IVal))) {
229 // ((X << C2)*C1) == (X * (C1 << C2))
230 Constant *Shl = ConstantExpr::getShl(C1, C2);
231 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
232 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
233 if (HasNUW && Mul->hasNoUnsignedWrap())
235 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
236 BO->setHasNoSignedWrap();
237 return BO;
238 }
239
240 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
241 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
242 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C1)) {
243 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
244
245 if (HasNUW)
247 if (HasNSW) {
248 const APInt *V;
249 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
250 Shl->setHasNoSignedWrap();
251 }
252
253 return Shl;
254 }
255 }
256 }
257
258 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
259 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
260 // The "* (1<<C)" thus becomes a potential shifting opportunity.
261 if (Value *NegOp0 =
262 Negator::Negate(/*IsNegation*/ true, HasNSW, Op0, *this)) {
263 auto *Op1C = cast<Constant>(Op1);
264 return replaceInstUsesWith(
265 I, Builder.CreateMul(NegOp0, ConstantExpr::getNeg(Op1C), "",
266 /* HasNUW */ false,
267 HasNSW && Op1C->isNotMinSignedValue()));
268 }
269
270 // Try to convert multiply of extended operand to narrow negate and shift
271 // for better analysis.
272 // This is valid if the shift amount (trailing zeros in the multiplier
273 // constant) clears more high bits than the bitwidth difference between
274 // source and destination types:
275 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
276 const APInt *NegPow2C;
277 Value *X;
278 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
279 match(Op1, m_APIntAllowUndef(NegPow2C))) {
280 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
281 unsigned ShiftAmt = NegPow2C->countr_zero();
282 if (ShiftAmt >= BitWidth - SrcWidth) {
283 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
284 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
285 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
286 }
287 }
288 }
289
290 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
291 return FoldedMul;
292
293 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
294 return replaceInstUsesWith(I, FoldedMul);
295
296 // Simplify mul instructions with a constant RHS.
297 Constant *MulC;
298 if (match(Op1, m_ImmConstant(MulC))) {
299 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
300 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
301 Value *X;
302 Constant *C1;
303 if (match(Op0, m_OneUse(m_AddLike(m_Value(X), m_ImmConstant(C1))))) {
304 // C1*MulC simplifies to a tidier constant.
305 Value *NewC = Builder.CreateMul(C1, MulC);
306 auto *BOp0 = cast<BinaryOperator>(Op0);
307 bool Op0NUW =
308 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
309 Value *NewMul = Builder.CreateMul(X, MulC);
310 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
311 if (HasNUW && Op0NUW) {
312 // If NewMulBO is constant we also can set BO to nuw.
313 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
314 NewMulBO->setHasNoUnsignedWrap();
315 BO->setHasNoUnsignedWrap();
316 }
317 return BO;
318 }
319 }
320
321 // abs(X) * abs(X) -> X * X
322 // nabs(X) * nabs(X) -> X * X
323 if (Op0 == Op1) {
324 Value *X, *Y;
326 if (SPF == SPF_ABS || SPF == SPF_NABS)
327 return BinaryOperator::CreateMul(X, X);
328
329 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
330 return BinaryOperator::CreateMul(X, X);
331 }
332
333 {
334 Value *X, *Y;
335 // abs(X) * abs(Y) -> abs(X * Y)
336 if (I.hasNoSignedWrap() &&
337 match(Op0,
338 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One()))) &&
339 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(Y), m_One()))))
340 return replaceInstUsesWith(
341 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
343 Builder.getTrue()));
344 }
345
346 // -X * C --> X * -C
347 Value *X, *Y;
348 Constant *Op1C;
349 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
350 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
351
352 // -X * -Y --> X * Y
353 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
354 auto *NewMul = BinaryOperator::CreateMul(X, Y);
355 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
356 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
357 NewMul->setHasNoSignedWrap();
358 return NewMul;
359 }
360
361 // -X * Y --> -(X * Y)
362 // X * -Y --> -(X * Y)
365
366 // (-X * Y) * -X --> (X * Y) * X
367 // (-X << Y) * -X --> (X << Y) * X
368 if (match(Op1, m_Neg(m_Value(X)))) {
369 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
370 return BinaryOperator::CreateMul(NegOp0, X);
371 }
372
373 // (X / Y) * Y = X - (X % Y)
374 // (X / Y) * -Y = (X % Y) - X
375 {
376 Value *Y = Op1;
377 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
378 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
379 Div->getOpcode() != Instruction::SDiv)) {
380 Y = Op0;
381 Div = dyn_cast<BinaryOperator>(Op1);
382 }
383 Value *Neg = dyn_castNegVal(Y);
384 if (Div && Div->hasOneUse() &&
385 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
386 (Div->getOpcode() == Instruction::UDiv ||
387 Div->getOpcode() == Instruction::SDiv)) {
388 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
389
390 // If the division is exact, X % Y is zero, so we end up with X or -X.
391 if (Div->isExact()) {
392 if (DivOp1 == Y)
393 return replaceInstUsesWith(I, X);
395 }
396
397 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
398 : Instruction::SRem;
399 // X must be frozen because we are increasing its number of uses.
400 Value *XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
401 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
402 if (DivOp1 == Y)
403 return BinaryOperator::CreateSub(XFreeze, Rem);
404 return BinaryOperator::CreateSub(Rem, XFreeze);
405 }
406 }
407
408 // Fold the following two scenarios:
409 // 1) i1 mul -> i1 and.
410 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
411 // Note: We could use known bits to generalize this and related patterns with
412 // shifts/truncs
413 if (Ty->isIntOrIntVectorTy(1) ||
414 (match(Op0, m_And(m_Value(), m_One())) &&
415 match(Op1, m_And(m_Value(), m_One()))))
416 return BinaryOperator::CreateAnd(Op0, Op1);
417
418 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
419 return replaceInstUsesWith(I, R);
420 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
421 return replaceInstUsesWith(I, R);
422
423 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
424 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
425 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
426 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
427 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
428 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
429 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
430 Value *And = Builder.CreateAnd(X, Y, "mulbool");
431 return CastInst::Create(Instruction::ZExt, And, Ty);
432 }
433 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
434 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
435 // Note: -1 * 1 == 1 * -1 == -1
436 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
437 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
438 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
439 (Op0->hasOneUse() || Op1->hasOneUse())) {
440 Value *And = Builder.CreateAnd(X, Y, "mulbool");
441 return CastInst::Create(Instruction::SExt, And, Ty);
442 }
443
444 // (zext bool X) * Y --> X ? Y : 0
445 // Y * (zext bool X) --> X ? Y : 0
446 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
448 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
450
451 // mul (sext X), Y -> select X, -Y, 0
452 // mul Y, (sext X) -> select X, -Y, 0
453 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
454 X->getType()->isIntOrIntVectorTy(1))
455 return SelectInst::Create(
456 X, Builder.CreateNeg(Y, "", /*HasNUW=*/false, I.hasNoSignedWrap()),
458
459 Constant *ImmC;
460 if (match(Op1, m_ImmConstant(ImmC))) {
461 // (sext bool X) * C --> X ? -C : 0
462 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
463 Constant *NegC = ConstantExpr::getNeg(ImmC);
465 }
466
467 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
468 const APInt *C;
469 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
470 *C == C->getBitWidth() - 1) {
471 Constant *NegC = ConstantExpr::getNeg(ImmC);
472 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
473 return SelectInst::Create(IsNeg, NegC, ConstantInt::getNullValue(Ty));
474 }
475 }
476
477 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
478 // TODO: We are not checking one-use because the elimination of the multiply
479 // is better for analysis?
480 const APInt *C;
481 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
482 *C == C->getBitWidth() - 1) {
483 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
485 }
486
487 // (and X, 1) * Y --> (trunc X) ? Y : 0
488 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
491 }
492
493 // ((ashr X, 31) | 1) * X --> abs(X)
494 // X * ((ashr X, 31) | 1) --> abs(X)
497 m_One()),
498 m_Deferred(X)))) {
500 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
501 Abs->takeName(&I);
502 return replaceInstUsesWith(I, Abs);
503 }
504
505 if (Instruction *Ext = narrowMathIfNoOverflow(I))
506 return Ext;
507
509 return Res;
510
511 // (mul Op0 Op1):
512 // if Log2(Op0) folds away ->
513 // (shl Op1, Log2(Op0))
514 // if Log2(Op1) folds away ->
515 // (shl Op0, Log2(Op1))
516 if (takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
517 /*DoFold*/ false)) {
518 Value *Res = takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
519 /*DoFold*/ true);
520 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
521 // We can only propegate nuw flag.
522 Shl->setHasNoUnsignedWrap(HasNUW);
523 return Shl;
524 }
525 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
526 /*DoFold*/ false)) {
527 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
528 /*DoFold*/ true);
529 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
530 // We can only propegate nuw flag.
531 Shl->setHasNoUnsignedWrap(HasNUW);
532 return Shl;
533 }
534
535 bool Changed = false;
536 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
537 Changed = true;
538 I.setHasNoSignedWrap(true);
539 }
540
541 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I)) {
542 Changed = true;
543 I.setHasNoUnsignedWrap(true);
544 }
545
546 return Changed ? &I : nullptr;
547}
548
549Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
550 BinaryOperator::BinaryOps Opcode = I.getOpcode();
551 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
552 "Expected fmul or fdiv");
553
554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
555 Value *X, *Y;
556
557 // -X * -Y --> X * Y
558 // -X / -Y --> X / Y
559 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
560 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
561
562 // fabs(X) * fabs(X) -> X * X
563 // fabs(X) / fabs(X) -> X / X
564 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
565 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
566
567 // fabs(X) * fabs(Y) --> fabs(X * Y)
568 // fabs(X) / fabs(Y) --> fabs(X / Y)
569 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
570 (Op0->hasOneUse() || Op1->hasOneUse())) {
572 Builder.setFastMathFlags(I.getFastMathFlags());
573 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
574 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
575 Fabs->takeName(&I);
576 return replaceInstUsesWith(I, Fabs);
577 }
578
579 return nullptr;
580}
581
583 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
584 Value *Y, Value *Z) {
585 InstCombiner::BuilderTy &Builder = IC.Builder;
586 Value *YZ = Builder.CreateAdd(Y, Z);
587 auto *NewPow = Builder.CreateIntrinsic(
588 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
589 return IC.replaceInstUsesWith(I, NewPow);
590 };
591
592 Value *X, *Y, *Z;
593
594 // powi(X, Y) * X --> powi(X, Y+1)
595 // X * powi(X, Y) --> powi(X, Y+1)
596 if (match(&I, m_c_FMul(m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
597 m_Value(X), m_Value(Y)))),
598 m_Deferred(X)))) {
599 Constant *One = ConstantInt::get(Y->getType(), 1);
600 if (willNotOverflowSignedAdd(Y, One, I))
601 return createPowiExpr(I, *this, X, Y, One);
602 }
603
604 // powi(x, y) * powi(x, z) -> powi(x, y + z)
605 Value *Op0 = I.getOperand(0);
606 Value *Op1 = I.getOperand(1);
607 if (I.isOnlyUserOfAnyOperand() &&
609 m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y)))) &&
610 match(Op1, m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(m_Specific(X),
611 m_Value(Z)))) &&
612 Y->getType() == Z->getType())
613 return createPowiExpr(I, *this, X, Y, Z);
614
615 return nullptr;
616}
617
619 Value *Op0 = I.getOperand(0);
620 Value *Op1 = I.getOperand(1);
621 Value *X, *Y;
622 Constant *C;
623
624 // Reassociate constant RHS with another constant to form constant
625 // expression.
626 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
627 Constant *C1;
628 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
629 // (C1 / X) * C --> (C * C1) / X
630 Constant *CC1 =
631 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
632 if (CC1 && CC1->isNormalFP())
633 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
634 }
635 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
636 // (X / C1) * C --> X * (C / C1)
637 Constant *CDivC1 =
638 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
639 if (CDivC1 && CDivC1->isNormalFP())
640 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
641
642 // If the constant was a denormal, try reassociating differently.
643 // (X / C1) * C --> X / (C1 / C)
644 Constant *C1DivC =
645 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
646 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
647 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
648 }
649
650 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
651 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
652 // further folds and (X * C) + C2 is 'fma'.
653 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
654 // (X + C1) * C --> (X * C) + (C * C1)
655 if (Constant *CC1 =
656 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
657 Value *XC = Builder.CreateFMulFMF(X, C, &I);
658 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
659 }
660 }
661 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
662 // (C1 - X) * C --> (C * C1) - (X * C)
663 if (Constant *CC1 =
664 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
665 Value *XC = Builder.CreateFMulFMF(X, C, &I);
666 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
667 }
668 }
669 }
670
671 Value *Z;
672 if (match(&I,
674 // Sink division: (X / Y) * Z --> (X * Z) / Y
675 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
676 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
677 }
678
679 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
680 // nnan disallows the possibility of returning a number if both operands are
681 // negative (in that case, we should return NaN).
682 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
683 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
684 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
685 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
686 return replaceInstUsesWith(I, Sqrt);
687 }
688
689 // The following transforms are done irrespective of the number of uses
690 // for the expression "1.0/sqrt(X)".
691 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
692 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
693 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
694 // has the necessary (reassoc) fast-math-flags.
695 if (I.hasNoSignedZeros() &&
696 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
697 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
699 if (I.hasNoSignedZeros() &&
700 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
701 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
703
704 // Like the similar transform in instsimplify, this requires 'nsz' because
705 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
706 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
707 // Peek through fdiv to find squaring of square root:
708 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
709 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
710 Value *XX = Builder.CreateFMulFMF(X, X, &I);
711 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
712 }
713 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
714 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
715 Value *XX = Builder.CreateFMulFMF(X, X, &I);
716 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
717 }
718 }
719
720 // pow(X, Y) * X --> pow(X, Y+1)
721 // X * pow(X, Y) --> pow(X, Y+1)
722 if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Value(X),
723 m_Value(Y))),
724 m_Deferred(X)))) {
725 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
726 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
727 return replaceInstUsesWith(I, Pow);
728 }
729
730 if (Instruction *FoldedPowi = foldPowiReassoc(I))
731 return FoldedPowi;
732
733 if (I.isOnlyUserOfAnyOperand()) {
734 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
735 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
736 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) {
737 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
738 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
739 return replaceInstUsesWith(I, NewPow);
740 }
741 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
742 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
743 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Value(Z), m_Specific(Y)))) {
744 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
745 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
746 return replaceInstUsesWith(I, NewPow);
747 }
748
749 // exp(X) * exp(Y) -> exp(X + Y)
750 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
751 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) {
752 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
753 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
754 return replaceInstUsesWith(I, Exp);
755 }
756
757 // exp2(X) * exp2(Y) -> exp2(X + Y)
758 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
759 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) {
760 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
761 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
762 return replaceInstUsesWith(I, Exp2);
763 }
764 }
765
766 // (X*Y) * X => (X*X) * Y where Y != X
767 // The purpose is two-fold:
768 // 1) to form a power expression (of X).
769 // 2) potentially shorten the critical path: After transformation, the
770 // latency of the instruction Y is amortized by the expression of X*X,
771 // and therefore Y is in a "less critical" position compared to what it
772 // was before the transformation.
773 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
774 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
775 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
776 }
777 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
778 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
779 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
780 }
781
782 return nullptr;
783}
784
786 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
787 I.getFastMathFlags(),
789 return replaceInstUsesWith(I, V);
790
792 return &I;
793
795 return X;
796
798 return Phi;
799
800 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
801 return FoldedMul;
802
803 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
804 return replaceInstUsesWith(I, FoldedMul);
805
806 if (Instruction *R = foldFPSignBitOps(I))
807 return R;
808
809 if (Instruction *R = foldFBinOpOfIntCasts(I))
810 return R;
811
812 // X * -1.0 --> -X
813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
814 if (match(Op1, m_SpecificFP(-1.0)))
815 return UnaryOperator::CreateFNegFMF(Op0, &I);
816
817 // With no-nans: X * 0.0 --> copysign(0.0, X)
818 if (I.hasNoNaNs() && match(Op1, m_PosZeroFP())) {
819 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
820 {I.getType()}, {Op1, Op0}, &I);
821 return replaceInstUsesWith(I, CopySign);
822 }
823
824 // -X * C --> X * -C
825 Value *X, *Y;
826 Constant *C;
827 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
828 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
829 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
830
831 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
832 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
833 return replaceInstUsesWith(I, V);
834
835 if (I.hasAllowReassoc())
836 if (Instruction *FoldedMul = foldFMulReassoc(I))
837 return FoldedMul;
838
839 // log2(X * 0.5) * Y = log2(X) * Y - Y
840 if (I.isFast()) {
841 IntrinsicInst *Log2 = nullptr;
842 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
843 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
844 Log2 = cast<IntrinsicInst>(Op0);
845 Y = Op1;
846 }
847 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
848 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
849 Log2 = cast<IntrinsicInst>(Op1);
850 Y = Op0;
851 }
852 if (Log2) {
853 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
854 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
855 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
856 }
857 }
858
859 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
860 // Given a phi node with entry value as 0 and it used in fmul operation,
861 // we can replace fmul with 0 safely and eleminate loop operation.
862 PHINode *PN = nullptr;
863 Value *Start = nullptr, *Step = nullptr;
864 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
865 I.hasNoSignedZeros() && match(Start, m_Zero()))
866 return replaceInstUsesWith(I, Start);
867
868 // minimum(X, Y) * maximum(X, Y) => X * Y.
869 if (match(&I,
870 m_c_FMul(m_Intrinsic<Intrinsic::maximum>(m_Value(X), m_Value(Y)),
871 m_c_Intrinsic<Intrinsic::minimum>(m_Deferred(X),
872 m_Deferred(Y))))) {
874 // We cannot preserve ninf if nnan flag is not set.
875 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
876 // while in optimized version NaN * Inf and this is a poison with ninf flag.
877 if (!Result->hasNoNaNs())
878 Result->setHasNoInfs(false);
879 return Result;
880 }
881
882 return nullptr;
883}
884
885/// Fold a divide or remainder with a select instruction divisor when one of the
886/// select operands is zero. In that case, we can use the other select operand
887/// because div/rem by zero is undefined.
889 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
890 if (!SI)
891 return false;
892
893 int NonNullOperand;
894 if (match(SI->getTrueValue(), m_Zero()))
895 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
896 NonNullOperand = 2;
897 else if (match(SI->getFalseValue(), m_Zero()))
898 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
899 NonNullOperand = 1;
900 else
901 return false;
902
903 // Change the div/rem to use 'Y' instead of the select.
904 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
905
906 // Okay, we know we replace the operand of the div/rem with 'Y' with no
907 // problem. However, the select, or the condition of the select may have
908 // multiple uses. Based on our knowledge that the operand must be non-zero,
909 // propagate the known value for the select into other uses of it, and
910 // propagate a known value of the condition into its other users.
911
912 // If the select and condition only have a single use, don't bother with this,
913 // early exit.
914 Value *SelectCond = SI->getCondition();
915 if (SI->use_empty() && SelectCond->hasOneUse())
916 return true;
917
918 // Scan the current block backward, looking for other uses of SI.
919 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
920 Type *CondTy = SelectCond->getType();
921 while (BBI != BBFront) {
922 --BBI;
923 // If we found an instruction that we can't assume will return, so
924 // information from below it cannot be propagated above it.
926 break;
927
928 // Replace uses of the select or its condition with the known values.
929 for (Use &Op : BBI->operands()) {
930 if (Op == SI) {
931 replaceUse(Op, SI->getOperand(NonNullOperand));
932 Worklist.push(&*BBI);
933 } else if (Op == SelectCond) {
934 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
935 : ConstantInt::getFalse(CondTy));
936 Worklist.push(&*BBI);
937 }
938 }
939
940 // If we past the instruction, quit looking for it.
941 if (&*BBI == SI)
942 SI = nullptr;
943 if (&*BBI == SelectCond)
944 SelectCond = nullptr;
945
946 // If we ran out of things to eliminate, break out of the loop.
947 if (!SelectCond && !SI)
948 break;
949
950 }
951 return true;
952}
953
954/// True if the multiply can not be expressed in an int this size.
955static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
956 bool IsSigned) {
957 bool Overflow;
958 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
959 return Overflow;
960}
961
962/// True if C1 is a multiple of C2. Quotient contains C1/C2.
963static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
964 bool IsSigned) {
965 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
966
967 // Bail if we will divide by zero.
968 if (C2.isZero())
969 return false;
970
971 // Bail if we would divide INT_MIN by -1.
972 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
973 return false;
974
975 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
976 if (IsSigned)
977 APInt::sdivrem(C1, C2, Quotient, Remainder);
978 else
979 APInt::udivrem(C1, C2, Quotient, Remainder);
980
981 return Remainder.isMinValue();
982}
983
985 assert((I.getOpcode() == Instruction::SDiv ||
986 I.getOpcode() == Instruction::UDiv) &&
987 "Expected integer divide");
988
989 bool IsSigned = I.getOpcode() == Instruction::SDiv;
990 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
991 Type *Ty = I.getType();
992
993 Value *X, *Y, *Z;
994
995 // With appropriate no-wrap constraints, remove a common factor in the
996 // dividend and divisor that is disguised as a left-shifted value.
997 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
998 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
999 // Both operands must have the matching no-wrap for this kind of division.
1000 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1001 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1002 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1003 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1004
1005 // (X * Y) u/ (X << Z) --> Y u>> Z
1006 if (!IsSigned && HasNUW)
1007 return Builder.CreateLShr(Y, Z, "", I.isExact());
1008
1009 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1010 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1011 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1012 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1013 }
1014 }
1015
1016 // With appropriate no-wrap constraints, remove a common factor in the
1017 // dividend and divisor that is disguised as a left-shift amount.
1018 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1019 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1020 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1021 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1022
1023 // For unsigned div, we need 'nuw' on both shifts or
1024 // 'nsw' on both shifts + 'nuw' on the dividend.
1025 // (X << Z) / (Y << Z) --> X / Y
1026 if (!IsSigned &&
1027 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1028 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1029 Shl1->hasNoSignedWrap())))
1030 return Builder.CreateUDiv(X, Y, "", I.isExact());
1031
1032 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1033 // (X << Z) / (Y << Z) --> X / Y
1034 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1035 Shl1->hasNoUnsignedWrap())
1036 return Builder.CreateSDiv(X, Y, "", I.isExact());
1037 }
1038
1039 // If X << Y and X << Z does not overflow, then:
1040 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1041 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1042 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1043 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1044 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1045
1046 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1047 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1048 Constant *One = ConstantInt::get(X->getType(), 1);
1049 // Only preserve the nsw flag if dividend has nsw
1050 // or divisor has nsw and operator is sdiv.
1051 Value *Dividend = Builder.CreateShl(
1052 One, Y, "shl.dividend",
1053 /*HasNUW*/ true,
1054 /*HasNSW*/
1055 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1056 : Shl0->hasNoSignedWrap());
1057 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1058 }
1059 }
1060
1061 return nullptr;
1062}
1063
1064/// This function implements the transforms common to both integer division
1065/// instructions (udiv and sdiv). It is called by the visitors to those integer
1066/// division instructions.
1067/// Common integer divide transforms
1070 return Phi;
1071
1072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1073 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1074 Type *Ty = I.getType();
1075
1076 // The RHS is known non-zero.
1077 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1078 return replaceOperand(I, 1, V);
1079
1080 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1081 // This does not apply for fdiv.
1083 return &I;
1084
1085 // If the divisor is a select-of-constants, try to constant fold all div ops:
1086 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC)
1087 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1088 if (match(Op0, m_ImmConstant()) &&
1090 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1091 /*FoldWithMultiUse*/ true))
1092 return R;
1093 }
1094
1095 const APInt *C2;
1096 if (match(Op1, m_APInt(C2))) {
1097 Value *X;
1098 const APInt *C1;
1099
1100 // (X / C1) / C2 -> X / (C1*C2)
1101 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1102 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1103 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1104 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1105 return BinaryOperator::Create(I.getOpcode(), X,
1106 ConstantInt::get(Ty, Product));
1107 }
1108
1109 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1110 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1111 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1112
1113 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1114 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1115 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1116 ConstantInt::get(Ty, Quotient));
1117 NewDiv->setIsExact(I.isExact());
1118 return NewDiv;
1119 }
1120
1121 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1122 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1123 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1124 ConstantInt::get(Ty, Quotient));
1125 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1126 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1127 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1128 return Mul;
1129 }
1130 }
1131
1132 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1133 C1->ult(C1->getBitWidth() - 1)) ||
1134 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1135 C1->ult(C1->getBitWidth()))) {
1136 APInt C1Shifted = APInt::getOneBitSet(
1137 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1138
1139 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1140 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1141 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1142 ConstantInt::get(Ty, Quotient));
1143 BO->setIsExact(I.isExact());
1144 return BO;
1145 }
1146
1147 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1148 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1149 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1150 ConstantInt::get(Ty, Quotient));
1151 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1152 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1153 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1154 return Mul;
1155 }
1156 }
1157
1158 // Distribute div over add to eliminate a matching div/mul pair:
1159 // ((X * C2) + C1) / C2 --> X + C1/C2
1160 // We need a multiple of the divisor for a signed add constant, but
1161 // unsigned is fine with any constant pair.
1162 if (IsSigned &&
1164 m_APInt(C1))) &&
1165 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1166 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1167 }
1168 if (!IsSigned &&
1170 m_APInt(C1)))) {
1171 return BinaryOperator::CreateNUWAdd(X,
1172 ConstantInt::get(Ty, C1->udiv(*C2)));
1173 }
1174
1175 if (!C2->isZero()) // avoid X udiv 0
1176 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1177 return FoldedDiv;
1178 }
1179
1180 if (match(Op0, m_One())) {
1181 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1182 if (IsSigned) {
1183 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1184 // (Op1 + 1) u< 3 ? Op1 : 0
1185 // Op1 must be frozen because we are increasing its number of uses.
1186 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1187 Value *Inc = Builder.CreateAdd(F1, Op0);
1188 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1189 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1190 } else {
1191 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1192 // result is one, otherwise it's zero.
1193 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1194 }
1195 }
1196
1197 // See if we can fold away this div instruction.
1199 return &I;
1200
1201 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1202 Value *X, *Z;
1203 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1204 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1205 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1206 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1207
1208 // (X << Y) / X -> 1 << Y
1209 Value *Y;
1210 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1211 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1212 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1213 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1214
1215 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1216 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1217 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1218 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1219 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1220 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1221 replaceOperand(I, 1, Y);
1222 return &I;
1223 }
1224 }
1225
1226 // (X << Z) / (X * Y) -> (1 << Z) / Y
1227 // TODO: Handle sdiv.
1228 if (!IsSigned && Op1->hasOneUse() &&
1229 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1230 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1231 if (cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap()) {
1232 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1233 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1234 NewDiv->setIsExact(I.isExact());
1235 return NewDiv;
1236 }
1237
1238 if (Value *R = foldIDivShl(I, Builder))
1239 return replaceInstUsesWith(I, R);
1240
1241 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1242 // after peeking through another divide:
1243 // ((Op1 * X) / Y) / Op1 --> X / Y
1244 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1245 m_Value(Y)))) {
1246 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1247 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1248 Instruction *NewDiv = nullptr;
1249 if (!IsSigned && Mul->hasNoUnsignedWrap())
1250 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1251 else if (IsSigned && Mul->hasNoSignedWrap())
1252 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1253
1254 // Exact propagates only if both of the original divides are exact.
1255 if (NewDiv) {
1256 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1257 return NewDiv;
1258 }
1259 }
1260
1261 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1262 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1263 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1264 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1265
1266 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1267 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1268 auto OB1HasNUW =
1269 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1270 const APInt *C1, *C2;
1271 if (IsSigned && OB0HasNSW) {
1272 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1273 return BinaryOperator::CreateSDiv(A, B);
1274 }
1275 if (!IsSigned && OB0HasNUW) {
1276 if (OB1HasNUW)
1277 return BinaryOperator::CreateUDiv(A, B);
1278 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1279 return BinaryOperator::CreateUDiv(A, B);
1280 }
1281 return nullptr;
1282 };
1283
1284 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1285 if (auto *Val = CreateDivOrNull(Y, Z))
1286 return Val;
1287 }
1288 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1289 if (auto *Val = CreateDivOrNull(X, Z))
1290 return Val;
1291 }
1292 }
1293 return nullptr;
1294}
1295
1296static const unsigned MaxDepth = 6;
1297
1298// Take the exact integer log2 of the value. If DoFold is true, create the
1299// actual instructions, otherwise return a non-null dummy value. Return nullptr
1300// on failure.
1301static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
1302 bool AssumeNonZero, bool DoFold) {
1303 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1304 if (!DoFold)
1305 return reinterpret_cast<Value *>(-1);
1306 return Fn();
1307 };
1308
1309 // FIXME: assert that Op1 isn't/doesn't contain undef.
1310
1311 // log2(2^C) -> C
1312 if (match(Op, m_Power2()))
1313 return IfFold([&]() {
1314 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op));
1315 if (!C)
1316 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1317 return C;
1318 });
1319
1320 // The remaining tests are all recursive, so bail out if we hit the limit.
1321 if (Depth++ == MaxDepth)
1322 return nullptr;
1323
1324 // log2(zext X) -> zext log2(X)
1325 // FIXME: Require one use?
1326 Value *X, *Y;
1327 if (match(Op, m_ZExt(m_Value(X))))
1328 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1329 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1330
1331 // log2(X << Y) -> log2(X) + Y
1332 // FIXME: Require one use unless X is 1?
1333 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1334 auto *BO = cast<OverflowingBinaryOperator>(Op);
1335 // nuw will be set if the `shl` is trivially non-zero.
1336 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1337 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1338 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1339 }
1340
1341 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1342 // FIXME: Require one use?
1343 if (SelectInst *SI = dyn_cast<SelectInst>(Op))
1344 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth,
1345 AssumeNonZero, DoFold))
1346 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth,
1347 AssumeNonZero, DoFold))
1348 return IfFold([&]() {
1349 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1350 });
1351
1352 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1353 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1354 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op);
1355 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1356 // Use AssumeNonZero as false here. Otherwise we can hit case where
1357 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1358 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth,
1359 /*AssumeNonZero*/ false, DoFold))
1360 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth,
1361 /*AssumeNonZero*/ false, DoFold))
1362 return IfFold([&]() {
1363 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1364 LogY);
1365 });
1366 }
1367
1368 return nullptr;
1369}
1370
1371/// If we have zero-extended operands of an unsigned div or rem, we may be able
1372/// to narrow the operation (sink the zext below the math).
1374 InstCombinerImpl &IC) {
1375 Instruction::BinaryOps Opcode = I.getOpcode();
1376 Value *N = I.getOperand(0);
1377 Value *D = I.getOperand(1);
1378 Type *Ty = I.getType();
1379 Value *X, *Y;
1380 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1381 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1382 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1383 // urem (zext X), (zext Y) --> zext (urem X, Y)
1384 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1385 return new ZExtInst(NarrowOp, Ty);
1386 }
1387
1388 Constant *C;
1389 if (isa<Instruction>(N) && match(N, m_OneUse(m_ZExt(m_Value(X)))) &&
1390 match(D, m_Constant(C))) {
1391 // If the constant is the same in the smaller type, use the narrow version.
1392 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1393 if (!TruncC)
1394 return nullptr;
1395
1396 // udiv (zext X), C --> zext (udiv X, C')
1397 // urem (zext X), C --> zext (urem X, C')
1398 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1399 }
1400 if (isa<Instruction>(D) && match(D, m_OneUse(m_ZExt(m_Value(X)))) &&
1401 match(N, m_Constant(C))) {
1402 // If the constant is the same in the smaller type, use the narrow version.
1403 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1404 if (!TruncC)
1405 return nullptr;
1406
1407 // udiv C, (zext X) --> zext (udiv C', X)
1408 // urem C, (zext X) --> zext (urem C', X)
1409 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1410 }
1411
1412 return nullptr;
1413}
1414
1416 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1418 return replaceInstUsesWith(I, V);
1419
1421 return X;
1422
1423 // Handle the integer div common cases
1424 if (Instruction *Common = commonIDivTransforms(I))
1425 return Common;
1426
1427 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1428 Value *X;
1429 const APInt *C1, *C2;
1430 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1431 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1432 bool Overflow;
1433 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1434 if (!Overflow) {
1435 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1436 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1437 X, ConstantInt::get(X->getType(), C2ShlC1));
1438 if (IsExact)
1439 BO->setIsExact();
1440 return BO;
1441 }
1442 }
1443
1444 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1445 // TODO: Could use isKnownNegative() to handle non-constant values.
1446 Type *Ty = I.getType();
1447 if (match(Op1, m_Negative())) {
1448 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1449 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1450 }
1451 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1452 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1454 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1455 }
1456
1457 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1458 return NarrowDiv;
1459
1460 Value *A, *B;
1461
1462 // Look through a right-shift to find the common factor:
1463 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1464 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1465 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1466 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1467 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1468 Lshr->setIsExact();
1469 return Lshr;
1470 }
1471
1472 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
1473 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ true,
1474 /*DoFold*/ false)) {
1475 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0,
1476 /*AssumeNonZero*/ true, /*DoFold*/ true);
1477 return replaceInstUsesWith(
1478 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1479 }
1480
1481 return nullptr;
1482}
1483
1485 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1487 return replaceInstUsesWith(I, V);
1488
1490 return X;
1491
1492 // Handle the integer div common cases
1493 if (Instruction *Common = commonIDivTransforms(I))
1494 return Common;
1495
1496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1497 Type *Ty = I.getType();
1498 Value *X;
1499 // sdiv Op0, -1 --> -Op0
1500 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1501 if (match(Op1, m_AllOnes()) ||
1502 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1503 return BinaryOperator::CreateNSWNeg(Op0);
1504
1505 // X / INT_MIN --> X == INT_MIN
1506 if (match(Op1, m_SignMask()))
1507 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1508
1509 if (I.isExact()) {
1510 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1511 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1512 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
1513 return BinaryOperator::CreateExactAShr(Op0, C);
1514 }
1515
1516 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1517 Value *ShAmt;
1518 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1519 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1520
1521 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1522 if (match(Op1, m_NegatedPower2())) {
1523 Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
1525 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1526 return BinaryOperator::CreateNSWNeg(Ashr);
1527 }
1528 }
1529
1530 const APInt *Op1C;
1531 if (match(Op1, m_APInt(Op1C))) {
1532 // If the dividend is sign-extended and the constant divisor is small enough
1533 // to fit in the source type, shrink the division to the narrower type:
1534 // (sext X) sdiv C --> sext (X sdiv C)
1535 Value *Op0Src;
1536 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1537 Op0Src->getType()->getScalarSizeInBits() >=
1538 Op1C->getSignificantBits()) {
1539
1540 // In the general case, we need to make sure that the dividend is not the
1541 // minimum signed value because dividing that by -1 is UB. But here, we
1542 // know that the -1 divisor case is already handled above.
1543
1544 Constant *NarrowDivisor =
1545 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1546 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1547 return new SExtInst(NarrowOp, Ty);
1548 }
1549
1550 // -X / C --> X / -C (if the negation doesn't overflow).
1551 // TODO: This could be enhanced to handle arbitrary vector constants by
1552 // checking if all elements are not the min-signed-val.
1553 if (!Op1C->isMinSignedValue() &&
1554 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1555 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1556 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1557 BO->setIsExact(I.isExact());
1558 return BO;
1559 }
1560 }
1561
1562 // -X / Y --> -(X / Y)
1563 Value *Y;
1566 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1567
1568 // abs(X) / X --> X > -1 ? 1 : -1
1569 // X / abs(X) --> X > -1 ? 1 : -1
1570 if (match(&I, m_c_BinOp(
1571 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1572 m_Deferred(X)))) {
1574 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1576 }
1577
1578 KnownBits KnownDividend = computeKnownBits(Op0, 0, &I);
1579 if (!I.isExact() &&
1580 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1581 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1582 I.setIsExact();
1583 return &I;
1584 }
1585
1586 if (KnownDividend.isNonNegative()) {
1587 // If both operands are unsigned, turn this into a udiv.
1589 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1590 BO->setIsExact(I.isExact());
1591 return BO;
1592 }
1593
1594 if (match(Op1, m_NegatedPower2())) {
1595 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1596 // -> -(X udiv (1 << C)) -> -(X u>> C)
1598 ConstantExpr::getNeg(cast<Constant>(Op1)));
1599 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1600 return BinaryOperator::CreateNeg(Shr);
1601 }
1602
1603 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1604 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1605 // Safe because the only negative value (1 << Y) can take on is
1606 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1607 // the sign bit set.
1608 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1609 BO->setIsExact(I.isExact());
1610 return BO;
1611 }
1612 }
1613
1614 // -X / X --> X == INT_MIN ? 1 : -1
1615 if (isKnownNegation(Op0, Op1)) {
1617 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1618 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1620 }
1621 return nullptr;
1622}
1623
1624/// Remove negation and try to convert division into multiplication.
1625Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1626 Constant *C;
1627 if (!match(I.getOperand(1), m_Constant(C)))
1628 return nullptr;
1629
1630 // -X / C --> X / -C
1631 Value *X;
1632 const DataLayout &DL = I.getModule()->getDataLayout();
1633 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1634 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1635 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1636
1637 // nnan X / +0.0 -> copysign(inf, X)
1638 // nnan nsz X / -0.0 -> copysign(inf, X)
1639 if (I.hasNoNaNs() &&
1640 (match(I.getOperand(1), m_PosZeroFP()) ||
1641 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1642 IRBuilder<> B(&I);
1643 CallInst *CopySign = B.CreateIntrinsic(
1644 Intrinsic::copysign, {C->getType()},
1645 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1646 CopySign->takeName(&I);
1647 return replaceInstUsesWith(I, CopySign);
1648 }
1649
1650 // If the constant divisor has an exact inverse, this is always safe. If not,
1651 // then we can still create a reciprocal if fast-math-flags allow it and the
1652 // constant is a regular number (not zero, infinite, or denormal).
1653 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1654 return nullptr;
1655
1656 // Disallow denormal constants because we don't know what would happen
1657 // on all targets.
1658 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1659 // denorms are flushed?
1660 auto *RecipC = ConstantFoldBinaryOpOperands(
1661 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1662 if (!RecipC || !RecipC->isNormalFP())
1663 return nullptr;
1664
1665 // X / C --> X * (1 / C)
1666 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1667}
1668
1669/// Remove negation and try to reassociate constant math.
1671 Constant *C;
1672 if (!match(I.getOperand(0), m_Constant(C)))
1673 return nullptr;
1674
1675 // C / -X --> -C / X
1676 Value *X;
1677 const DataLayout &DL = I.getModule()->getDataLayout();
1678 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1679 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1680 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1681
1682 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1683 return nullptr;
1684
1685 // Try to reassociate C / X expressions where X includes another constant.
1686 Constant *C2, *NewC = nullptr;
1687 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1688 // C / (X * C2) --> (C / C2) / X
1689 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1690 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1691 // C / (X / C2) --> (C * C2) / X
1692 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1693 }
1694 // Disallow denormal constants because we don't know what would happen
1695 // on all targets.
1696 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1697 // denorms are flushed?
1698 if (!NewC || !NewC->isNormalFP())
1699 return nullptr;
1700
1701 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1702}
1703
1704/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1706 InstCombiner::BuilderTy &Builder) {
1707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1708 auto *II = dyn_cast<IntrinsicInst>(Op1);
1709 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1710 !I.hasAllowReciprocal())
1711 return nullptr;
1712
1713 // Z / pow(X, Y) --> Z * pow(X, -Y)
1714 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1715 // In the general case, this creates an extra instruction, but fmul allows
1716 // for better canonicalization and optimization than fdiv.
1717 Intrinsic::ID IID = II->getIntrinsicID();
1719 switch (IID) {
1720 case Intrinsic::pow:
1721 Args.push_back(II->getArgOperand(0));
1722 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1723 break;
1724 case Intrinsic::powi: {
1725 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1726 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1727 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1728 // non-standard results, so this corner case should be acceptable if the
1729 // code rules out INF values.
1730 if (!I.hasNoInfs())
1731 return nullptr;
1732 Args.push_back(II->getArgOperand(0));
1733 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1734 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1735 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1736 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1737 }
1738 case Intrinsic::exp:
1739 case Intrinsic::exp2:
1740 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1741 break;
1742 default:
1743 return nullptr;
1744 }
1745 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1746 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1747}
1748
1749/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
1750/// instruction.
1752 InstCombiner::BuilderTy &Builder) {
1753 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
1754 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1755 return nullptr;
1756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1757 auto *II = dyn_cast<IntrinsicInst>(Op1);
1758 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
1759 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
1760 return nullptr;
1761
1762 Value *Y, *Z;
1763 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
1764 if (!DivOp)
1765 return nullptr;
1766 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
1767 return nullptr;
1768 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
1769 !DivOp->hasOneUse())
1770 return nullptr;
1771 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
1772 Value *NewSqrt =
1773 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
1774 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
1775}
1776
1778 Module *M = I.getModule();
1779
1780 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
1781 I.getFastMathFlags(),
1783 return replaceInstUsesWith(I, V);
1784
1786 return X;
1787
1789 return Phi;
1790
1791 if (Instruction *R = foldFDivConstantDivisor(I))
1792 return R;
1793
1795 return R;
1796
1797 if (Instruction *R = foldFPSignBitOps(I))
1798 return R;
1799
1800 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1801 if (isa<Constant>(Op0))
1802 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1803 if (Instruction *R = FoldOpIntoSelect(I, SI))
1804 return R;
1805
1806 if (isa<Constant>(Op1))
1807 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1808 if (Instruction *R = FoldOpIntoSelect(I, SI))
1809 return R;
1810
1811 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1812 Value *X, *Y;
1813 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1814 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1815 // (X / Y) / Z => X / (Y * Z)
1816 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1817 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1818 }
1819 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1820 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1821 // Z / (X / Y) => (Y * Z) / X
1822 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1823 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1824 }
1825 // Z / (1.0 / Y) => (Y * Z)
1826 //
1827 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1828 // m_OneUse check is avoided because even in the case of the multiple uses
1829 // for 1.0/Y, the number of instructions remain the same and a division is
1830 // replaced by a multiplication.
1831 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1832 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1833 }
1834
1835 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1836 // sin(X) / cos(X) -> tan(X)
1837 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1838 Value *X;
1839 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1840 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1841 bool IsCot =
1842 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1843 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1844
1845 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
1846 LibFunc_tanf, LibFunc_tanl)) {
1847 IRBuilder<> B(&I);
1849 B.setFastMathFlags(I.getFastMathFlags());
1850 AttributeList Attrs =
1851 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1852 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1853 LibFunc_tanl, B, Attrs);
1854 if (IsCot)
1855 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1856 return replaceInstUsesWith(I, Res);
1857 }
1858 }
1859
1860 // X / (X * Y) --> 1.0 / Y
1861 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1862 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1863 Value *X, *Y;
1864 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1865 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1866 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1867 replaceOperand(I, 1, Y);
1868 return &I;
1869 }
1870
1871 // X / fabs(X) -> copysign(1.0, X)
1872 // fabs(X) / X -> copysign(1.0, X)
1873 if (I.hasNoNaNs() && I.hasNoInfs() &&
1874 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1875 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1877 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1878 return replaceInstUsesWith(I, V);
1879 }
1880
1882 return Mul;
1883
1885 return Mul;
1886
1887 // pow(X, Y) / X --> pow(X, Y-1)
1888 if (I.hasAllowReassoc() &&
1889 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Specific(Op1),
1890 m_Value(Y))))) {
1891 Value *Y1 =
1892 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
1893 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
1894 return replaceInstUsesWith(I, Pow);
1895 }
1896
1897 // powi(X, Y) / X --> powi(X, Y-1)
1898 // This is legal when (Y - 1) can't wraparound, in which case reassoc and nnan
1899 // are required.
1900 // TODO: Multi-use may be also better off creating Powi(x,y-1)
1901 if (I.hasAllowReassoc() && I.hasNoNaNs() &&
1902 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::powi>(m_Specific(Op1),
1903 m_Value(Y)))) &&
1904 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
1905 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
1906 Value *Y1 = Builder.CreateAdd(Y, NegOne);
1907 Type *Types[] = {Op1->getType(), Y1->getType()};
1908 Value *Pow = Builder.CreateIntrinsic(Intrinsic::powi, Types, {Op1, Y1}, &I);
1909 return replaceInstUsesWith(I, Pow);
1910 }
1911
1912 return nullptr;
1913}
1914
1915// Variety of transform for:
1916// (urem/srem (mul X, Y), (mul X, Z))
1917// (urem/srem (shl X, Y), (shl X, Z))
1918// (urem/srem (shl Y, X), (shl Z, X))
1919// NB: The shift cases are really just extensions of the mul case. We treat
1920// shift as Val * (1 << Amt).
1922 InstCombinerImpl &IC) {
1923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
1924 APInt Y, Z;
1925 bool ShiftByX = false;
1926
1927 // If V is not nullptr, it will be matched using m_Specific.
1928 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C) -> bool {
1929 const APInt *Tmp = nullptr;
1930 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
1931 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
1932 C = *Tmp;
1933 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
1934 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp)))))
1935 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
1936 if (Tmp != nullptr)
1937 return true;
1938
1939 // Reset `V` so we don't start with specific value on next match attempt.
1940 V = nullptr;
1941 return false;
1942 };
1943
1944 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
1945 const APInt *Tmp = nullptr;
1946 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
1947 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
1948 C = *Tmp;
1949 return true;
1950 }
1951
1952 // Reset `V` so we don't start with specific value on next match attempt.
1953 V = nullptr;
1954 return false;
1955 };
1956
1957 if (MatchShiftOrMulXC(Op0, X, Y) && MatchShiftOrMulXC(Op1, X, Z)) {
1958 // pass
1959 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
1960 ShiftByX = true;
1961 } else {
1962 return nullptr;
1963 }
1964
1965 bool IsSRem = I.getOpcode() == Instruction::SRem;
1966
1967 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Op0);
1968 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
1969 // Z or Z >= Y.
1970 bool BO0HasNSW = BO0->hasNoSignedWrap();
1971 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
1972 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
1973
1974 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
1975 // (rem (mul nuw/nsw X, Y), (mul X, Z))
1976 // if (rem Y, Z) == 0
1977 // -> 0
1978 if (RemYZ.isZero() && BO0NoWrap)
1979 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
1980
1981 // Helper function to emit either (RemSimplificationC << X) or
1982 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
1983 // (shl V, X) or (mul V, X) respectively.
1984 auto CreateMulOrShift =
1985 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
1986 Value *RemSimplification =
1987 ConstantInt::get(I.getType(), RemSimplificationC);
1988 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
1989 : BinaryOperator::CreateMul(X, RemSimplification);
1990 };
1991
1992 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Op1);
1993 bool BO1HasNSW = BO1->hasNoSignedWrap();
1994 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
1995 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
1996 // (rem (mul X, Y), (mul nuw/nsw X, Z))
1997 // if (rem Y, Z) == Y
1998 // -> (mul nuw/nsw X, Y)
1999 if (RemYZ == Y && BO1NoWrap) {
2000 BinaryOperator *BO = CreateMulOrShift(Y);
2001 // Copy any overflow flags from Op0.
2002 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2003 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2004 return BO;
2005 }
2006
2007 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2008 // if Y >= Z
2009 // -> (mul {nuw} nsw X, (rem Y, Z))
2010 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2011 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2012 BO->setHasNoSignedWrap();
2013 BO->setHasNoUnsignedWrap(BO0HasNUW);
2014 return BO;
2015 }
2016
2017 return nullptr;
2018}
2019
2020/// This function implements the transforms common to both integer remainder
2021/// instructions (urem and srem). It is called by the visitors to those integer
2022/// remainder instructions.
2023/// Common integer remainder transforms
2026 return Phi;
2027
2028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2029
2030 // The RHS is known non-zero.
2031 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
2032 return replaceOperand(I, 1, V);
2033
2034 // Handle cases involving: rem X, (select Cond, Y, Z)
2036 return &I;
2037
2038 // If the divisor is a select-of-constants, try to constant fold all rem ops:
2039 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
2040 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
2041 if (match(Op0, m_ImmConstant()) &&
2043 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
2044 /*FoldWithMultiUse*/ true))
2045 return R;
2046 }
2047
2048 if (isa<Constant>(Op1)) {
2049 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2051 if (Instruction *R = FoldOpIntoSelect(I, SI))
2052 return R;
2053 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2054 const APInt *Op1Int;
2055 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2056 (I.getOpcode() == Instruction::URem ||
2057 !Op1Int->isMinSignedValue())) {
2058 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2059 // predecessor blocks, so do this only if we know the srem or urem
2060 // will not fault.
2061 if (Instruction *NV = foldOpIntoPhi(I, PN))
2062 return NV;
2063 }
2064 }
2065
2066 // See if we can fold away this rem instruction.
2068 return &I;
2069 }
2070 }
2071
2072 if (Instruction *R = simplifyIRemMulShl(I, *this))
2073 return R;
2074
2075 return nullptr;
2076}
2077
2079 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2081 return replaceInstUsesWith(I, V);
2082
2084 return X;
2085
2086 if (Instruction *common = commonIRemTransforms(I))
2087 return common;
2088
2089 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2090 return NarrowRem;
2091
2092 // X urem Y -> X and Y-1, where Y is a power of 2,
2093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2094 Type *Ty = I.getType();
2095 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
2096 // This may increase instruction count, we don't enforce that Y is a
2097 // constant.
2099 Value *Add = Builder.CreateAdd(Op1, N1);
2100 return BinaryOperator::CreateAnd(Op0, Add);
2101 }
2102
2103 // 1 urem X -> zext(X != 1)
2104 if (match(Op0, m_One())) {
2105 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2106 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2107 }
2108
2109 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2110 // Op0 must be frozen because we are increasing its number of uses.
2111 if (match(Op1, m_Negative())) {
2112 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2113 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2114 Value *Sub = Builder.CreateSub(F0, Op1);
2115 return SelectInst::Create(Cmp, F0, Sub);
2116 }
2117
2118 // If the divisor is a sext of a boolean, then the divisor must be max
2119 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2120 // max unsigned value. In that case, the remainder is 0:
2121 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2122 Value *X;
2123 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2124 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2125 Value *Cmp =
2127 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2128 }
2129
2130 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2131 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2132 Value *Val =
2134 if (Val && match(Val, m_One())) {
2135 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2136 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2137 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2138 }
2139 }
2140
2141 return nullptr;
2142}
2143
2145 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2147 return replaceInstUsesWith(I, V);
2148
2150 return X;
2151
2152 // Handle the integer rem common cases
2153 if (Instruction *Common = commonIRemTransforms(I))
2154 return Common;
2155
2156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2157 {
2158 const APInt *Y;
2159 // X % -Y -> X % Y
2160 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2161 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2162 }
2163
2164 // -X srem Y --> -(X srem Y)
2165 Value *X, *Y;
2168
2169 // If the sign bits of both operands are zero (i.e. we can prove they are
2170 // unsigned inputs), turn this into a urem.
2171 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2172 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
2173 MaskedValueIsZero(Op0, Mask, 0, &I)) {
2174 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2175 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2176 }
2177
2178 // If it's a constant vector, flip any negative values positive.
2179 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
2180 Constant *C = cast<Constant>(Op1);
2181 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2182
2183 bool hasNegative = false;
2184 bool hasMissing = false;
2185 for (unsigned i = 0; i != VWidth; ++i) {
2186 Constant *Elt = C->getAggregateElement(i);
2187 if (!Elt) {
2188 hasMissing = true;
2189 break;
2190 }
2191
2192 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2193 if (RHS->isNegative())
2194 hasNegative = true;
2195 }
2196
2197 if (hasNegative && !hasMissing) {
2198 SmallVector<Constant *, 16> Elts(VWidth);
2199 for (unsigned i = 0; i != VWidth; ++i) {
2200 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2201 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2202 if (RHS->isNegative())
2203 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2204 }
2205 }
2206
2207 Constant *NewRHSV = ConstantVector::get(Elts);
2208 if (NewRHSV != C) // Don't loop on -MININT
2209 return replaceOperand(I, 1, NewRHSV);
2210 }
2211 }
2212
2213 return nullptr;
2214}
2215
2217 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2218 I.getFastMathFlags(),
2220 return replaceInstUsesWith(I, V);
2221
2223 return X;
2224
2226 return Phi;
2227
2228 return nullptr;
2229}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides internal interfaces used to implement the InstCombine.
static Instruction * simplifyIRemMulShl(BinaryOperator &I, InstCombinerImpl &IC)
static Instruction * narrowUDivURem(BinaryOperator &I, InstCombinerImpl &IC)
If we have zero-extended operands of an unsigned div or rem, we may be able to narrow the operation (...
static Value * simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, Instruction &CxtI)
The specific integer value is used in a context where it is known to be non-zero.
static const unsigned MaxDepth
static Value * foldMulSelectToNegate(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static Instruction * foldFDivPowDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Negate the exponent of pow/exp to fold division-by-pow() into multiply.
static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, bool IsSigned)
True if the multiply can not be expressed in an int this size.
static Value * foldMulShl1(BinaryOperator &Mul, bool CommuteOperands, InstCombiner::BuilderTy &Builder)
Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
static Value * takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold)
static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, bool IsSigned)
True if C1 is a multiple of C2. Quotient contains C1/C2.
static Instruction * foldFDivSqrtDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv instruction.
static Instruction * foldFDivConstantDividend(BinaryOperator &I)
Remove negation and try to reassociate constant math.
static Value * foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
This file provides the interface for the instcombine pass implementation.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Value * RHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1977
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1579
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition: APInt.cpp:1764
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:207
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:401
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1896
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:349
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:395
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1589
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:2011
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1482
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1966
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1128
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:164
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:328
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name, BasicBlock::iterator InsertBefore)
BinaryOps getOpcode() const
Definition: InstrTypes.h:491
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name, BasicBlock::iterator InsertBefore)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:323
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:318
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:313
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:297
This class represents a function call, abstracting a target machine's calling convention.
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Create a ZExt or BitCast cast instruction.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1323
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:990
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2562
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2098
static Constant * getExactLogBase2(Constant *C)
If C is a scalar/fixed width vector of known powers of 2, then this function returns a new scalar/fix...
Definition: Constants.cpp:2569
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2525
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1083
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:856
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:863
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
Definition: Constants.cpp:235
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
Definition: Constants.cpp:186
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
Value * CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1541
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:913
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2240
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2006
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1715
Value * CreateSRem(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1404
Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Definition: IRBuilder.cpp:921
Value * CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1595
Value * CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1622
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:460
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:932
Value * CreateFNegFMF(Value *V, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1739
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1110
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2518
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1431
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2542
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:305
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1364
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1372
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2228
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2224
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition: IRBuilder.h:2537
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1338
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1410
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2010
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1469
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1321
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1385
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1660
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2236
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1450
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1729
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1355
Instruction * visitMul(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
Instruction * visitUDiv(BinaryOperator &I)
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * visitURem(BinaryOperator &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * visitSRem(BinaryOperator &I)
Instruction * visitFDiv(BinaryOperator &I)
bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I)
Fold a divide or remainder with a select instruction divisor when one of the select operands is zero.
Constant * getLosslessUnsignedTrunc(Constant *C, Type *TruncTy)
Instruction * commonIDivTransforms(BinaryOperator &I)
This function implements the transforms common to both integer division instructions (udiv and sdiv).
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * visitFRem(BinaryOperator &I)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * visitFMul(BinaryOperator &I)
Instruction * foldFMulReassoc(BinaryOperator &I)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * foldPowiReassoc(BinaryOperator &I)
Instruction * visitSDiv(BinaryOperator &I)
Instruction * commonIRemTransforms(BinaryOperator &I)
This function implements the transforms common to both integer remainder instructions (urem and srem)...
SimplifyQuery SQ
Definition: InstCombiner.h:76
TargetLibraryInfo & TLI
Definition: InstCombiner.h:73
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, unsigned Depth=0, const Instruction *CxtI=nullptr)
Definition: InstCombiner.h:440
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:385
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:417
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
const DataLayout & DL
Definition: InstCombiner.h:75
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:409
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:430
BuilderTy & Builder
Definition: InstCombiner.h:60
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:446
void push(Instruction *I)
Push the instruction onto the worklist stack.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:75
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:108
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:102
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:189
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:149
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:477
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:903
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
Definition: PatternMatch.h:499
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::FMul, true > m_c_FMul(const LHS &L, const RHS &R)
Matches FMul with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
Definition: PatternMatch.h:613
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
apint_match m_APIntAllowUndef(const APInt *&Res)
Match APInt while allowing undefs in splat vector constants.
Definition: PatternMatch.h:300
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:568
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:160
AllowReassoc_match< T > m_AllowReassoc(const T &SubPattern)
Definition: PatternMatch.h:83
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
Definition: PatternMatch.h:713
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:821
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
Definition: PatternMatch.h:509
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:541
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
Definition: PatternMatch.h:864
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:839
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:800
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
Definition: PatternMatch.h:576
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
specific_intval< true > m_SpecificIntAllowUndef(APInt V)
Definition: PatternMatch.h:911
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:294
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
Definition: PatternMatch.h:722
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FDiv > m_FDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:561
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * emitUnaryFloatFnCall(Value *Op, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the unary function named 'Name' (e.g.
Value * simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FMul, fold the result or return null.
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
bool hasFloatFn(const Module *M, const TargetLibraryInfo *TLI, Type *Ty, LibFunc DoubleFn, LibFunc FloatFn, LibFunc LongDoubleFn)
Check whether the overloaded floating point function corresponding to Ty is available.
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
Value * simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FRem, fold the result or return null.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
Value * simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
Value * simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FDiv, fold the result or return null.
@ Mul
Product of integers.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
Value * simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for a UDiv, fold the result or return null.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
Value * simplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an SRem, fold the result or return null.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:104
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:238
SelectPatternFlavor Flavor
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96