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