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