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, "", 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, "", 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_APIntAllowPoison(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 Value *X;
323 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
324 return BinaryOperator::CreateMul(X, X);
325
326 {
327 Value *Y;
328 // abs(X) * abs(Y) -> abs(X * Y)
329 if (I.hasNoSignedWrap() &&
330 match(Op0,
331 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One()))) &&
332 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(Y), m_One()))))
333 return replaceInstUsesWith(
334 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
336 Builder.getTrue()));
337 }
338
339 // -X * C --> X * -C
340 Value *Y;
341 Constant *Op1C;
342 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
343 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
344
345 // -X * -Y --> X * Y
346 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
347 auto *NewMul = BinaryOperator::CreateMul(X, Y);
348 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
349 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
350 NewMul->setHasNoSignedWrap();
351 return NewMul;
352 }
353
354 // -X * Y --> -(X * Y)
355 // X * -Y --> -(X * Y)
358
359 // (-X * Y) * -X --> (X * Y) * X
360 // (-X << Y) * -X --> (X << Y) * X
361 if (match(Op1, m_Neg(m_Value(X)))) {
362 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
363 return BinaryOperator::CreateMul(NegOp0, X);
364 }
365
366 // (X / Y) * Y = X - (X % Y)
367 // (X / Y) * -Y = (X % Y) - X
368 {
369 Value *Y = Op1;
370 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
371 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
372 Div->getOpcode() != Instruction::SDiv)) {
373 Y = Op0;
374 Div = dyn_cast<BinaryOperator>(Op1);
375 }
376 Value *Neg = dyn_castNegVal(Y);
377 if (Div && Div->hasOneUse() &&
378 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
379 (Div->getOpcode() == Instruction::UDiv ||
380 Div->getOpcode() == Instruction::SDiv)) {
381 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
382
383 // If the division is exact, X % Y is zero, so we end up with X or -X.
384 if (Div->isExact()) {
385 if (DivOp1 == Y)
386 return replaceInstUsesWith(I, X);
388 }
389
390 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
391 : Instruction::SRem;
392 // X must be frozen because we are increasing its number of uses.
393 Value *XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
394 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
395 if (DivOp1 == Y)
396 return BinaryOperator::CreateSub(XFreeze, Rem);
397 return BinaryOperator::CreateSub(Rem, XFreeze);
398 }
399 }
400
401 // Fold the following two scenarios:
402 // 1) i1 mul -> i1 and.
403 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
404 // Note: We could use known bits to generalize this and related patterns with
405 // shifts/truncs
406 if (Ty->isIntOrIntVectorTy(1) ||
407 (match(Op0, m_And(m_Value(), m_One())) &&
408 match(Op1, m_And(m_Value(), m_One()))))
409 return BinaryOperator::CreateAnd(Op0, Op1);
410
411 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
412 return replaceInstUsesWith(I, R);
413 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
414 return replaceInstUsesWith(I, R);
415
416 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
417 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
418 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
419 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
420 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
421 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
422 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
423 Value *And = Builder.CreateAnd(X, Y, "mulbool");
424 return CastInst::Create(Instruction::ZExt, And, Ty);
425 }
426 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
427 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
428 // Note: -1 * 1 == 1 * -1 == -1
429 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
430 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
431 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
432 (Op0->hasOneUse() || Op1->hasOneUse())) {
433 Value *And = Builder.CreateAnd(X, Y, "mulbool");
434 return CastInst::Create(Instruction::SExt, And, Ty);
435 }
436
437 // (zext bool X) * Y --> X ? Y : 0
438 // Y * (zext bool X) --> X ? Y : 0
439 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
441 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
443
444 // mul (sext X), Y -> select X, -Y, 0
445 // mul Y, (sext X) -> select X, -Y, 0
446 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
447 X->getType()->isIntOrIntVectorTy(1))
448 return SelectInst::Create(X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
450
451 Constant *ImmC;
452 if (match(Op1, m_ImmConstant(ImmC))) {
453 // (sext bool X) * C --> X ? -C : 0
454 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
455 Constant *NegC = ConstantExpr::getNeg(ImmC);
457 }
458
459 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
460 const APInt *C;
461 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
462 *C == C->getBitWidth() - 1) {
463 Constant *NegC = ConstantExpr::getNeg(ImmC);
464 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
465 return SelectInst::Create(IsNeg, NegC, ConstantInt::getNullValue(Ty));
466 }
467 }
468
469 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
470 // TODO: We are not checking one-use because the elimination of the multiply
471 // is better for analysis?
472 const APInt *C;
473 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
474 *C == C->getBitWidth() - 1) {
475 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
477 }
478
479 // (and X, 1) * Y --> (trunc X) ? Y : 0
480 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
483 }
484
485 // ((ashr X, 31) | 1) * X --> abs(X)
486 // X * ((ashr X, 31) | 1) --> abs(X)
489 m_One()),
490 m_Deferred(X)))) {
492 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
493 Abs->takeName(&I);
494 return replaceInstUsesWith(I, Abs);
495 }
496
497 if (Instruction *Ext = narrowMathIfNoOverflow(I))
498 return Ext;
499
501 return Res;
502
503 // (mul Op0 Op1):
504 // if Log2(Op0) folds away ->
505 // (shl Op1, Log2(Op0))
506 // if Log2(Op1) folds away ->
507 // (shl Op0, Log2(Op1))
508 if (takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
509 /*DoFold*/ false)) {
510 Value *Res = takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
511 /*DoFold*/ true);
512 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
513 // We can only propegate nuw flag.
514 Shl->setHasNoUnsignedWrap(HasNUW);
515 return Shl;
516 }
517 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
518 /*DoFold*/ false)) {
519 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
520 /*DoFold*/ true);
521 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
522 // We can only propegate nuw flag.
523 Shl->setHasNoUnsignedWrap(HasNUW);
524 return Shl;
525 }
526
527 bool Changed = false;
528 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
529 Changed = true;
530 I.setHasNoSignedWrap(true);
531 }
532
533 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I, I.hasNoSignedWrap())) {
534 Changed = true;
535 I.setHasNoUnsignedWrap(true);
536 }
537
538 return Changed ? &I : nullptr;
539}
540
541Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
542 BinaryOperator::BinaryOps Opcode = I.getOpcode();
543 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
544 "Expected fmul or fdiv");
545
546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
547 Value *X, *Y;
548
549 // -X * -Y --> X * Y
550 // -X / -Y --> X / Y
551 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
552 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
553
554 // fabs(X) * fabs(X) -> X * X
555 // fabs(X) / fabs(X) -> X / X
556 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
557 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
558
559 // fabs(X) * fabs(Y) --> fabs(X * Y)
560 // fabs(X) / fabs(Y) --> fabs(X / Y)
561 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
562 (Op0->hasOneUse() || Op1->hasOneUse())) {
564 Builder.setFastMathFlags(I.getFastMathFlags());
565 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
566 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
567 Fabs->takeName(&I);
568 return replaceInstUsesWith(I, Fabs);
569 }
570
571 return nullptr;
572}
573
575 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
576 Value *Y, Value *Z) {
577 InstCombiner::BuilderTy &Builder = IC.Builder;
578 Value *YZ = Builder.CreateAdd(Y, Z);
580 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
581
582 return NewPow;
583 };
584
585 Value *X, *Y, *Z;
586 unsigned Opcode = I.getOpcode();
587 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
588 "Unexpected opcode");
589
590 // powi(X, Y) * X --> powi(X, Y+1)
591 // X * powi(X, Y) --> powi(X, Y+1)
592 if (match(&I, m_c_FMul(m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
593 m_Value(X), m_Value(Y)))),
594 m_Deferred(X)))) {
595 Constant *One = ConstantInt::get(Y->getType(), 1);
596 if (willNotOverflowSignedAdd(Y, One, I)) {
597 Instruction *NewPow = createPowiExpr(I, *this, X, Y, One);
598 return replaceInstUsesWith(I, NewPow);
599 }
600 }
601
602 // powi(x, y) * powi(x, z) -> powi(x, y + z)
603 Value *Op0 = I.getOperand(0);
604 Value *Op1 = I.getOperand(1);
605 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
607 m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y)))) &&
608 match(Op1, m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(m_Specific(X),
609 m_Value(Z)))) &&
610 Y->getType() == Z->getType()) {
611 Instruction *NewPow = createPowiExpr(I, *this, X, Y, Z);
612 return replaceInstUsesWith(I, NewPow);
613 }
614
615 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
616 // powi(X, Y) / X --> powi(X, Y-1)
617 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
618 // nnan are required.
619 // TODO: Multi-use may be also better off creating Powi(x,y-1)
620 if (match(Op0, m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
621 m_Specific(Op1), m_Value(Y))))) &&
622 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
623 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
624 Instruction *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
625 return replaceInstUsesWith(I, NewPow);
626 }
627
628 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
629 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
630 // nnan are required.
631 // TODO: Multi-use may be also better off creating Powi(x,y-1)
632 if (match(Op0, m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
633 m_Value(X), m_Value(Y))))) &&
635 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
636 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
637 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
638 return BinaryOperator::CreateFDivFMF(NewPow, Z, &I);
639 }
640 }
641
642 return nullptr;
643}
644
646 Value *Op0 = I.getOperand(0);
647 Value *Op1 = I.getOperand(1);
648 Value *X, *Y;
649 Constant *C;
650 BinaryOperator *Op0BinOp;
651
652 // Reassociate constant RHS with another constant to form constant
653 // expression.
654 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
655 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
656 // Everything in this scope folds I with Op0, intersecting their FMF.
657 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
660 Constant *C1;
661 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
662 // (C1 / X) * C --> (C * C1) / X
663 Constant *CC1 =
664 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
665 if (CC1 && CC1->isNormalFP())
666 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
667 }
668 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
669 // FIXME: This seems like it should also be checking for arcp
670 // (X / C1) * C --> X * (C / C1)
671 Constant *CDivC1 =
672 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
673 if (CDivC1 && CDivC1->isNormalFP())
674 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
675
676 // If the constant was a denormal, try reassociating differently.
677 // (X / C1) * C --> X / (C1 / C)
678 Constant *C1DivC =
679 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
680 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
681 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
682 }
683
684 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
685 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
686 // further folds and (X * C) + C2 is 'fma'.
687 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
688 // (X + C1) * C --> (X * C) + (C * C1)
689 if (Constant *CC1 =
690 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
691 Value *XC = Builder.CreateFMul(X, C);
692 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
693 }
694 }
695 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
696 // (C1 - X) * C --> (C * C1) - (X * C)
697 if (Constant *CC1 =
698 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
699 Value *XC = Builder.CreateFMul(X, C);
700 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
701 }
702 }
703 }
704
705 Value *Z;
706 if (match(&I,
708 m_Value(Z)))) {
709 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
710 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
711 if (FMF.allowReassoc()) {
712 // Sink division: (X / Y) * Z --> (X * Z) / Y
715 auto *NewFMul = Builder.CreateFMul(X, Z);
716 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
717 }
718 }
719
720 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
721 // nnan disallows the possibility of returning a number if both operands are
722 // negative (in that case, we should return NaN).
723 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
724 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
725 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
726 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
727 return replaceInstUsesWith(I, Sqrt);
728 }
729
730 // The following transforms are done irrespective of the number of uses
731 // for the expression "1.0/sqrt(X)".
732 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
733 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
734 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
735 // has the necessary (reassoc) fast-math-flags.
736 if (I.hasNoSignedZeros() &&
737 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
738 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
740 if (I.hasNoSignedZeros() &&
741 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
742 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
744
745 // Like the similar transform in instsimplify, this requires 'nsz' because
746 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
747 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
748 // Peek through fdiv to find squaring of square root:
749 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
750 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
751 Value *XX = Builder.CreateFMulFMF(X, X, &I);
752 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
753 }
754 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
755 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
756 Value *XX = Builder.CreateFMulFMF(X, X, &I);
757 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
758 }
759 }
760
761 // pow(X, Y) * X --> pow(X, Y+1)
762 // X * pow(X, Y) --> pow(X, Y+1)
763 if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Value(X),
764 m_Value(Y))),
765 m_Deferred(X)))) {
766 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
767 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
768 return replaceInstUsesWith(I, Pow);
769 }
770
771 if (Instruction *FoldedPowi = foldPowiReassoc(I))
772 return FoldedPowi;
773
774 if (I.isOnlyUserOfAnyOperand()) {
775 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
776 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
777 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) {
778 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
779 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
780 return replaceInstUsesWith(I, NewPow);
781 }
782 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
783 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
784 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Value(Z), m_Specific(Y)))) {
785 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
786 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
787 return replaceInstUsesWith(I, NewPow);
788 }
789
790 // exp(X) * exp(Y) -> exp(X + Y)
791 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
792 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) {
793 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
794 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
795 return replaceInstUsesWith(I, Exp);
796 }
797
798 // exp2(X) * exp2(Y) -> exp2(X + Y)
799 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
800 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) {
801 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
802 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
803 return replaceInstUsesWith(I, Exp2);
804 }
805 }
806
807 // (X*Y) * X => (X*X) * Y where Y != X
808 // The purpose is two-fold:
809 // 1) to form a power expression (of X).
810 // 2) potentially shorten the critical path: After transformation, the
811 // latency of the instruction Y is amortized by the expression of X*X,
812 // and therefore Y is in a "less critical" position compared to what it
813 // was before the transformation.
814 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
815 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
816 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
817 }
818 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
819 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
820 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
821 }
822
823 return nullptr;
824}
825
827 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
828 I.getFastMathFlags(),
830 return replaceInstUsesWith(I, V);
831
833 return &I;
834
836 return X;
837
839 return Phi;
840
841 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
842 return FoldedMul;
843
844 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
845 return replaceInstUsesWith(I, FoldedMul);
846
847 if (Instruction *R = foldFPSignBitOps(I))
848 return R;
849
850 if (Instruction *R = foldFBinOpOfIntCasts(I))
851 return R;
852
853 // X * -1.0 --> -X
854 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
855 if (match(Op1, m_SpecificFP(-1.0)))
856 return UnaryOperator::CreateFNegFMF(Op0, &I);
857
858 // With no-nans/no-infs:
859 // X * 0.0 --> copysign(0.0, X)
860 // X * -0.0 --> copysign(0.0, -X)
861 const APFloat *FPC;
862 if (match(Op1, m_APFloatAllowPoison(FPC)) && FPC->isZero() &&
863 ((I.hasNoInfs() &&
864 isKnownNeverNaN(Op0, /*Depth=*/0, SQ.getWithInstruction(&I))) ||
865 isKnownNeverNaN(&I, /*Depth=*/0, SQ.getWithInstruction(&I)))) {
866 if (FPC->isNegative())
867 Op0 = Builder.CreateFNegFMF(Op0, &I);
868 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
869 {I.getType()}, {Op1, Op0}, &I);
870 return replaceInstUsesWith(I, CopySign);
871 }
872
873 // -X * C --> X * -C
874 Value *X, *Y;
875 Constant *C;
876 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
877 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
878 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
879
880 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
881 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
882 return replaceInstUsesWith(I, V);
883
884 if (I.hasAllowReassoc())
885 if (Instruction *FoldedMul = foldFMulReassoc(I))
886 return FoldedMul;
887
888 // log2(X * 0.5) * Y = log2(X) * Y - Y
889 if (I.isFast()) {
890 IntrinsicInst *Log2 = nullptr;
891 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
892 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
893 Log2 = cast<IntrinsicInst>(Op0);
894 Y = Op1;
895 }
896 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
897 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
898 Log2 = cast<IntrinsicInst>(Op1);
899 Y = Op0;
900 }
901 if (Log2) {
902 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
903 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
904 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
905 }
906 }
907
908 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
909 // Given a phi node with entry value as 0 and it used in fmul operation,
910 // we can replace fmul with 0 safely and eleminate loop operation.
911 PHINode *PN = nullptr;
912 Value *Start = nullptr, *Step = nullptr;
913 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
914 I.hasNoSignedZeros() && match(Start, m_Zero()))
915 return replaceInstUsesWith(I, Start);
916
917 // minimum(X, Y) * maximum(X, Y) => X * Y.
918 if (match(&I,
919 m_c_FMul(m_Intrinsic<Intrinsic::maximum>(m_Value(X), m_Value(Y)),
920 m_c_Intrinsic<Intrinsic::minimum>(m_Deferred(X),
921 m_Deferred(Y))))) {
923 // We cannot preserve ninf if nnan flag is not set.
924 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
925 // while in optimized version NaN * Inf and this is a poison with ninf flag.
926 if (!Result->hasNoNaNs())
927 Result->setHasNoInfs(false);
928 return Result;
929 }
930
931 return nullptr;
932}
933
934/// Fold a divide or remainder with a select instruction divisor when one of the
935/// select operands is zero. In that case, we can use the other select operand
936/// because div/rem by zero is undefined.
938 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
939 if (!SI)
940 return false;
941
942 int NonNullOperand;
943 if (match(SI->getTrueValue(), m_Zero()))
944 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
945 NonNullOperand = 2;
946 else if (match(SI->getFalseValue(), m_Zero()))
947 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
948 NonNullOperand = 1;
949 else
950 return false;
951
952 // Change the div/rem to use 'Y' instead of the select.
953 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
954
955 // Okay, we know we replace the operand of the div/rem with 'Y' with no
956 // problem. However, the select, or the condition of the select may have
957 // multiple uses. Based on our knowledge that the operand must be non-zero,
958 // propagate the known value for the select into other uses of it, and
959 // propagate a known value of the condition into its other users.
960
961 // If the select and condition only have a single use, don't bother with this,
962 // early exit.
963 Value *SelectCond = SI->getCondition();
964 if (SI->use_empty() && SelectCond->hasOneUse())
965 return true;
966
967 // Scan the current block backward, looking for other uses of SI.
968 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
969 Type *CondTy = SelectCond->getType();
970 while (BBI != BBFront) {
971 --BBI;
972 // If we found an instruction that we can't assume will return, so
973 // information from below it cannot be propagated above it.
975 break;
976
977 // Replace uses of the select or its condition with the known values.
978 for (Use &Op : BBI->operands()) {
979 if (Op == SI) {
980 replaceUse(Op, SI->getOperand(NonNullOperand));
981 Worklist.push(&*BBI);
982 } else if (Op == SelectCond) {
983 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
984 : ConstantInt::getFalse(CondTy));
985 Worklist.push(&*BBI);
986 }
987 }
988
989 // If we past the instruction, quit looking for it.
990 if (&*BBI == SI)
991 SI = nullptr;
992 if (&*BBI == SelectCond)
993 SelectCond = nullptr;
994
995 // If we ran out of things to eliminate, break out of the loop.
996 if (!SelectCond && !SI)
997 break;
998
999 }
1000 return true;
1001}
1002
1003/// True if the multiply can not be expressed in an int this size.
1004static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1005 bool IsSigned) {
1006 bool Overflow;
1007 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
1008 return Overflow;
1009}
1010
1011/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1012static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1013 bool IsSigned) {
1014 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1015
1016 // Bail if we will divide by zero.
1017 if (C2.isZero())
1018 return false;
1019
1020 // Bail if we would divide INT_MIN by -1.
1021 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1022 return false;
1023
1024 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1025 if (IsSigned)
1026 APInt::sdivrem(C1, C2, Quotient, Remainder);
1027 else
1028 APInt::udivrem(C1, C2, Quotient, Remainder);
1029
1030 return Remainder.isMinValue();
1031}
1032
1034 assert((I.getOpcode() == Instruction::SDiv ||
1035 I.getOpcode() == Instruction::UDiv) &&
1036 "Expected integer divide");
1037
1038 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1040 Type *Ty = I.getType();
1041
1042 Value *X, *Y, *Z;
1043
1044 // With appropriate no-wrap constraints, remove a common factor in the
1045 // dividend and divisor that is disguised as a left-shifted value.
1046 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1047 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1048 // Both operands must have the matching no-wrap for this kind of division.
1049 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1050 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1051 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1052 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1053
1054 // (X * Y) u/ (X << Z) --> Y u>> Z
1055 if (!IsSigned && HasNUW)
1056 return Builder.CreateLShr(Y, Z, "", I.isExact());
1057
1058 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1059 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1060 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1061 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1062 }
1063 }
1064
1065 // With appropriate no-wrap constraints, remove a common factor in the
1066 // dividend and divisor that is disguised as a left-shift amount.
1067 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1068 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1069 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1070 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1071
1072 // For unsigned div, we need 'nuw' on both shifts or
1073 // 'nsw' on both shifts + 'nuw' on the dividend.
1074 // (X << Z) / (Y << Z) --> X / Y
1075 if (!IsSigned &&
1076 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1077 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1078 Shl1->hasNoSignedWrap())))
1079 return Builder.CreateUDiv(X, Y, "", I.isExact());
1080
1081 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1082 // (X << Z) / (Y << Z) --> X / Y
1083 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1084 Shl1->hasNoUnsignedWrap())
1085 return Builder.CreateSDiv(X, Y, "", I.isExact());
1086 }
1087
1088 // If X << Y and X << Z does not overflow, then:
1089 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1090 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1091 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1092 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1093 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1094
1095 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1096 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1097 Constant *One = ConstantInt::get(X->getType(), 1);
1098 // Only preserve the nsw flag if dividend has nsw
1099 // or divisor has nsw and operator is sdiv.
1100 Value *Dividend = Builder.CreateShl(
1101 One, Y, "shl.dividend",
1102 /*HasNUW*/ true,
1103 /*HasNSW*/
1104 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1105 : Shl0->hasNoSignedWrap());
1106 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1107 }
1108 }
1109
1110 return nullptr;
1111}
1112
1113/// This function implements the transforms common to both integer division
1114/// instructions (udiv and sdiv). It is called by the visitors to those integer
1115/// division instructions.
1116/// Common integer divide transforms
1119 return Phi;
1120
1121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1122 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1123 Type *Ty = I.getType();
1124
1125 // The RHS is known non-zero.
1126 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1127 return replaceOperand(I, 1, V);
1128
1129 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1130 // This does not apply for fdiv.
1132 return &I;
1133
1134 // If the divisor is a select-of-constants, try to constant fold all div ops:
1135 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC)
1136 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1137 if (match(Op0, m_ImmConstant()) &&
1139 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1140 /*FoldWithMultiUse*/ true))
1141 return R;
1142 }
1143
1144 const APInt *C2;
1145 if (match(Op1, m_APInt(C2))) {
1146 Value *X;
1147 const APInt *C1;
1148
1149 // (X / C1) / C2 -> X / (C1*C2)
1150 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1151 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1152 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1153 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1154 return BinaryOperator::Create(I.getOpcode(), X,
1155 ConstantInt::get(Ty, Product));
1156 }
1157
1158 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1159 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1160 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1161
1162 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1163 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1164 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1165 ConstantInt::get(Ty, Quotient));
1166 NewDiv->setIsExact(I.isExact());
1167 return NewDiv;
1168 }
1169
1170 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1171 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1172 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1173 ConstantInt::get(Ty, Quotient));
1174 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1175 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1176 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1177 return Mul;
1178 }
1179 }
1180
1181 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1182 C1->ult(C1->getBitWidth() - 1)) ||
1183 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1184 C1->ult(C1->getBitWidth()))) {
1185 APInt C1Shifted = APInt::getOneBitSet(
1186 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1187
1188 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1189 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1190 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1191 ConstantInt::get(Ty, Quotient));
1192 BO->setIsExact(I.isExact());
1193 return BO;
1194 }
1195
1196 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1197 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1198 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1199 ConstantInt::get(Ty, Quotient));
1200 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1201 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1202 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1203 return Mul;
1204 }
1205 }
1206
1207 // Distribute div over add to eliminate a matching div/mul pair:
1208 // ((X * C2) + C1) / C2 --> X + C1/C2
1209 // We need a multiple of the divisor for a signed add constant, but
1210 // unsigned is fine with any constant pair.
1211 if (IsSigned &&
1213 m_APInt(C1))) &&
1214 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1215 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1216 }
1217 if (!IsSigned &&
1219 m_APInt(C1)))) {
1220 return BinaryOperator::CreateNUWAdd(X,
1221 ConstantInt::get(Ty, C1->udiv(*C2)));
1222 }
1223
1224 if (!C2->isZero()) // avoid X udiv 0
1225 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1226 return FoldedDiv;
1227 }
1228
1229 if (match(Op0, m_One())) {
1230 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1231 if (IsSigned) {
1232 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1233 // (Op1 + 1) u< 3 ? Op1 : 0
1234 // Op1 must be frozen because we are increasing its number of uses.
1235 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1236 Value *Inc = Builder.CreateAdd(F1, Op0);
1237 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1238 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1239 } else {
1240 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1241 // result is one, otherwise it's zero.
1242 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1243 }
1244 }
1245
1246 // See if we can fold away this div instruction.
1248 return &I;
1249
1250 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1251 Value *X, *Z;
1252 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1253 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1254 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1255 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1256
1257 // (X << Y) / X -> 1 << Y
1258 Value *Y;
1259 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1260 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1261 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1262 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1263
1264 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1265 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1266 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1267 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1268 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1269 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1270 replaceOperand(I, 1, Y);
1271 return &I;
1272 }
1273 }
1274
1275 // (X << Z) / (X * Y) -> (1 << Z) / Y
1276 // TODO: Handle sdiv.
1277 if (!IsSigned && Op1->hasOneUse() &&
1278 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1279 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1280 if (cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap()) {
1281 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1282 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1283 NewDiv->setIsExact(I.isExact());
1284 return NewDiv;
1285 }
1286
1287 if (Value *R = foldIDivShl(I, Builder))
1288 return replaceInstUsesWith(I, R);
1289
1290 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1291 // after peeking through another divide:
1292 // ((Op1 * X) / Y) / Op1 --> X / Y
1293 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1294 m_Value(Y)))) {
1295 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1296 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1297 Instruction *NewDiv = nullptr;
1298 if (!IsSigned && Mul->hasNoUnsignedWrap())
1299 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1300 else if (IsSigned && Mul->hasNoSignedWrap())
1301 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1302
1303 // Exact propagates only if both of the original divides are exact.
1304 if (NewDiv) {
1305 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1306 return NewDiv;
1307 }
1308 }
1309
1310 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1311 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1312 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1313 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1314
1315 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1316 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1317 auto OB1HasNUW =
1318 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1319 const APInt *C1, *C2;
1320 if (IsSigned && OB0HasNSW) {
1321 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1322 return BinaryOperator::CreateSDiv(A, B);
1323 }
1324 if (!IsSigned && OB0HasNUW) {
1325 if (OB1HasNUW)
1326 return BinaryOperator::CreateUDiv(A, B);
1327 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1328 return BinaryOperator::CreateUDiv(A, B);
1329 }
1330 return nullptr;
1331 };
1332
1333 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1334 if (auto *Val = CreateDivOrNull(Y, Z))
1335 return Val;
1336 }
1337 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1338 if (auto *Val = CreateDivOrNull(X, Z))
1339 return Val;
1340 }
1341 }
1342 return nullptr;
1343}
1344
1345static const unsigned MaxDepth = 6;
1346
1347// Take the exact integer log2 of the value. If DoFold is true, create the
1348// actual instructions, otherwise return a non-null dummy value. Return nullptr
1349// on failure.
1350static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
1351 bool AssumeNonZero, bool DoFold) {
1352 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1353 if (!DoFold)
1354 return reinterpret_cast<Value *>(-1);
1355 return Fn();
1356 };
1357
1358 // FIXME: assert that Op1 isn't/doesn't contain undef.
1359
1360 // log2(2^C) -> C
1361 if (match(Op, m_Power2()))
1362 return IfFold([&]() {
1363 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op));
1364 if (!C)
1365 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1366 return C;
1367 });
1368
1369 // The remaining tests are all recursive, so bail out if we hit the limit.
1370 if (Depth++ == MaxDepth)
1371 return nullptr;
1372
1373 // log2(zext X) -> zext log2(X)
1374 // FIXME: Require one use?
1375 Value *X, *Y;
1376 if (match(Op, m_ZExt(m_Value(X))))
1377 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1378 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1379
1380 // log2(X << Y) -> log2(X) + Y
1381 // FIXME: Require one use unless X is 1?
1382 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1383 auto *BO = cast<OverflowingBinaryOperator>(Op);
1384 // nuw will be set if the `shl` is trivially non-zero.
1385 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1386 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1387 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1388 }
1389
1390 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1391 // FIXME: Require one use?
1392 if (SelectInst *SI = dyn_cast<SelectInst>(Op))
1393 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth,
1394 AssumeNonZero, DoFold))
1395 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth,
1396 AssumeNonZero, DoFold))
1397 return IfFold([&]() {
1398 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1399 });
1400
1401 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1402 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1403 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op);
1404 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1405 // Use AssumeNonZero as false here. Otherwise we can hit case where
1406 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1407 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth,
1408 /*AssumeNonZero*/ false, DoFold))
1409 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth,
1410 /*AssumeNonZero*/ false, DoFold))
1411 return IfFold([&]() {
1412 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1413 LogY);
1414 });
1415 }
1416
1417 return nullptr;
1418}
1419
1420/// If we have zero-extended operands of an unsigned div or rem, we may be able
1421/// to narrow the operation (sink the zext below the math).
1423 InstCombinerImpl &IC) {
1424 Instruction::BinaryOps Opcode = I.getOpcode();
1425 Value *N = I.getOperand(0);
1426 Value *D = I.getOperand(1);
1427 Type *Ty = I.getType();
1428 Value *X, *Y;
1429 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1430 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1431 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1432 // urem (zext X), (zext Y) --> zext (urem X, Y)
1433 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1434 return new ZExtInst(NarrowOp, Ty);
1435 }
1436
1437 Constant *C;
1438 if (isa<Instruction>(N) && match(N, m_OneUse(m_ZExt(m_Value(X)))) &&
1439 match(D, m_Constant(C))) {
1440 // If the constant is the same in the smaller type, use the narrow version.
1441 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1442 if (!TruncC)
1443 return nullptr;
1444
1445 // udiv (zext X), C --> zext (udiv X, C')
1446 // urem (zext X), C --> zext (urem X, C')
1447 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1448 }
1449 if (isa<Instruction>(D) && match(D, m_OneUse(m_ZExt(m_Value(X)))) &&
1450 match(N, m_Constant(C))) {
1451 // If the constant is the same in the smaller type, use the narrow version.
1452 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1453 if (!TruncC)
1454 return nullptr;
1455
1456 // udiv C, (zext X) --> zext (udiv C', X)
1457 // urem C, (zext X) --> zext (urem C', X)
1458 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1459 }
1460
1461 return nullptr;
1462}
1463
1465 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1467 return replaceInstUsesWith(I, V);
1468
1470 return X;
1471
1472 // Handle the integer div common cases
1473 if (Instruction *Common = commonIDivTransforms(I))
1474 return Common;
1475
1476 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1477 Value *X;
1478 const APInt *C1, *C2;
1479 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1480 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1481 bool Overflow;
1482 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1483 if (!Overflow) {
1484 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1485 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1486 X, ConstantInt::get(X->getType(), C2ShlC1));
1487 if (IsExact)
1488 BO->setIsExact();
1489 return BO;
1490 }
1491 }
1492
1493 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1494 // TODO: Could use isKnownNegative() to handle non-constant values.
1495 Type *Ty = I.getType();
1496 if (match(Op1, m_Negative())) {
1497 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1498 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1499 }
1500 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1501 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1503 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1504 }
1505
1506 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1507 return NarrowDiv;
1508
1509 Value *A, *B;
1510
1511 // Look through a right-shift to find the common factor:
1512 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1513 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1514 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1515 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1516 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1517 Lshr->setIsExact();
1518 return Lshr;
1519 }
1520
1521 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
1522 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ true,
1523 /*DoFold*/ false)) {
1524 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0,
1525 /*AssumeNonZero*/ true, /*DoFold*/ true);
1526 return replaceInstUsesWith(
1527 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1528 }
1529
1530 return nullptr;
1531}
1532
1534 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1536 return replaceInstUsesWith(I, V);
1537
1539 return X;
1540
1541 // Handle the integer div common cases
1542 if (Instruction *Common = commonIDivTransforms(I))
1543 return Common;
1544
1545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1546 Type *Ty = I.getType();
1547 Value *X;
1548 // sdiv Op0, -1 --> -Op0
1549 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1550 if (match(Op1, m_AllOnes()) ||
1551 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1552 return BinaryOperator::CreateNSWNeg(Op0);
1553
1554 // X / INT_MIN --> X == INT_MIN
1555 if (match(Op1, m_SignMask()))
1556 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1557
1558 if (I.isExact()) {
1559 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1560 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1561 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
1562 return BinaryOperator::CreateExactAShr(Op0, C);
1563 }
1564
1565 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1566 Value *ShAmt;
1567 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1568 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1569
1570 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1571 if (match(Op1, m_NegatedPower2())) {
1572 Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
1574 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1575 return BinaryOperator::CreateNSWNeg(Ashr);
1576 }
1577 }
1578
1579 const APInt *Op1C;
1580 if (match(Op1, m_APInt(Op1C))) {
1581 // If the dividend is sign-extended and the constant divisor is small enough
1582 // to fit in the source type, shrink the division to the narrower type:
1583 // (sext X) sdiv C --> sext (X sdiv C)
1584 Value *Op0Src;
1585 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1586 Op0Src->getType()->getScalarSizeInBits() >=
1587 Op1C->getSignificantBits()) {
1588
1589 // In the general case, we need to make sure that the dividend is not the
1590 // minimum signed value because dividing that by -1 is UB. But here, we
1591 // know that the -1 divisor case is already handled above.
1592
1593 Constant *NarrowDivisor =
1594 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1595 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1596 return new SExtInst(NarrowOp, Ty);
1597 }
1598
1599 // -X / C --> X / -C (if the negation doesn't overflow).
1600 // TODO: This could be enhanced to handle arbitrary vector constants by
1601 // checking if all elements are not the min-signed-val.
1602 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
1603 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1604 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1605 BO->setIsExact(I.isExact());
1606 return BO;
1607 }
1608 }
1609
1610 // -X / Y --> -(X / Y)
1611 Value *Y;
1614 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1615
1616 // abs(X) / X --> X > -1 ? 1 : -1
1617 // X / abs(X) --> X > -1 ? 1 : -1
1618 if (match(&I, m_c_BinOp(
1619 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1620 m_Deferred(X)))) {
1622 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1624 }
1625
1626 KnownBits KnownDividend = computeKnownBits(Op0, 0, &I);
1627 if (!I.isExact() &&
1628 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1629 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1630 I.setIsExact();
1631 return &I;
1632 }
1633
1634 if (KnownDividend.isNonNegative()) {
1635 // If both operands are unsigned, turn this into a udiv.
1637 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1638 BO->setIsExact(I.isExact());
1639 return BO;
1640 }
1641
1642 if (match(Op1, m_NegatedPower2())) {
1643 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1644 // -> -(X udiv (1 << C)) -> -(X u>> C)
1646 ConstantExpr::getNeg(cast<Constant>(Op1)));
1647 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1648 return BinaryOperator::CreateNeg(Shr);
1649 }
1650
1651 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1652 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1653 // Safe because the only negative value (1 << Y) can take on is
1654 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1655 // the sign bit set.
1656 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1657 BO->setIsExact(I.isExact());
1658 return BO;
1659 }
1660 }
1661
1662 // -X / X --> X == INT_MIN ? 1 : -1
1663 if (isKnownNegation(Op0, Op1)) {
1665 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1666 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1668 }
1669 return nullptr;
1670}
1671
1672/// Remove negation and try to convert division into multiplication.
1673Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1674 Constant *C;
1675 if (!match(I.getOperand(1), m_Constant(C)))
1676 return nullptr;
1677
1678 // -X / C --> X / -C
1679 Value *X;
1680 const DataLayout &DL = I.getModule()->getDataLayout();
1681 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1682 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1683 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1684
1685 // nnan X / +0.0 -> copysign(inf, X)
1686 // nnan nsz X / -0.0 -> copysign(inf, X)
1687 if (I.hasNoNaNs() &&
1688 (match(I.getOperand(1), m_PosZeroFP()) ||
1689 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1690 IRBuilder<> B(&I);
1691 CallInst *CopySign = B.CreateIntrinsic(
1692 Intrinsic::copysign, {C->getType()},
1693 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1694 CopySign->takeName(&I);
1695 return replaceInstUsesWith(I, CopySign);
1696 }
1697
1698 // If the constant divisor has an exact inverse, this is always safe. If not,
1699 // then we can still create a reciprocal if fast-math-flags allow it and the
1700 // constant is a regular number (not zero, infinite, or denormal).
1701 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1702 return nullptr;
1703
1704 // Disallow denormal constants because we don't know what would happen
1705 // on all targets.
1706 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1707 // denorms are flushed?
1708 auto *RecipC = ConstantFoldBinaryOpOperands(
1709 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1710 if (!RecipC || !RecipC->isNormalFP())
1711 return nullptr;
1712
1713 // X / C --> X * (1 / C)
1714 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1715}
1716
1717/// Remove negation and try to reassociate constant math.
1719 Constant *C;
1720 if (!match(I.getOperand(0), m_Constant(C)))
1721 return nullptr;
1722
1723 // C / -X --> -C / X
1724 Value *X;
1725 const DataLayout &DL = I.getModule()->getDataLayout();
1726 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1727 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1728 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1729
1730 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1731 return nullptr;
1732
1733 // Try to reassociate C / X expressions where X includes another constant.
1734 Constant *C2, *NewC = nullptr;
1735 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1736 // C / (X * C2) --> (C / C2) / X
1737 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1738 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1739 // C / (X / C2) --> (C * C2) / X
1740 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1741 }
1742 // Disallow denormal constants because we don't know what would happen
1743 // on all targets.
1744 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1745 // denorms are flushed?
1746 if (!NewC || !NewC->isNormalFP())
1747 return nullptr;
1748
1749 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1750}
1751
1752/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1754 InstCombiner::BuilderTy &Builder) {
1755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1756 auto *II = dyn_cast<IntrinsicInst>(Op1);
1757 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1758 !I.hasAllowReciprocal())
1759 return nullptr;
1760
1761 // Z / pow(X, Y) --> Z * pow(X, -Y)
1762 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1763 // In the general case, this creates an extra instruction, but fmul allows
1764 // for better canonicalization and optimization than fdiv.
1765 Intrinsic::ID IID = II->getIntrinsicID();
1767 switch (IID) {
1768 case Intrinsic::pow:
1769 Args.push_back(II->getArgOperand(0));
1770 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1771 break;
1772 case Intrinsic::powi: {
1773 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1774 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1775 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1776 // non-standard results, so this corner case should be acceptable if the
1777 // code rules out INF values.
1778 if (!I.hasNoInfs())
1779 return nullptr;
1780 Args.push_back(II->getArgOperand(0));
1781 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1782 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1783 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1784 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1785 }
1786 case Intrinsic::exp:
1787 case Intrinsic::exp2:
1788 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1789 break;
1790 default:
1791 return nullptr;
1792 }
1793 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1794 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1795}
1796
1797/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
1798/// instruction.
1800 InstCombiner::BuilderTy &Builder) {
1801 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
1802 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1803 return nullptr;
1804 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1805 auto *II = dyn_cast<IntrinsicInst>(Op1);
1806 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
1807 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
1808 return nullptr;
1809
1810 Value *Y, *Z;
1811 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
1812 if (!DivOp)
1813 return nullptr;
1814 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
1815 return nullptr;
1816 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
1817 !DivOp->hasOneUse())
1818 return nullptr;
1819 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
1820 Value *NewSqrt =
1821 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
1822 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
1823}
1824
1826 Module *M = I.getModule();
1827
1828 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
1829 I.getFastMathFlags(),
1831 return replaceInstUsesWith(I, V);
1832
1834 return X;
1835
1837 return Phi;
1838
1839 if (Instruction *R = foldFDivConstantDivisor(I))
1840 return R;
1841
1843 return R;
1844
1845 if (Instruction *R = foldFPSignBitOps(I))
1846 return R;
1847
1848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1849 if (isa<Constant>(Op0))
1850 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1851 if (Instruction *R = FoldOpIntoSelect(I, SI))
1852 return R;
1853
1854 if (isa<Constant>(Op1))
1855 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1856 if (Instruction *R = FoldOpIntoSelect(I, SI))
1857 return R;
1858
1859 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1860 Value *X, *Y;
1861 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1862 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1863 // (X / Y) / Z => X / (Y * Z)
1864 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1865 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1866 }
1867 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1868 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1869 // Z / (X / Y) => (Y * Z) / X
1870 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1871 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1872 }
1873 // Z / (1.0 / Y) => (Y * Z)
1874 //
1875 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1876 // m_OneUse check is avoided because even in the case of the multiple uses
1877 // for 1.0/Y, the number of instructions remain the same and a division is
1878 // replaced by a multiplication.
1879 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1880 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1881 }
1882
1883 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1884 // sin(X) / cos(X) -> tan(X)
1885 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1886 Value *X;
1887 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1888 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1889 bool IsCot =
1890 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1891 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1892
1893 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
1894 LibFunc_tanf, LibFunc_tanl)) {
1895 IRBuilder<> B(&I);
1897 B.setFastMathFlags(I.getFastMathFlags());
1898 AttributeList Attrs =
1899 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1900 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1901 LibFunc_tanl, B, Attrs);
1902 if (IsCot)
1903 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1904 return replaceInstUsesWith(I, Res);
1905 }
1906 }
1907
1908 // X / (X * Y) --> 1.0 / Y
1909 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1910 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1911 Value *X, *Y;
1912 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1913 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1914 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1915 replaceOperand(I, 1, Y);
1916 return &I;
1917 }
1918
1919 // X / fabs(X) -> copysign(1.0, X)
1920 // fabs(X) / X -> copysign(1.0, X)
1921 if (I.hasNoNaNs() && I.hasNoInfs() &&
1922 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1923 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1925 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1926 return replaceInstUsesWith(I, V);
1927 }
1928
1930 return Mul;
1931
1933 return Mul;
1934
1935 // pow(X, Y) / X --> pow(X, Y-1)
1936 if (I.hasAllowReassoc() &&
1937 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Specific(Op1),
1938 m_Value(Y))))) {
1939 Value *Y1 =
1940 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
1941 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
1942 return replaceInstUsesWith(I, Pow);
1943 }
1944
1945 if (Instruction *FoldedPowi = foldPowiReassoc(I))
1946 return FoldedPowi;
1947
1948 return nullptr;
1949}
1950
1951// Variety of transform for:
1952// (urem/srem (mul X, Y), (mul X, Z))
1953// (urem/srem (shl X, Y), (shl X, Z))
1954// (urem/srem (shl Y, X), (shl Z, X))
1955// NB: The shift cases are really just extensions of the mul case. We treat
1956// shift as Val * (1 << Amt).
1958 InstCombinerImpl &IC) {
1959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
1960 APInt Y, Z;
1961 bool ShiftByX = false;
1962
1963 // If V is not nullptr, it will be matched using m_Specific.
1964 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C) -> bool {
1965 const APInt *Tmp = nullptr;
1966 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
1967 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
1968 C = *Tmp;
1969 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
1970 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp)))))
1971 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
1972 if (Tmp != nullptr)
1973 return true;
1974
1975 // Reset `V` so we don't start with specific value on next match attempt.
1976 V = nullptr;
1977 return false;
1978 };
1979
1980 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
1981 const APInt *Tmp = nullptr;
1982 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
1983 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
1984 C = *Tmp;
1985 return true;
1986 }
1987
1988 // Reset `V` so we don't start with specific value on next match attempt.
1989 V = nullptr;
1990 return false;
1991 };
1992
1993 if (MatchShiftOrMulXC(Op0, X, Y) && MatchShiftOrMulXC(Op1, X, Z)) {
1994 // pass
1995 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
1996 ShiftByX = true;
1997 } else {
1998 return nullptr;
1999 }
2000
2001 bool IsSRem = I.getOpcode() == Instruction::SRem;
2002
2003 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Op0);
2004 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2005 // Z or Z >= Y.
2006 bool BO0HasNSW = BO0->hasNoSignedWrap();
2007 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2008 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2009
2010 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
2011 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2012 // if (rem Y, Z) == 0
2013 // -> 0
2014 if (RemYZ.isZero() && BO0NoWrap)
2015 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
2016
2017 // Helper function to emit either (RemSimplificationC << X) or
2018 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2019 // (shl V, X) or (mul V, X) respectively.
2020 auto CreateMulOrShift =
2021 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2022 Value *RemSimplification =
2023 ConstantInt::get(I.getType(), RemSimplificationC);
2024 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2025 : BinaryOperator::CreateMul(X, RemSimplification);
2026 };
2027
2028 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Op1);
2029 bool BO1HasNSW = BO1->hasNoSignedWrap();
2030 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2031 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2032 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2033 // if (rem Y, Z) == Y
2034 // -> (mul nuw/nsw X, Y)
2035 if (RemYZ == Y && BO1NoWrap) {
2036 BinaryOperator *BO = CreateMulOrShift(Y);
2037 // Copy any overflow flags from Op0.
2038 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2039 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2040 return BO;
2041 }
2042
2043 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2044 // if Y >= Z
2045 // -> (mul {nuw} nsw X, (rem Y, Z))
2046 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2047 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2048 BO->setHasNoSignedWrap();
2049 BO->setHasNoUnsignedWrap(BO0HasNUW);
2050 return BO;
2051 }
2052
2053 return nullptr;
2054}
2055
2056/// This function implements the transforms common to both integer remainder
2057/// instructions (urem and srem). It is called by the visitors to those integer
2058/// remainder instructions.
2059/// Common integer remainder transforms
2062 return Phi;
2063
2064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2065
2066 // The RHS is known non-zero.
2067 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
2068 return replaceOperand(I, 1, V);
2069
2070 // Handle cases involving: rem X, (select Cond, Y, Z)
2072 return &I;
2073
2074 // If the divisor is a select-of-constants, try to constant fold all rem ops:
2075 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
2076 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
2077 if (match(Op0, m_ImmConstant()) &&
2079 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
2080 /*FoldWithMultiUse*/ true))
2081 return R;
2082 }
2083
2084 if (isa<Constant>(Op1)) {
2085 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2086 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2087 if (Instruction *R = FoldOpIntoSelect(I, SI))
2088 return R;
2089 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2090 const APInt *Op1Int;
2091 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2092 (I.getOpcode() == Instruction::URem ||
2093 !Op1Int->isMinSignedValue())) {
2094 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2095 // predecessor blocks, so do this only if we know the srem or urem
2096 // will not fault.
2097 if (Instruction *NV = foldOpIntoPhi(I, PN))
2098 return NV;
2099 }
2100 }
2101
2102 // See if we can fold away this rem instruction.
2104 return &I;
2105 }
2106 }
2107
2108 if (Instruction *R = simplifyIRemMulShl(I, *this))
2109 return R;
2110
2111 return nullptr;
2112}
2113
2115 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2117 return replaceInstUsesWith(I, V);
2118
2120 return X;
2121
2122 if (Instruction *common = commonIRemTransforms(I))
2123 return common;
2124
2125 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2126 return NarrowRem;
2127
2128 // X urem Y -> X and Y-1, where Y is a power of 2,
2129 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2130 Type *Ty = I.getType();
2131 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
2132 // This may increase instruction count, we don't enforce that Y is a
2133 // constant.
2135 Value *Add = Builder.CreateAdd(Op1, N1);
2136 return BinaryOperator::CreateAnd(Op0, Add);
2137 }
2138
2139 // 1 urem X -> zext(X != 1)
2140 if (match(Op0, m_One())) {
2141 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2142 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2143 }
2144
2145 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2146 // Op0 must be frozen because we are increasing its number of uses.
2147 if (match(Op1, m_Negative())) {
2148 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2149 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2150 Value *Sub = Builder.CreateSub(F0, Op1);
2151 return SelectInst::Create(Cmp, F0, Sub);
2152 }
2153
2154 // If the divisor is a sext of a boolean, then the divisor must be max
2155 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2156 // max unsigned value. In that case, the remainder is 0:
2157 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2158 Value *X;
2159 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2160 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2161 Value *Cmp =
2163 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2164 }
2165
2166 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2167 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2168 Value *Val =
2170 if (Val && match(Val, m_One())) {
2171 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2172 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2173 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2174 }
2175 }
2176
2177 return nullptr;
2178}
2179
2181 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2183 return replaceInstUsesWith(I, V);
2184
2186 return X;
2187
2188 // Handle the integer rem common cases
2189 if (Instruction *Common = commonIRemTransforms(I))
2190 return Common;
2191
2192 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2193 {
2194 const APInt *Y;
2195 // X % -Y -> X % Y
2196 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2197 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2198 }
2199
2200 // -X srem Y --> -(X srem Y)
2201 Value *X, *Y;
2204
2205 // If the sign bits of both operands are zero (i.e. we can prove they are
2206 // unsigned inputs), turn this into a urem.
2207 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2208 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
2209 MaskedValueIsZero(Op0, Mask, 0, &I)) {
2210 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2211 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2212 }
2213
2214 // If it's a constant vector, flip any negative values positive.
2215 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
2216 Constant *C = cast<Constant>(Op1);
2217 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2218
2219 bool hasNegative = false;
2220 bool hasMissing = false;
2221 for (unsigned i = 0; i != VWidth; ++i) {
2222 Constant *Elt = C->getAggregateElement(i);
2223 if (!Elt) {
2224 hasMissing = true;
2225 break;
2226 }
2227
2228 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2229 if (RHS->isNegative())
2230 hasNegative = true;
2231 }
2232
2233 if (hasNegative && !hasMissing) {
2234 SmallVector<Constant *, 16> Elts(VWidth);
2235 for (unsigned i = 0; i != VWidth; ++i) {
2236 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2237 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2238 if (RHS->isNegative())
2239 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2240 }
2241 }
2242
2243 Constant *NewRHSV = ConstantVector::get(Elts);
2244 if (NewRHSV != C) // Don't loop on -MININT
2245 return replaceOperand(I, 1, NewRHSV);
2246 }
2247 }
2248
2249 return nullptr;
2250}
2251
2253 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2254 I.getFastMathFlags(),
2256 return replaceInstUsesWith(I, V);
2257
2259 return X;
2260
2262 return Phi;
2263
2264 return nullptr;
2265}
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
bool isNegative() const
Definition: APFloat.h:1295
bool isZero() const
Definition: APFloat.h:1291
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1941
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1543
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition: APInt.cpp:1728
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:1498
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1860
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:1446
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:1596
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:1975
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1489
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1930
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:165
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:324
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:513
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, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:332
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:336
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:328
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:299
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:1362
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:1018
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2560
static Constant * getNeg(Constant *C, bool HasNSW=false)
Definition: Constants.cpp:2523
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:2567
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:81
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
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool allowReassoc() const
Flag queries.
Definition: FMF.h:65
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:1547
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:2258
Value * CreateSRem(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1410
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:1601
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:1628
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:466
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:1740
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1090
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2536
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1437
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2560
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:311
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1370
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1378
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2246
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1721
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2242
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition: IRBuilder.h:2555
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1344
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1416
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2022
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1475
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1327
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1391
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2008
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1666
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2254
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1456
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1587
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1730
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1361
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:441
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:418
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:410
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
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:447
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.
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
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:77
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:110
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:104
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:191
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:524
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
Definition: PatternMatch.h:550
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:664
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
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:619
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:165
AllowReassoc_match< T > m_AllowReassoc(const T &SubPattern)
Definition: PatternMatch.h:83
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:972
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:764
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:875
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
Definition: PatternMatch.h:980
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
Definition: PatternMatch.h:560
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
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:918
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:893
apint_match m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
Definition: PatternMatch.h:305
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:854
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:627
apfloat_match m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
Definition: PatternMatch.h:322
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)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
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.
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:773
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:612
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
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.
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.
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.
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 isKnownNeverNaN(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
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
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96