LLVM 24.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"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constant.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/InstrTypes.h"
25#include "llvm/IR/Instruction.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Operator.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
38#include <cassert>
39
40#define DEBUG_TYPE "instcombine"
42
43using namespace llvm;
44using namespace PatternMatch;
45
46/// The specific integer value is used in a context where it is known to be
47/// non-zero. If this allows us to simplify the computation, do so and return
48/// the new operand, otherwise return null.
50 Instruction &CtxI) {
51 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
54 if (!V->hasOneUse()) return nullptr;
55
56 bool MadeChange = false;
57
58 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
60 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
63 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
65 }
66
67 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
70 if (I && I->isLogicalShift() &&
71 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, &CtxI)) {
72 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 {
77 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CtxI)) {
78 IC.replaceOperand(*I, 0, V2);
79 MadeChange = true;
80 }
81 }
82
83 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
84 I->setIsExact();
85 MadeChange = true;
86 }
87
88 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
89 I->setHasNoUnsignedWrap();
90 MadeChange = true;
91 }
92 }
93
94 // TODO: Lots more we could do here:
95 // If V is a phi node, we can call this on each of its operands.
96 // "select cond, X, 0" can simplify to "X".
97
98 return MadeChange ? V : nullptr;
99}
100
101// TODO: This is a specific form of a much more general pattern.
102// We could detect a select with any binop identity constant, or we
103// could use SimplifyBinOp to see if either arm of the select reduces.
104// But that needs to be done carefully and/or while removing potential
105// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
107 InstCombiner::BuilderTy &Builder) {
108 Value *Cond, *OtherOp;
109 Instruction *SI = nullptr;
110
111 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
112 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
115 m_Value(OtherOp)))) {
116 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
117 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
118 return Builder.CreateSelect(Cond, OtherOp, Neg, "",
120 }
121 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
122 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
125 m_Value(OtherOp)))) {
126 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
127 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
128 return Builder.CreateSelect(Cond, Neg, OtherOp, "",
130 }
131
132 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
133 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
136 m_SpecificFP(-1.0)))),
137 m_Value(OtherOp))))
138 return Builder.CreateSelectFMF(
139 Cond, OtherOp, Builder.CreateFNegFMF(OtherOp, &I), &I, "",
141
142 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
143 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
146 m_SpecificFP(1.0)))),
147 m_Value(OtherOp))))
148 return Builder.CreateSelectFMF(
149 Cond, Builder.CreateFNegFMF(OtherOp, &I), OtherOp, &I, "",
151
152 return nullptr;
153}
154
155/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
156/// Callers are expected to call this twice to handle commuted patterns.
157static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
158 InstCombiner::BuilderTy &Builder) {
159 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
160 if (CommuteOperands)
161 std::swap(X, Y);
162
163 const bool HasNSW = Mul.hasNoSignedWrap();
164 const bool HasNUW = Mul.hasNoUnsignedWrap();
165
166 // X * (1 << Z) --> X << Z
167 Value *Z;
168 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
169 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
170 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
171 }
172
173 // Similar to above, but an increment of the shifted value becomes an add:
174 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
175 // This increases uses of X, so it may require a freeze, but that is still
176 // expected to be an improvement because it removes the multiply.
177 BinaryOperator *Shift;
178 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
179 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
180 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
181 Value *FrX = X;
183 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
184 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
185 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
186 }
187
188 // Similar to above, but a decrement of the shifted value is disguised as
189 // 'not' and becomes a sub:
190 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
191 // This increases uses of X, so it may require a freeze, but that is still
192 // expected to be an improvement because it removes the multiply.
194 Value *FrX = X;
196 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
197 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
198 return Builder.CreateSub(Shl, FrX, Mul.getName());
199 }
200
201 return nullptr;
202}
203
205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
206 if (Value *V =
207 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
208 SQ.getWithInstruction(&I)))
209 return replaceInstUsesWith(I, V);
210
212 return &I;
213
215 return X;
216
218 return Phi;
219
221 return replaceInstUsesWith(I, V);
222
223 Type *Ty = I.getType();
224 const unsigned BitWidth = Ty->getScalarSizeInBits();
225 const bool HasNSW = I.hasNoSignedWrap();
226 const bool HasNUW = I.hasNoUnsignedWrap();
227
228 // X * -1 --> 0 - X
229 if (match(Op1, m_AllOnes())) {
230 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
232 }
233
234 // Also allow combining multiply instructions on vectors.
235 {
236 Value *NewOp;
237 Constant *C1, *C2;
238 const APInt *IVal;
239 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_ImmConstant(C2)),
240 m_ImmConstant(C1))) &&
241 match(C1, m_APInt(IVal))) {
242 // ((X << C2)*C1) == (X * (C1 << C2))
243 Constant *Shl =
244 ConstantFoldBinaryOpOperands(Instruction::Shl, C1, C2, DL);
245 assert(Shl && "Constant folding of immediate constants failed");
246 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
247 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
248 if (HasNUW && Mul->hasNoUnsignedWrap())
250 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
251 BO->setHasNoSignedWrap();
252 return BO;
253 }
254
255 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
256 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
258 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
259
260 if (HasNUW)
262 if (HasNSW) {
263 const APInt *V;
264 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
265 Shl->setHasNoSignedWrap();
266 }
267
268 return Shl;
269 }
270 }
271 }
272
273 // mul (shr exact X, N), (2^N + 1) -> add (X, shr exact (X, N))
274 {
275 Value *NewOp;
276 const APInt *ShiftC;
277 const APInt *MulAP;
278 if (BitWidth > 2 &&
279 match(&I, m_Mul(m_Exact(m_Shr(m_Value(NewOp), m_APInt(ShiftC))),
280 m_APInt(MulAP))) &&
281 (*MulAP - 1).isPowerOf2() && *ShiftC == MulAP->logBase2()) {
282 Value *BinOp = Op0;
284
285 // mul nuw (ashr exact X, N) -> add nuw (X, lshr exact (X, N))
286 if (HasNUW && OpBO->getOpcode() == Instruction::AShr && OpBO->hasOneUse())
287 BinOp = Builder.CreateLShr(NewOp, ConstantInt::get(Ty, *ShiftC), "",
288 /*isExact=*/true);
289
290 auto *NewAdd = BinaryOperator::CreateAdd(NewOp, BinOp);
291 if (HasNSW && (HasNUW || OpBO->getOpcode() == Instruction::LShr ||
292 ShiftC->getZExtValue() < BitWidth - 1))
293 NewAdd->setHasNoSignedWrap(true);
294
295 NewAdd->setHasNoUnsignedWrap(HasNUW);
296 return NewAdd;
297 }
298 }
299
300 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
301 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
302 // The "* (1<<C)" thus becomes a potential shifting opportunity.
303 if (Value *NegOp0 =
304 Negator::Negate(/*IsNegation*/ true, HasNSW, Op0, *this)) {
305 auto *Op1C = cast<Constant>(Op1);
306 return replaceInstUsesWith(
307 I, Builder.CreateMul(NegOp0, ConstantExpr::getNeg(Op1C), "",
308 /*HasNUW=*/false,
309 HasNSW && Op1C->isNotMinSignedValue()));
310 }
311
312 // Try to convert multiply of extended operand to narrow negate and shift
313 // for better analysis.
314 // This is valid if the shift amount (trailing zeros in the multiplier
315 // constant) clears more high bits than the bitwidth difference between
316 // source and destination types:
317 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
318 const APInt *NegPow2C;
319 Value *X;
320 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
321 match(Op1, m_APIntAllowPoison(NegPow2C))) {
322 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
323 unsigned ShiftAmt = NegPow2C->countr_zero();
324 if (ShiftAmt >= BitWidth - SrcWidth) {
325 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
326 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
327 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
328 }
329 }
330 }
331
332 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
333 return FoldedMul;
334
335 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(I))
336 return FoldedLogic;
337
338 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
339 return replaceInstUsesWith(I, FoldedMul);
340
341 // (shl X, C1)*(select cond, C2, C3)--> X * (select cond, C2<<C1, C3<<C1)
342 // (mul X, C1)*(select cond, C2, C3)--> X * (select cond, C2*C1, C3*C1)
343 // (Includes commuted forms)
344
345 {
346 Value *NewOp, *Cond, *OtherValue;
347 Constant *C1, *C2, *C3;
348 Instruction *SI = nullptr;
349
350 if (match(&I, m_c_Mul(m_OneUse(m_Value(OtherValue)),
353 m_ImmConstant(C3)))))) &&
354 (match(OtherValue, m_Mul(m_Value(NewOp), m_ImmConstant(C1))) ||
355 match(OtherValue, m_Shl(m_Value(NewOp), m_ImmConstant(C1))))) {
356
357 auto *OtherInst = cast<OverflowingBinaryOperator>(OtherValue);
358 auto Opc = OtherInst->getOpcode();
359
362
363 if (NewTV && NewFV) {
364 Value *NewSel = Builder.CreateSelect(Cond, NewTV, NewFV, "", SI);
365 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, NewSel);
366
367 if (HasNUW && OtherInst->hasNoUnsignedWrap())
369 if (HasNSW && OtherInst->hasNoSignedWrap() &&
370 NewTV->isNotMinSignedValue() && NewFV->isNotMinSignedValue())
371 BO->setHasNoSignedWrap();
372
373 return BO;
374 }
375 }
376 }
377
378 // Simplify mul instructions with a constant RHS.
379 Constant *MulC;
380 if (match(Op1, m_ImmConstant(MulC))) {
381 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
382 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
383 Value *X;
384 Constant *C1;
386 // C1*MulC simplifies to a tidier constant.
387 Value *NewC = Builder.CreateMul(C1, MulC);
388 auto *BOp0 = cast<BinaryOperator>(Op0);
389 bool Op0NUW =
390 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
391 Value *NewMul = Builder.CreateMul(X, MulC);
392 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
393 if (HasNUW && Op0NUW) {
394 // If NewMulBO is constant we also can set BO to nuw.
395 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
396 NewMulBO->setHasNoUnsignedWrap();
397 BO->setHasNoUnsignedWrap();
398 }
399 return BO;
400 }
401 }
402
403 // abs(X) * abs(X) -> X * X
404 Value *X;
405 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
406 return BinaryOperator::CreateMul(X, X);
407
408 {
409 Value *Y;
410 // abs(X) * abs(Y) -> abs(X * Y)
411 if (I.hasNoSignedWrap() &&
412 match(Op0,
415 return replaceInstUsesWith(
416 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
417 Builder.CreateNSWMul(X, Y),
418 Builder.getTrue()));
419 }
420
421 // -X * C --> X * -C
422 Value *Y;
423 Constant *Op1C;
424 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
425 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
426
427 // -X * -Y --> X * Y
428 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
429 auto *NewMul = BinaryOperator::CreateMul(X, Y);
430 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
432 NewMul->setHasNoSignedWrap();
433 return NewMul;
434 }
435
436 // -X * Y --> -(X * Y)
437 // X * -Y --> -(X * Y)
439 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
440
441 // (-X * Y) * -X --> (X * Y) * X
442 // (-X << Y) * -X --> (X << Y) * X
443 if (match(Op1, m_Neg(m_Value(X)))) {
444 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
445 return BinaryOperator::CreateMul(NegOp0, X);
446 }
447
448 if (Op0->hasOneUse()) {
449 // (mul (div exact X, C0), C1)
450 // -> (div exact X, C0 / C1)
451 // iff C0 % C1 == 0 and X / (C0 / C1) doesn't create UB.
452 const APInt *C1;
453 auto UDivCheck = [&C1](const APInt &C) { return C.urem(*C1).isZero(); };
454 auto SDivCheck = [&C1](const APInt &C) {
455 APInt Quot, Rem;
456 APInt::sdivrem(C, *C1, Quot, Rem);
457 return Rem.isZero() && !Quot.isAllOnes();
458 };
459 if (match(Op1, m_APInt(C1)) &&
460 (match(Op0, m_Exact(m_UDiv(m_Value(X), m_CheckedInt(UDivCheck)))) ||
461 match(Op0, m_Exact(m_SDiv(m_Value(X), m_CheckedInt(SDivCheck)))))) {
462 auto BOpc = cast<BinaryOperator>(Op0)->getOpcode();
464 BOpc, X,
465 Builder.CreateBinOp(BOpc, cast<BinaryOperator>(Op0)->getOperand(1),
466 Op1));
467 }
468 }
469
470 // (X / Y) * Y = X - (X % Y)
471 // (X / Y) * -Y = (X % Y) - X
472 {
473 Value *Y = Op1;
475 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
476 Div->getOpcode() != Instruction::SDiv)) {
477 Y = Op0;
479 }
480 Value *Neg = dyn_castNegVal(Y);
481 if (Div && Div->hasOneUse() &&
482 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
483 (Div->getOpcode() == Instruction::UDiv ||
484 Div->getOpcode() == Instruction::SDiv)) {
485 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
486
487 // If the division is exact, X % Y is zero, so we end up with X or -X.
488 if (Div->isExact()) {
489 if (DivOp1 == Y)
490 return replaceInstUsesWith(I, X);
492 }
493
494 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
495 : Instruction::SRem;
496 // X must be frozen because we are increasing its number of uses.
497 Value *XFreeze = X;
499 XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
500 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
501 if (DivOp1 == Y)
502 return BinaryOperator::CreateSub(XFreeze, Rem);
503 return BinaryOperator::CreateSub(Rem, XFreeze);
504 }
505 }
506
507 // Fold the following two scenarios:
508 // 1) i1 mul -> i1 and.
509 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
510 // Note: We could use known bits to generalize this and related patterns with
511 // shifts/truncs
512 if (Ty->isIntOrIntVectorTy(1) ||
513 (match(Op0, m_And(m_Value(), m_One())) &&
514 match(Op1, m_And(m_Value(), m_One()))))
515 return BinaryOperator::CreateAnd(Op0, Op1);
516
517 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
518 return replaceInstUsesWith(I, R);
519 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
520 return replaceInstUsesWith(I, R);
521
522 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
523 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
524 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
525 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
526 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
527 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
528 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
529 Value *And = Builder.CreateAnd(X, Y, "mulbool");
530 return CastInst::Create(Instruction::ZExt, And, Ty);
531 }
532 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
533 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
534 // Note: -1 * 1 == 1 * -1 == -1
535 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
536 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
537 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
538 (Op0->hasOneUse() || Op1->hasOneUse())) {
539 Value *And = Builder.CreateAnd(X, Y, "mulbool");
540 return CastInst::Create(Instruction::SExt, And, Ty);
541 }
542
543 // (zext bool X) * Y --> X ? Y : 0
544 // Y * (zext bool X) --> X ? Y : 0
545 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
546 return createSelectInstWithUnknownProfile(X, Op1,
548 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
549 return createSelectInstWithUnknownProfile(X, Op0,
551
552 // mul (sext X), Y -> select X, -Y, 0
553 // mul Y, (sext X) -> select X, -Y, 0
554 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
555 X->getType()->isIntOrIntVectorTy(1))
556 return createSelectInstWithUnknownProfile(
557 X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
559
560 Constant *ImmC;
561 if (match(Op1, m_ImmConstant(ImmC))) {
562 // (sext bool X) * C --> X ? -C : 0
563 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
564 Constant *NegC = ConstantExpr::getNeg(ImmC);
565 return createSelectInstWithUnknownProfile(X, NegC,
567 }
568
569 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
570 const APInt *C;
571 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
572 *C == C->getBitWidth() - 1) {
573 Constant *NegC = ConstantExpr::getNeg(ImmC);
574 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
575 return createSelectInstWithUnknownProfile(IsNeg, NegC,
577 }
578 }
579
580 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
581 // TODO: We are not checking one-use because the elimination of the multiply
582 // is better for analysis?
583 const APInt *C;
584 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
585 *C == C->getBitWidth() - 1) {
586 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
587 return createSelectInstWithUnknownProfile(IsNeg, Y,
589 }
590
591 // (and X, 1) * Y --> (trunc X) ? Y : 0
592 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
593 Value *Tr = Builder.CreateTrunc(X, CmpInst::makeCmpResultType(Ty));
594 return createSelectInstWithUnknownProfile(Tr, Y,
596 }
597
598 // ((ashr X, 31) | 1) * X --> abs(X)
599 // X * ((ashr X, 31) | 1) --> abs(X)
602 m_One()),
603 m_Deferred(X)))) {
604 Value *Abs = Builder.CreateBinaryIntrinsic(
605 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
606 Abs->takeName(&I);
607 return replaceInstUsesWith(I, Abs);
608 }
609
610 if (Instruction *Ext = narrowMathIfNoOverflow(I))
611 return Ext;
612
614 return Res;
615
616 // (mul Op0 Op1):
617 // if Log2(Op0) folds away ->
618 // (shl Op1, Log2(Op0))
619 // if Log2(Op1) folds away ->
620 // (shl Op0, Log2(Op1))
621 if (Value *Res = tryGetLog2(Op0, /*AssumeNonZero=*/false)) {
622 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
623 // We can only propegate nuw flag.
624 Shl->setHasNoUnsignedWrap(HasNUW);
625 return Shl;
626 }
627 if (Value *Res = tryGetLog2(Op1, /*AssumeNonZero=*/false)) {
628 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
629 // We can only propegate nuw flag.
630 Shl->setHasNoUnsignedWrap(HasNUW);
631 return Shl;
632 }
633
634 bool Changed = false;
635 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
636 Changed = true;
637 I.setHasNoSignedWrap(true);
638 }
639
640 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I, I.hasNoSignedWrap())) {
641 Changed = true;
642 I.setHasNoUnsignedWrap(true);
643 }
644
645 return Changed ? &I : nullptr;
646}
647
648Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
649 BinaryOperator::BinaryOps Opcode = I.getOpcode();
650 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
651 "Expected fmul or fdiv");
652
653 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
654 Value *X, *Y;
655
656 // -X * -Y --> X * Y
657 // -X / -Y --> X / Y
658 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
659 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X))) &&
661 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
662
663 // fabs(X) * fabs(X) -> X * X
664 // fabs(X) / fabs(X) -> X / X
665 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
666 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
667
668 // fabs(X) * fabs(Y) --> fabs(X * Y)
669 // fabs(X) / fabs(Y) --> fabs(X / Y)
670 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
671 (Op0->hasOneUse() || Op1->hasOneUse())) {
672 Value *XY = Builder.CreateBinOpFMF(Opcode, X, Y, &I);
673 Value *Fabs = Builder.CreateFAbs(XY, &I, I.getName());
674 return replaceInstUsesWith(I, Fabs);
675 }
676
677 return nullptr;
678}
679
681 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
682 Value *Y, Value *Z) {
683 InstCombiner::BuilderTy &Builder = IC.Builder;
684 Value *YZ = Builder.CreateNSWAdd(Y, Z);
685 Value *NewPow = Builder.CreateIntrinsic(
686 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
687
688 return NewPow;
689 };
690
691 Value *X, *Y, *Z;
692 unsigned Opcode = I.getOpcode();
693 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
694 "Unexpected opcode");
695
696 // powi(X, Y) * X --> powi(X, Y+1)
697 // X * powi(X, Y) --> powi(X, Y+1)
699 m_Value(X), m_Value(Y)))),
700 m_Deferred(X)))) {
701 Constant *One = ConstantInt::get(Y->getType(), 1);
702 if (willNotOverflowSignedAdd(Y, One, I)) {
703 Value *NewPow = createPowiExpr(I, *this, X, Y, One);
704 return replaceInstUsesWith(I, NewPow);
705 }
706 }
707
708 // powi(x, y) * powi(x, z) -> powi(x, y + z)
709 Value *Op0 = I.getOperand(0);
710 Value *Op1 = I.getOperand(1);
711 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
715 m_Value(Z)))) &&
716 Y->getType() == Z->getType() && willNotOverflowSignedAdd(Y, Z, I)) {
717 Value *NewPow = createPowiExpr(I, *this, X, Y, Z);
718 return replaceInstUsesWith(I, NewPow);
719 }
720
721 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
722 // powi(X, Y) / X --> powi(X, Y-1)
723 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
724 // nnan are required.
725 // TODO: Multi-use may be also better off creating Powi(x,y-1)
727 m_Specific(Op1), m_Value(Y))))) &&
728 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
729 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
730 Value *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
731 return replaceInstUsesWith(I, NewPow);
732 }
733
734 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
735 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
736 // nnan are required.
737 // TODO: Multi-use may be also better off creating Powi(x,y-1)
739 m_Value(X), m_Value(Y))))) &&
741 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
742 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
743 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
744 return BinaryOperator::CreateFDivFMF(NewPow, Z, &I);
745 }
746 }
747
748 return nullptr;
749}
750
751// If we have the following pattern,
752// X = 1.0/sqrt(a)
753// R1 = X * X
754// R2 = a/sqrt(a)
755// then this method collects all the instructions that match R1 and R2.
759 Value *A;
760 if (match(Div, m_FDiv(m_FPOne(), m_Sqrt(m_Value(A)))) ||
762 for (Instruction *I : Div->users()) {
764 R1.insert(I);
765 }
766
767 CallInst *CI = cast<CallInst>(Div->getOperand(1));
768 for (Instruction *I : CI->users()) {
770 R2.insert(I);
771 }
772 }
773 return !R1.empty() && !R2.empty();
774}
775
776// Check legality for transforming
777// x = 1.0/sqrt(a)
778// r1 = x * x;
779// r2 = a/sqrt(a);
780//
781// TO
782//
783// r1 = 1/a
784// r2 = sqrt(a)
785// x = r1 * r2
786// This transform works only when 'a' is known positive.
790 // Check if the required pattern for the transformation exists.
791 if (!getFSqrtDivOptPattern(X, R1, R2))
792 return false;
793
794 BasicBlock *BBx = X->getParent();
795 BasicBlock *BBr1 = (*R1.begin())->getParent();
796 BasicBlock *BBr2 = (*R2.begin())->getParent();
797
798 CallInst *FSqrt = cast<CallInst>(X->getOperand(1));
799 if (!FSqrt->hasAllowReassoc() || !FSqrt->hasNoNaNs() ||
800 !FSqrt->hasNoSignedZeros() || !FSqrt->hasNoInfs())
801 return false;
802
803 // We change x = 1/sqrt(a) to x = sqrt(a) * 1/a . This change isn't allowed
804 // by recip fp as it is strictly meant to transform ops of type a/b to
805 // a * 1/b. So, this can be considered as algebraic rewrite and reassoc flag
806 // has been used(rather abused)in the past for algebraic rewrites.
807 if (!X->hasAllowReassoc() || !X->hasAllowReciprocal() || !X->hasNoInfs())
808 return false;
809
810 // Check the constraints on X, R1 and R2 combined.
811 // fdiv instruction and one of the multiplications must reside in the same
812 // block. If not, the optimized code may execute more ops than before and
813 // this may hamper the performance.
814 if (BBx != BBr1 && BBx != BBr2)
815 return false;
816
817 // Check the constraints on instructions in R1.
818 if (any_of(R1, [BBr1](Instruction *I) {
819 // When you have multiple instructions residing in R1 and R2
820 // respectively, it's difficult to generate combinations of (R1,R2) and
821 // then check if we have the required pattern. So, for now, just be
822 // conservative.
823 return (I->getParent() != BBr1 || !I->hasAllowReassoc());
824 }))
825 return false;
826
827 // Check the constraints on instructions in R2.
828 return all_of(R2, [BBr2](Instruction *I) {
829 // When you have multiple instructions residing in R1 and R2
830 // respectively, it's difficult to generate combination of (R1,R2) and
831 // then check if we have the required pattern. So, for now, just be
832 // conservative.
833 return (I->getParent() == BBr2 && I->hasAllowReassoc());
834 });
835}
836
838 Value *Op0 = I.getOperand(0);
839 Value *Op1 = I.getOperand(1);
840 Value *X, *Y;
841 Constant *C;
842 BinaryOperator *Op0BinOp;
843
844 // Reassociate constant RHS with another constant to form constant
845 // expression.
846 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
847 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
848 // Everything in this scope folds I with Op0, intersecting their FMF.
849 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
850 Constant *C1;
851 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
852 // (C1 / X) * C --> (C * C1) / X
853 Constant *CC1 =
854 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
855 if (CC1 && CC1->isNormalFP())
856 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
857 }
858 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
859 // FIXME: This seems like it should also be checking for arcp
860 // (X / C1) * C --> X * (C / C1)
861 Constant *CDivC1 =
862 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
863 if (CDivC1 && CDivC1->isNormalFP())
864 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
865
866 // If the constant was a denormal, try reassociating differently.
867 // (X / C1) * C --> X / (C1 / C)
868 Constant *C1DivC =
869 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
870 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
871 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
872 }
873
874 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
875 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
876 // further folds and (X * C) + C2 is 'fma'.
877 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
878 // (X + C1) * C --> (X * C) + (C * C1)
879 if (Constant *CC1 =
880 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
881 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
882 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
883 }
884 }
885 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
886 // (C1 - X) * C --> (C * C1) - (X * C)
887 if (Constant *CC1 =
888 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
889 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
890 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
891 }
892 }
893 }
894
895 Value *Z;
896 if (match(&I,
898 m_Value(Z)))) {
899 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
900 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
901 if (FMF.allowReassoc()) {
902 // Sink division: (X / Y) * Z --> (X * Z) / Y
903 auto *NewFMul = Builder.CreateFMulFMF(X, Z, FMF);
904 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
905 }
906 }
907
908 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
909 // nnan disallows the possibility of returning a number if both operands are
910 // negative (in that case, we should return NaN).
911 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
912 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
913 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
914 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
915 return replaceInstUsesWith(I, Sqrt);
916 }
917
918 // The following transforms are done irrespective of the number of uses
919 // for the expression "1.0/sqrt(X)".
920 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
921 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
922 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
923 // has the necessary (reassoc) fast-math-flags.
924 if (I.hasNoSignedZeros() &&
925 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
926 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
928 if (I.hasNoSignedZeros() &&
929 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
930 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
932
933 // Like the similar transform in instsimplify, this requires 'nsz' because
934 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
935 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
936 // Peek through fdiv to find squaring of square root:
937 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
938 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
939 Value *XX = Builder.CreateFMulFMF(X, X, &I);
940 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
941 }
942 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
943 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
944 Value *XX = Builder.CreateFMulFMF(X, X, &I);
945 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
946 }
947 }
948
949 // pow(X, Y) * X --> pow(X, Y+1)
950 // X * pow(X, Y) --> pow(X, Y+1)
952 m_Value(Y))),
953 m_Deferred(X)))) {
954 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
955 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
956 return replaceInstUsesWith(I, Pow);
957 }
958
959 if (Instruction *FoldedPowi = foldPowiReassoc(I))
960 return FoldedPowi;
961
962 if (I.isOnlyUserOfAnyOperand()) {
963 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
966 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
967 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
968 return replaceInstUsesWith(I, NewPow);
969 }
970 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
973 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
974 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
975 return replaceInstUsesWith(I, NewPow);
976 }
977
978 // exp(X) * exp(Y) -> exp(X + Y)
981 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
982 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
983 return replaceInstUsesWith(I, Exp);
984 }
985
986 // exp2(X) * exp2(Y) -> exp2(X + Y)
989 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
990 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
991 return replaceInstUsesWith(I, Exp2);
992 }
993 }
994
995 // (X*Y) * X => (X*X) * Y where Y != X
996 // The purpose is two-fold:
997 // 1) to form a power expression (of X).
998 // 2) potentially shorten the critical path: After transformation, the
999 // latency of the instruction Y is amortized by the expression of X*X,
1000 // and therefore Y is in a "less critical" position compared to what it
1001 // was before the transformation.
1002 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
1003 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
1004 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
1005 }
1006 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
1007 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
1008 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
1009 }
1010
1011 return nullptr;
1012}
1013
1015 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
1016 I.getFastMathFlags(),
1017 SQ.getWithInstruction(&I)))
1018 return replaceInstUsesWith(I, V);
1019
1021 return &I;
1022
1024 return X;
1025
1027 return Phi;
1028
1029 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
1030 return FoldedMul;
1031
1032 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
1033 return replaceInstUsesWith(I, FoldedMul);
1034
1035 if (Instruction *R = foldFPSignBitOps(I))
1036 return R;
1037
1038 if (Instruction *R = foldFBinOpOfIntCasts(I))
1039 return R;
1040
1041 // X * -1.0 --> -X
1042 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1043 if (match(Op1, m_SpecificFP(-1.0)))
1044 return UnaryOperator::CreateFNegFMF(Op0, &I);
1045
1046 // -X * C --> X * -C
1047 Value *X, *Y;
1048 Constant *C;
1049 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
1050 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X))) && match(Op1, m_Constant(C)))
1051 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1052 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
1053
1054 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
1055 // (uitofp bool X) * Y --> X ? Y : 0
1056 // Y * (uitofp bool X) --> X ? Y : 0
1057 // Note INF * 0 is NaN.
1058 if (match(Op0, m_UIToFP(m_Value(X))) &&
1059 X->getType()->isIntOrIntVectorTy(1)) {
1060 auto *SI = createSelectInstWithUnknownProfile(
1061 X, Op1, ConstantFP::get(I.getType(), 0.0));
1062 SI->copyFastMathFlags(I.getFastMathFlags());
1063 return SI;
1064 }
1065 if (match(Op1, m_UIToFP(m_Value(X))) &&
1066 X->getType()->isIntOrIntVectorTy(1)) {
1067 auto *SI = createSelectInstWithUnknownProfile(
1068 X, Op0, ConstantFP::get(I.getType(), 0.0));
1069 SI->copyFastMathFlags(I.getFastMathFlags());
1070 return SI;
1071 }
1072 }
1073
1074 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
1075 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1076 return replaceInstUsesWith(I, V);
1077
1078 if (I.hasAllowReassoc())
1079 if (Instruction *FoldedMul = foldFMulReassoc(I))
1080 return FoldedMul;
1081
1082 // log2(X * 0.5) * Y = log2(X) * Y - Y
1083 if (I.isFast()) {
1084 IntrinsicInst *Log2 = nullptr;
1086 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1088 Y = Op1;
1089 }
1091 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1093 Y = Op0;
1094 }
1095 if (Log2) {
1096 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
1097 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
1098 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
1099 }
1100 }
1101
1102 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
1103 // Given a phi node with entry value as 0 and it used in fmul operation,
1104 // we can replace fmul with 0 safely and eleminate loop operation.
1105 PHINode *PN = nullptr;
1106 Value *Start = nullptr, *Step = nullptr;
1107 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
1108 I.hasNoSignedZeros() && match(Start, m_Zero()))
1109 return replaceInstUsesWith(I, Start);
1110
1111 // minimum(X, Y) * maximum(X, Y) => X * Y.
1112 if (match(&I,
1115 m_Deferred(Y))))) {
1117 // We cannot preserve ninf if nnan flag is not set.
1118 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
1119 // while in optimized version NaN * Inf and this is a poison with ninf flag.
1120 if (!Result->hasNoNaNs())
1121 Result->setHasNoInfs(false);
1122 return Result;
1123 }
1124
1125 // tan(X) * cos(X) -> sin(X)
1126 if (I.hasAllowContract() &&
1127 match(&I,
1130 Value *Sin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, &I);
1131 if (auto *Metadata = I.getMetadata(LLVMContext::MD_fpmath))
1132 if (auto *SinI = dyn_cast<Instruction>(Sin))
1133 SinI->setMetadata(LLVMContext::MD_fpmath, Metadata);
1134 return replaceInstUsesWith(I, Sin);
1135 }
1136
1137 // X * ldexp(1.0, Y) -> ldexp(X, Y)
1139 m_Value(X),
1141 m_FPOne(), m_Value(Y))))))))
1142 return replaceInstUsesWith(
1143 I, Builder.CreateIntrinsic(Intrinsic::ldexp,
1144 {X->getType(), Y->getType()}, {X, Y}, &I));
1145
1147 return &I;
1148
1149 return nullptr;
1150}
1151
1152/// Fold a divide or remainder with a select instruction divisor when one of the
1153/// select operands is zero. In that case, we can use the other select operand
1154/// because div/rem by zero is undefined.
1156 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
1157 if (!SI)
1158 return false;
1159
1160 int NonNullOperand;
1161 if (match(SI->getTrueValue(), m_Zero()))
1162 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1163 NonNullOperand = 2;
1164 else if (match(SI->getFalseValue(), m_Zero()))
1165 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1166 NonNullOperand = 1;
1167 else
1168 return false;
1169
1170 // Change the div/rem to use 'Y' instead of the select.
1171 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
1172
1173 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1174 // problem. However, the select, or the condition of the select may have
1175 // multiple uses. Based on our knowledge that the operand must be non-zero,
1176 // propagate the known value for the select into other uses of it, and
1177 // propagate a known value of the condition into its other users.
1178
1179 // If the select and condition only have a single use, don't bother with this,
1180 // early exit.
1181 Value *SelectCond = SI->getCondition();
1182 if (SI->use_empty() && SelectCond->hasOneUse())
1183 return true;
1184
1185 // Scan the current block backward, looking for other uses of SI.
1186 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
1187 Type *CondTy = SelectCond->getType();
1188 while (BBI != BBFront) {
1189 --BBI;
1190 // If we found an instruction that we can't assume will return, so
1191 // information from below it cannot be propagated above it.
1193 break;
1194
1195 // Replace uses of the select or its condition with the known values.
1196 for (Use &Op : BBI->operands()) {
1197 if (Op == SI) {
1198 replaceUse(Op, SI->getOperand(NonNullOperand));
1199 Worklist.push(&*BBI);
1200 } else if (Op == SelectCond) {
1201 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
1202 : ConstantInt::getFalse(CondTy));
1203 Worklist.push(&*BBI);
1204 }
1205 }
1206
1207 // If we past the instruction, quit looking for it.
1208 if (&*BBI == SI)
1209 SI = nullptr;
1210 if (&*BBI == SelectCond)
1211 SelectCond = nullptr;
1212
1213 // If we ran out of things to eliminate, break out of the loop.
1214 if (!SelectCond && !SI)
1215 break;
1216
1217 }
1218 return true;
1219}
1220
1221/// True if the multiply can not be expressed in an int this size.
1222static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1223 bool IsSigned) {
1224 bool Overflow;
1225 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
1226 return Overflow;
1227}
1228
1229/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1230static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1231 bool IsSigned) {
1232 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1233
1234 // Bail if we will divide by zero.
1235 if (C2.isZero())
1236 return false;
1237
1238 // Bail if we would divide INT_MIN by -1.
1239 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1240 return false;
1241
1242 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1243 if (IsSigned)
1244 APInt::sdivrem(C1, C2, Quotient, Remainder);
1245 else
1246 APInt::udivrem(C1, C2, Quotient, Remainder);
1247
1248 return Remainder.isMinValue();
1249}
1250
1252 assert((I.getOpcode() == Instruction::SDiv ||
1253 I.getOpcode() == Instruction::UDiv) &&
1254 "Expected integer divide");
1255
1256 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1258 Type *Ty = I.getType();
1259
1260 Value *X, *Y, *Z;
1261
1262 // With appropriate no-wrap constraints, remove a common factor in the
1263 // dividend and divisor that is disguised as a left-shifted value.
1264 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1265 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1266 // Both operands must have the matching no-wrap for this kind of division.
1268 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1269 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1270 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1271
1272 // (X * Y) u/ (X << Z) --> Y u>> Z
1273 if (!IsSigned && HasNUW)
1274 return Builder.CreateLShr(Y, Z, "", I.isExact());
1275
1276 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1277 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1278 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1279 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1280 }
1281 }
1282
1283 // With appropriate no-wrap constraints, remove a common factor in the
1284 // dividend and divisor that is disguised as a left-shift amount.
1285 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1286 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1287 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1288 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1289
1290 // For unsigned div, we need 'nuw' on both shifts or
1291 // 'nsw' on both shifts + 'nuw' on the dividend.
1292 // (X << Z) / (Y << Z) --> X / Y
1293 if (!IsSigned &&
1294 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1295 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1296 Shl1->hasNoSignedWrap())))
1297 return Builder.CreateUDiv(X, Y, "", I.isExact());
1298
1299 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1300 // (X << Z) / (Y << Z) --> X / Y
1301 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1302 Shl1->hasNoUnsignedWrap())
1303 return Builder.CreateSDiv(X, Y, "", I.isExact());
1304 }
1305
1306 // If X << Y and X << Z does not overflow, then:
1307 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1308 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1309 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1310 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1311 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1312
1313 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1314 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1315 Constant *One = ConstantInt::get(X->getType(), 1);
1316 // Only preserve the nsw flag if dividend has nsw
1317 // or divisor has nsw and operator is sdiv.
1318 Value *Dividend = Builder.CreateShl(
1319 One, Y, "shl.dividend",
1320 /*HasNUW=*/true,
1321 /*HasNSW=*/
1322 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1323 : Shl0->hasNoSignedWrap());
1324 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1325 }
1326 }
1327
1328 return nullptr;
1329}
1330
1331/// Return true if a matching remainder is known to be zero at the division.
1333 const SimplifyQuery &Q) {
1334 assert((Div.getOpcode() == Instruction::SDiv ||
1335 Div.getOpcode() == Instruction::UDiv) &&
1336 "Expected integer divide");
1337
1338 // The condition cache does not track vector lanes independently.
1339 if (!Div.getType()->isIntegerTy())
1340 return false;
1341
1342 unsigned RemOpcode = Div.getOpcode() == Instruction::SDiv ? Instruction::SRem
1343 : Instruction::URem;
1344
1345 Value *Op0 = Div.getOperand(0);
1346 Value *Op1 = Div.getOperand(1);
1347
1348 auto IsKnownZeroRemainder = [&](Value *Cond) {
1349 auto *Cmp = dyn_cast<ICmpInst>(Cond);
1350 if (!Cmp || !Cmp->isEquality())
1351 return false;
1352
1353 // Search for a remainder being compared to zero.
1354 BinaryOperator *Rem;
1355 if (!match(Cmp, m_c_ICmp(m_BinOp(Rem), m_Zero())))
1356 return false;
1357 if (Rem->getOpcode() != RemOpcode || Rem->getOperand(0) != Op0 ||
1358 Rem->getOperand(1) != Op1)
1359 return false;
1360
1363 return Known.isZero();
1364 };
1365
1366 // findValuesAffectedByCondition() records both operands of a remainder that
1367 // is compared against zero, so looking up one non-constant operand finds
1368 // every candidate condition.
1369 Value *V = isa<Constant>(Op0) ? Op1 : Op0;
1370
1371 if (Q.DC && Q.DT) {
1372 for (CondBrInst *BI : Q.DC->conditionsFor(V))
1373 if (IsKnownZeroRemainder(BI->getCondition()))
1374 return true;
1375 }
1376
1377 if (Q.AC) {
1378 for (auto &AssumeValueHandle : Q.AC->assumptionsFor(V)) {
1379 if (!AssumeValueHandle)
1380 continue;
1381 auto *Assume = cast<AssumeInst>(AssumeValueHandle);
1382 if (IsKnownZeroRemainder(Assume->getArgOperand(0)))
1383 return true;
1384 }
1385 }
1386
1387 return false;
1388}
1389
1390/// Common integer divide/remainder transforms
1392 assert(I.isIntDivRem() && "Unexpected instruction");
1393 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1394
1395 // If any element of a constant divisor fixed width vector is zero or undef
1396 // the behavior is undefined and we can fold the whole op to poison.
1399 return replaceInstUsesWith(I, PoisonValue::get(I.getType()));
1400 }
1401
1403 return Phi;
1404
1405 // The RHS is known non-zero.
1406 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1407 return replaceOperand(I, 1, V);
1408
1409 // Handle cases involving: div/rem X, (select Cond, Y, Z)
1411 return &I;
1412
1413 // If the divisor is a select-of-constants, try to constant fold all div ops:
1414 // C div/rem (select Cond, TrueC, FalseC) --> select Cond, (C div/rem TrueC),
1415 // (C div/rem FalseC)
1416 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1417 if (match(Op0, m_ImmConstant()) &&
1420 /*FoldWithMultiUse*/ true))
1421 return R;
1422 }
1423
1424 return nullptr;
1425}
1426
1427/// This function implements the transforms common to both integer division
1428/// instructions (udiv and sdiv). It is called by the visitors to those integer
1429/// division instructions.
1430/// Common integer divide transforms
1433 return Res;
1434
1435 if (!I.isExact() && isKnownExactFromRem(I, SQ)) {
1436 I.setIsExact();
1437 return &I;
1438 }
1439
1440 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1441 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1442 Type *Ty = I.getType();
1443
1444 const APInt *C2;
1445 if (match(Op1, m_APInt(C2))) {
1446 Value *X;
1447 const APInt *C1;
1448
1449 // (X / C1) / C2 -> X / (C1*C2)
1450 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1451 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1452 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1453 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1454 return BinaryOperator::Create(I.getOpcode(), X,
1455 ConstantInt::get(Ty, Product));
1456 }
1457
1458 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1459 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1460 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1461
1462 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1463 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1464 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1465 ConstantInt::get(Ty, Quotient));
1466 NewDiv->setIsExact(I.isExact());
1467 return NewDiv;
1468 }
1469
1470 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1471 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1472 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1473 ConstantInt::get(Ty, Quotient));
1474 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1475 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1476 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1477 return Mul;
1478 }
1479
1480 // (X * C1) / C2 -> (X * (C1/D)) / (C2/D) if D = gcd(C1, C2) > 1.
1481 if (Op0->hasOneUse()) {
1482 APInt GCD = APIntOps::GreatestCommonDivisor(*C1, *C2, IsSigned);
1483 if (GCD.ugt(1)) {
1484 APInt NewC1 = IsSigned ? C1->sdiv(GCD) : C1->udiv(GCD);
1485 APInt NewC2 = IsSigned ? C2->sdiv(GCD) : C2->udiv(GCD);
1486
1487 auto *OldMul = cast<OverflowingBinaryOperator>(Op0);
1488 Value *NewMul = Builder.CreateMul(X, ConstantInt::get(Ty, NewC1), "",
1489 OldMul->hasNoUnsignedWrap(),
1490 OldMul->hasNoSignedWrap());
1491 NewMul->takeName(OldMul);
1492
1493 Constant *NewDivisor = ConstantInt::get(Ty, NewC2);
1494 auto *NewDiv =
1495 BinaryOperator::Create(I.getOpcode(), NewMul, NewDivisor);
1496 NewDiv->setIsExact(I.isExact());
1497 return NewDiv;
1498 }
1499 }
1500 }
1501
1502 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1503 C1->ult(C1->getBitWidth() - 1)) ||
1504 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1505 C1->ult(C1->getBitWidth()))) {
1506 APInt C1Shifted = APInt::getOneBitSet(
1507 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1508
1509 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1510 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1511 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1512 ConstantInt::get(Ty, Quotient));
1513 BO->setIsExact(I.isExact());
1514 return BO;
1515 }
1516
1517 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1518 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1519 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1520 ConstantInt::get(Ty, Quotient));
1521 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1522 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1523 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1524 return Mul;
1525 }
1526
1527 // (X << C1) / C2 -> (X << (C1 - K)) / (C2 / (1 << K))
1528 // Where K = min(C1, countr_zero(C2)), the shared power of 2.
1529 if (Op0->hasOneUse()) {
1530 unsigned ShiftAmt = static_cast<unsigned>(C1->getZExtValue());
1531 unsigned K = std::min(C2->countr_zero(), ShiftAmt);
1532 if (K > 0) {
1533 unsigned NewShiftAmt = ShiftAmt - K;
1534 APInt NewC2 = IsSigned ? C2->ashr(K) : C2->lshr(K);
1535
1536 auto *OldShift = cast<OverflowingBinaryOperator>(Op0);
1537 Value *NewShift = Builder.CreateShl(
1538 X, ConstantInt::get(Ty, NewShiftAmt), "",
1539 OldShift->hasNoUnsignedWrap(), OldShift->hasNoSignedWrap());
1540 NewShift->takeName(OldShift);
1541
1542 Constant *NewDivisor = ConstantInt::get(Ty, NewC2);
1543 auto *NewDiv =
1544 BinaryOperator::Create(I.getOpcode(), NewShift, NewDivisor);
1545 NewDiv->setIsExact(I.isExact());
1546 return NewDiv;
1547 }
1548 }
1549 }
1550
1551 // Distribute div over add to eliminate a matching div/mul pair:
1552 // ((X * C2) + C1) / C2 --> X + C1/C2
1553 // We need a multiple of the divisor for a signed add constant, but
1554 // unsigned is fine with any constant pair.
1555 if (IsSigned &&
1557 m_APInt(C1))) &&
1558 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1559 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1560 }
1561 if (!IsSigned &&
1563 m_APInt(C1)))) {
1564 return BinaryOperator::CreateNUWAdd(X,
1565 ConstantInt::get(Ty, C1->udiv(*C2)));
1566 }
1567
1568 if (!C2->isZero()) // avoid X udiv 0
1569 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1570 return FoldedDiv;
1571 }
1572
1573 if (match(Op0, m_One())) {
1574 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1575 if (IsSigned) {
1576 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1577 // (Op1 + 1) u< 3 ? Op1 : 0
1578 // Op1 must be frozen because we are increasing its number of uses.
1579 Value *F1 = Op1;
1580 if (!isGuaranteedNotToBeUndef(Op1))
1581 F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1582 Value *Inc = Builder.CreateAdd(F1, Op0);
1583 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1584 return createSelectInstWithUnknownProfile(Cmp, F1,
1585 ConstantInt::get(Ty, 0));
1586 } else {
1587 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1588 // result is one, otherwise it's zero.
1589 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1590 }
1591 }
1592
1593 // See if we can fold away this div instruction.
1595 return &I;
1596
1597 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1598 Value *X, *Z;
1599 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1600 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1601 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1602 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1603
1604 // (X << Y) / X -> 1 << Y
1605 Value *Y;
1606 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1607 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1608 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1609 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1610
1611 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1612 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1613 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1614 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1615 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1616 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1617 replaceOperand(I, 1, Y);
1618 return &I;
1619 }
1620 }
1621
1622 // (X << Z) / (X * Y) -> (1 << Z) / Y
1623 // TODO: Handle sdiv.
1624 if (!IsSigned && Op1->hasOneUse() &&
1625 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1626 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1628 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1629 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1630 NewDiv->setIsExact(I.isExact());
1631 return NewDiv;
1632 }
1633
1634 if (Value *R = foldIDivShl(I, Builder))
1635 return replaceInstUsesWith(I, R);
1636
1637 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1638 // after peeking through another divide:
1639 // ((Op1 * X) / Y) / Op1 --> X / Y
1640 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1641 m_Value(Y)))) {
1642 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1643 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1644 Instruction *NewDiv = nullptr;
1645 if (!IsSigned && Mul->hasNoUnsignedWrap())
1646 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1647 else if (IsSigned && Mul->hasNoSignedWrap())
1648 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1649
1650 // Exact propagates only if both of the original divides are exact.
1651 if (NewDiv) {
1652 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1653 return NewDiv;
1654 }
1655 }
1656
1657 // X / (select Cond, 1, Y) --> select Cond, X, (X / Y)
1658 // X / (select Cond, Y, 1) --> select Cond, (X / Y), X
1659 // Division by 1 is a no-op, so we sink the division into the non-1 arm.
1660 // For sdiv, limit Y to constant to avoid signed overflow concern.
1661 {
1662 Value *Cond, *DivY;
1663 const APInt *C;
1664 auto IsSafeDivisor = [&](Value *V) {
1665 if (IsSigned)
1666 return match(V, m_APInt(C)) && !C->isZero() && !C->isAllOnes();
1667 return isKnownNonZero(V, SQ.getWithInstruction(&I)) &&
1668 isGuaranteedNotToBePoison(V, SQ.AC, &I, SQ.DT);
1669 };
1670 if (match(Op1, m_OneUse(m_Select(m_Value(Cond), m_One(), m_Value(DivY)))) &&
1671 IsSafeDivisor(DivY)) {
1672 Value *NewDiv =
1673 Builder.CreateExactBinOp(I.getOpcode(), Op0, DivY, I.isExact());
1674 return SelectInst::Create(Cond, Op0, NewDiv, "", nullptr,
1675 cast<SelectInst>(Op1));
1676 }
1677 if (match(Op1, m_OneUse(m_Select(m_Value(Cond), m_Value(DivY), m_One()))) &&
1678 IsSafeDivisor(DivY)) {
1679 Value *NewDiv =
1680 Builder.CreateExactBinOp(I.getOpcode(), Op0, DivY, I.isExact());
1681 return SelectInst::Create(Cond, NewDiv, Op0, "", nullptr,
1682 cast<SelectInst>(Op1));
1683 }
1684 }
1685
1686 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1687 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1688 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1689 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1690
1691 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1692 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1693 auto OB1HasNUW =
1694 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1695 const APInt *C1, *C2;
1696 if (IsSigned && OB0HasNSW) {
1697 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1698 return BinaryOperator::CreateSDiv(A, B);
1699 }
1700 if (!IsSigned && OB0HasNUW) {
1701 if (OB1HasNUW)
1702 return BinaryOperator::CreateUDiv(A, B);
1703 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1704 return BinaryOperator::CreateUDiv(A, B);
1705 }
1706 return nullptr;
1707 };
1708
1709 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1710 if (auto *Val = CreateDivOrNull(Y, Z))
1711 return Val;
1712 }
1713 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1714 if (auto *Val = CreateDivOrNull(X, Z))
1715 return Val;
1716 }
1717 }
1718 return nullptr;
1719}
1720
1721Value *InstCombinerImpl::takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero,
1722 bool DoFold) {
1723 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1724 if (!DoFold)
1725 return reinterpret_cast<Value *>(-1);
1726 return Fn();
1727 };
1728
1729 // FIXME: assert that Op1 isn't/doesn't contain undef.
1730
1731 // log2(2^C) -> C
1732 if (match(Op, m_Power2()))
1733 return IfFold([&]() {
1735 if (!C)
1736 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1737 return C;
1738 });
1739
1740 // The remaining tests are all recursive, so bail out if we hit the limit.
1742 return nullptr;
1743
1744 // log2(zext X) -> zext log2(X)
1745 // FIXME: Require one use?
1746 Value *X, *Y;
1747 if (match(Op, m_ZExt(m_Value(X))))
1748 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1749 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1750
1751 // log2(trunc x) -> trunc log2(X)
1752 // FIXME: Require one use?
1753 if (match(Op, m_Trunc(m_Value(X)))) {
1754 auto *TI = cast<TruncInst>(Op);
1755 if (AssumeNonZero || TI->hasNoUnsignedWrap())
1756 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1757 return IfFold([&]() {
1758 return Builder.CreateTrunc(LogX, Op->getType(), "",
1759 /*IsNUW=*/TI->hasNoUnsignedWrap());
1760 });
1761 }
1762
1763 // log2(X << Y) -> log2(X) + Y
1764 // FIXME: Require one use unless X is 1?
1765 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1767 // nuw will be set if the `shl` is trivially non-zero.
1768 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1769 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1770 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1771 }
1772
1773 // log2(X >>u Y) -> log2(X) - Y
1774 // FIXME: Require one use?
1775 if (match(Op, m_LShr(m_Value(X), m_Value(Y)))) {
1776 auto *PEO = cast<PossiblyExactOperator>(Op);
1777 if (AssumeNonZero || PEO->isExact())
1778 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1779 return IfFold([&]() { return Builder.CreateSub(LogX, Y); });
1780 }
1781
1782 // log2(X & Y) -> either log2(X) or log2(Y)
1783 // This requires `AssumeNonZero` as `X & Y` may be zero when X != Y.
1784 if (AssumeNonZero && match(Op, m_And(m_Value(X), m_Value(Y)))) {
1785 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1786 return IfFold([&]() { return LogX; });
1787 if (Value *LogY = takeLog2(Y, Depth, AssumeNonZero, DoFold))
1788 return IfFold([&]() { return LogY; });
1789 }
1790
1791 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1792 // FIXME: Require one use?
1794 if (Value *LogX = takeLog2(SI->getOperand(1), Depth, AssumeNonZero, DoFold))
1795 if (Value *LogY =
1796 takeLog2(SI->getOperand(2), Depth, AssumeNonZero, DoFold))
1797 return IfFold([&]() {
1798 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY, "", SI);
1799 });
1800
1801 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1802 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1804 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1805 // Use AssumeNonZero as false here. Otherwise we can hit case where
1806 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1807 if (Value *LogX = takeLog2(MinMax->getLHS(), Depth,
1808 /*AssumeNonZero*/ false, DoFold))
1809 if (Value *LogY = takeLog2(MinMax->getRHS(), Depth,
1810 /*AssumeNonZero*/ false, DoFold))
1811 return IfFold([&]() {
1812 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1813 LogY);
1814 });
1815 }
1816
1817 // log2(X + 1) IIF X[0,1] -> X
1818 if (Op->getType()->getScalarSizeInBits() != 1 &&
1819 match(Op, m_Add(m_Value(X), m_One())) &&
1820 computeKnownBits(X, cast<Instruction>(Op)).countMaxActiveBits() == 1)
1821 return IfFold([&]() { return X; });
1822
1823 return nullptr;
1824}
1825
1826/// If we have zero-extended operands of an unsigned div or rem, we may be able
1827/// to narrow the operation (sink the zext below the math).
1829 InstCombinerImpl &IC) {
1830 Instruction::BinaryOps Opcode = I.getOpcode();
1831 Value *N = I.getOperand(0);
1832 Value *D = I.getOperand(1);
1833 Type *Ty = I.getType();
1834 Value *X, *Y;
1835 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1836 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1837 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1838 // urem (zext X), (zext Y) --> zext (urem X, Y)
1839 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1840 return new ZExtInst(NarrowOp, Ty);
1841 }
1842
1843 Constant *C;
1844 auto &DL = IC.getDataLayout();
1846 match(D, m_Constant(C))) {
1847 // If the constant is the same in the smaller type, use the narrow version.
1848 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1849 if (!TruncC)
1850 return nullptr;
1851
1852 // udiv (zext X), C --> zext (udiv X, C')
1853 // urem (zext X), C --> zext (urem X, C')
1854 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1855 }
1857 match(N, m_Constant(C))) {
1858 // If the constant is the same in the smaller type, use the narrow version.
1859 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1860 if (!TruncC)
1861 return nullptr;
1862
1863 // udiv C, (zext X) --> zext (udiv C', X)
1864 // urem C, (zext X) --> zext (urem C', X)
1865 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1866 }
1867
1868 return nullptr;
1869}
1870
1872 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1873 SQ.getWithInstruction(&I)))
1874 return replaceInstUsesWith(I, V);
1875
1877 return X;
1878
1879 // Handle the integer div common cases
1880 if (Instruction *Common = commonIDivTransforms(I))
1881 return Common;
1882
1883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1884 Value *X;
1885 const APInt *C1, *C2;
1886 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1887 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1888 bool Overflow;
1889 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1890 if (!Overflow) {
1891 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1892 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1893 X, ConstantInt::get(X->getType(), C2ShlC1));
1894 if (IsExact)
1895 BO->setIsExact();
1896 return BO;
1897 }
1898 }
1899
1900 // (X udiv Y) udiv Z --> X udiv (Y * Z), if Y * Z does not overflow.
1901 // This is the variable-operand version of the (X / C1) / C2 fold in
1902 // commonIDivTransforms().
1903 Value *Y;
1904 if (match(Op0, m_OneUse(m_UDiv(m_Value(X), m_Value(Y)))) &&
1905 willNotOverflowUnsignedMul(Y, Op1, I)) {
1906 Value *YZ = Builder.CreateNUWMul(Y, Op1);
1907 auto *NewDiv = BinaryOperator::CreateUDiv(X, YZ);
1908 // The result is exact only if both of the original divides are exact.
1909 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1910 NewDiv->setIsExact();
1911 return NewDiv;
1912 }
1913
1914 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1915 // This also handles non-constant values where the sign bit is known to be
1916 // set.
1917 Type *Ty = I.getType();
1918 if (isKnownNegative(Op1, SQ.getWithInstruction(&I))) {
1919 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1920 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1921 }
1922 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1923 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1924 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1925 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1926 }
1927
1928 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1929 return NarrowDiv;
1930
1931 Value *A, *B;
1932
1933 // Look through a right-shift to find the common factor:
1934 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1935 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1936 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1937 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1938 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1939 Lshr->setIsExact();
1940 return Lshr;
1941 }
1942
1943 auto GetShiftableDenom = [&](Value *Denom) -> Value * {
1944 // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
1945 if (Value *Log2 = tryGetLog2(Op1, /*AssumeNonZero=*/true))
1946 return Log2;
1947
1948 // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
1949 if (isKnownToBeAPowerOfTwo(Denom, /*OrZero=*/true, &I))
1950 // This will increase instruction count but it's okay
1951 // since bitwise operations are substantially faster than
1952 // division.
1953 return Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Denom,
1954 Builder.getTrue());
1955
1956 return nullptr;
1957 };
1958
1959 if (auto *Res = GetShiftableDenom(Op1))
1960 return replaceInstUsesWith(
1961 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1962
1963 return nullptr;
1964}
1965
1967 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1968 SQ.getWithInstruction(&I)))
1969 return replaceInstUsesWith(I, V);
1970
1972 return X;
1973
1974 // Handle the integer div common cases
1975 if (Instruction *Common = commonIDivTransforms(I))
1976 return Common;
1977
1978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1979 Type *Ty = I.getType();
1980 Value *X;
1981 // sdiv Op0, -1 --> -Op0
1982 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1983 if (match(Op1, m_AllOnes()) ||
1984 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1985 return BinaryOperator::CreateNSWNeg(Op0);
1986
1987 // X / INT_MIN --> X == INT_MIN
1988 if (match(Op1, m_SignMask()))
1989 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1990
1991 if (I.isExact()) {
1992 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1993 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1995 return BinaryOperator::CreateExactAShr(Op0, C);
1996 }
1997
1998 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1999 Value *ShAmt;
2000 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
2001 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
2002
2003 // sdiv exact X, -1<<C --> -(ashr exact X, C)
2004 if (match(Op1, m_NegatedPower2())) {
2007 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
2008 return BinaryOperator::CreateNSWNeg(Ashr);
2009 }
2010 }
2011
2012 const APInt *Op1C;
2013 if (match(Op1, m_APInt(Op1C))) {
2014 // If the dividend is sign-extended and the constant divisor is small enough
2015 // to fit in the source type, shrink the division to the narrower type:
2016 // (sext X) sdiv C --> sext (X sdiv C)
2017 Value *Op0Src;
2018 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
2019 Op0Src->getType()->getScalarSizeInBits() >=
2020 Op1C->getSignificantBits()) {
2021
2022 // In the general case, we need to make sure that the dividend is not the
2023 // minimum signed value because dividing that by -1 is UB. But here, we
2024 // know that the -1 divisor case is already handled above.
2025
2026 Constant *NarrowDivisor =
2028 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
2029 return new SExtInst(NarrowOp, Ty);
2030 }
2031
2032 // -X / C --> X / -C (if the negation doesn't overflow).
2033 // TODO: This could be enhanced to handle arbitrary vector constants by
2034 // checking if all elements are not the min-signed-val.
2035 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
2036 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
2037 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
2038 BO->setIsExact(I.isExact());
2039 return BO;
2040 }
2041 }
2042
2043 Value *Y;
2044 // -X / -Y --> X / Y
2045 if (Value *NegOp0 = dyn_castNegVal(Op0))
2046 if (Value *NegOp1 = dyn_castNegVal(Op1)) {
2047 // -X has the wrong sign if X is INT_MIN, unless -X is nsw (then the
2048 // source is poison).
2049 bool XNotIntMin =
2050 !computeKnownBits(NegOp0, &I).getSignedMinValue().isMinSignedValue();
2051 bool SignOK = XNotIntMin || match(Op0, m_NSWNeg(m_Value()));
2052 // X / Y is UB if Y is -1 and X is INT_MIN or poison, so known bits rule
2053 // out INT_MIN here only if X is not poison.
2054 bool YNotMinusOne = !computeKnownBits(NegOp1, &I).Zero.isZero();
2055 bool NoUB =
2056 YNotMinusOne ||
2057 (XNotIntMin && isGuaranteedNotToBePoison(NegOp0, SQ.AC, &I, SQ.DT));
2058 if (SignOK && NoUB) {
2059 auto *BO = BinaryOperator::CreateSDiv(NegOp0, NegOp1);
2060 BO->setIsExact(I.isExact());
2061 return BO;
2062 }
2063 }
2064
2065 // -X / Y --> -(X / Y)
2068 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
2069
2070 // abs(X) / X --> X > -1 ? 1 : -1
2071 // X / abs(X) --> X > -1 ? 1 : -1
2072 if (match(&I, m_c_BinOp(
2074 m_Deferred(X)))) {
2075 Value *Cond = Builder.CreateIsNotNeg(X);
2076 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
2078 }
2079
2080 KnownBits KnownDividend = computeKnownBits(Op0, &I);
2081 if (!I.isExact() &&
2082 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
2083 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
2084 I.setIsExact();
2085 return &I;
2086 }
2087
2088 if (KnownDividend.isNonNegative()) {
2089 // If both operands are unsigned, turn this into a udiv.
2090 if (isKnownNonNegative(Op1, SQ.getWithInstruction(&I))) {
2091 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2092 BO->setIsExact(I.isExact());
2093 return BO;
2094 }
2095
2096 if (match(Op1, m_NegatedPower2())) {
2097 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
2098 // -> -(X udiv (1 << C)) -> -(X u>> C)
2101 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
2102 return BinaryOperator::CreateNeg(Shr);
2103 }
2104
2105 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2106 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
2107 // Safe because the only negative value (1 << Y) can take on is
2108 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
2109 // the sign bit set.
2110 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2111 BO->setIsExact(I.isExact());
2112 return BO;
2113 }
2114 }
2115
2116 // -X / X --> X == INT_MIN ? 1 : -1
2117 if (isKnownNegation(Op0, Op1)) {
2118 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
2119 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
2120 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
2122 }
2123 return nullptr;
2124}
2125
2126/// Remove negation and try to convert division into multiplication.
2127Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
2128 Constant *C;
2129 if (!match(I.getOperand(1), m_Constant(C)))
2130 return nullptr;
2131
2132 // -X / C --> X / -C
2133 Value *X;
2134 const DataLayout &DL = I.getDataLayout();
2135 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2136 if (match(I.getOperand(0), m_FNegOrFSubNegZero(m_Value(X))))
2137 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2138 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
2139
2140 // nnan X / +0.0 -> copysign(inf, X)
2141 // nnan nsz X / -0.0 -> copysign(inf, X)
2142 if (I.hasNoNaNs() &&
2143 (match(I.getOperand(1), m_PosZeroFP()) ||
2144 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
2145 IRBuilder<> B(&I);
2146 Value *CopySign = B.CreateIntrinsic(
2147 Intrinsic::copysign, {C->getType()},
2148 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
2149 CopySign->takeName(&I);
2150 return replaceInstUsesWith(I, CopySign);
2151 }
2152
2153 // If the constant divisor has an exact inverse, this is always safe. If not,
2154 // then we can still create a reciprocal if fast-math-flags allow it and the
2155 // constant is a regular number (not zero, infinite, or denormal).
2156 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
2157 return nullptr;
2158
2159 // Disallow denormal constants because we don't know what would happen
2160 // on all targets.
2161 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
2162 // denorms are flushed?
2163 auto *RecipC = ConstantFoldBinaryOpOperands(
2164 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
2165 if (!RecipC || !RecipC->isNormalFP())
2166 return nullptr;
2167
2168 // X / C --> X * (1 / C)
2169 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
2170}
2171
2172/// Remove negation and try to reassociate constant math.
2174 Constant *C;
2175 if (!match(I.getOperand(0), m_Constant(C)))
2176 return nullptr;
2177
2178 // C / -X --> -C / X
2179 Value *X;
2180 const DataLayout &DL = I.getDataLayout();
2181 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2182 if (match(I.getOperand(1), m_FNegOrFSubNegZero(m_Value(X))))
2183 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2184 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
2185
2186 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2187 return nullptr;
2188
2189 // Try to reassociate C / X expressions where X includes another constant.
2190 Constant *C2, *NewC = nullptr;
2191 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
2192 // C / (X * C2) --> (C / C2) / X
2193 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
2194 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
2195 // C / (X / C2) --> (C * C2) / X
2196 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
2197 }
2198 // Disallow denormal constants because we don't know what would happen
2199 // on all targets.
2200 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
2201 // denorms are flushed?
2202 if (!NewC || !NewC->isNormalFP())
2203 return nullptr;
2204
2205 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
2206}
2207
2208/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
2210 InstCombiner::BuilderTy &Builder) {
2211 // Z / pow(X, Y) --> Z * pow(X, -Y)
2212 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
2213 // Z / splat(pow(X, Y)) --> Z * splat(pow(X, -Y))
2214 // In the general case, this creates an extra instruction, but fmul allows
2215 // for better canonicalization and optimization than fdiv.
2216 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2217 return nullptr;
2218
2219 Value *Op0 = I.getOperand(0);
2220 Value *Op1 = I.getOperand(1);
2221
2222 Value *Divisor = Op1;
2223 Value *Splat = nullptr;
2224 if (match(Op1,
2227 m_Value(), m_ZeroMask()))))
2228 Divisor = Splat;
2229
2230 auto *II = dyn_cast<IntrinsicInst>(Divisor);
2231 if (!II || !II->hasOneUse())
2232 return nullptr;
2233
2234 Intrinsic::ID IID = II->getIntrinsicID();
2235 SmallVector<Type *, 2> Tys = {II->getType()};
2237 switch (IID) {
2238 case Intrinsic::pow:
2239 Args.push_back(II->getArgOperand(0));
2240 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
2241 break;
2242 case Intrinsic::powi: {
2243 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
2244 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
2245 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
2246 // non-standard results, so this corner case should be acceptable if the
2247 // code rules out INF values.
2248 if (!I.hasNoInfs())
2249 return nullptr;
2250 Args.push_back(II->getArgOperand(0));
2251 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
2252 Tys.push_back(II->getArgOperand(1)->getType());
2253 break;
2254 }
2255 case Intrinsic::exp:
2256 case Intrinsic::exp2:
2257 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
2258 break;
2259 default:
2260 return nullptr;
2261 }
2262
2263 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
2264 if (Pow->getType() != I.getType())
2265 Pow = Builder.CreateVectorSplat(
2266 cast<VectorType>(I.getType())->getElementCount(), Pow);
2267
2268 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2269}
2270
2271/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
2272/// instruction.
2274 InstCombiner::BuilderTy &Builder) {
2275 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
2276 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2277 return nullptr;
2278 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2279 auto *II = dyn_cast<IntrinsicInst>(Op1);
2280 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
2281 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
2282 return nullptr;
2283
2284 Value *Y, *Z;
2285 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
2286 if (!DivOp)
2287 return nullptr;
2288 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
2289 return nullptr;
2290 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
2291 !DivOp->hasOneUse())
2292 return nullptr;
2293 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
2294 Value *NewSqrt =
2295 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
2296 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
2297}
2298
2299// Change
2300// X = 1/sqrt(a)
2301// R1 = X * X
2302// R2 = a * X
2303//
2304// TO
2305//
2306// FDiv = 1/a
2307// FSqrt = sqrt(a)
2308// FMul = FDiv * FSqrt
2309// Replace Uses Of R1 With FDiv
2310// Replace Uses Of R2 With FSqrt
2311// Replace Uses Of X With FMul
2312static Instruction *
2317
2318 B.SetInsertPoint(X);
2319
2320 // Have an instruction that is representative of all of instructions in R1 and
2321 // get the most common fpmath metadata and fast-math flags on it.
2322 Value *SqrtOp = CI->getArgOperand(0);
2323 auto *FDiv = cast<Instruction>(
2324 B.CreateFDiv(ConstantFP::get(X->getType(), 1.0), SqrtOp));
2325 auto *R1FPMathMDNode = (*R1.begin())->getMetadata(LLVMContext::MD_fpmath);
2326 FastMathFlags R1FMF = (*R1.begin())->getFastMathFlags(); // Common FMF
2327 for (Instruction *I : R1) {
2328 R1FPMathMDNode = MDNode::getMostGenericFPMath(
2329 R1FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2330 R1FMF &= I->getFastMathFlags();
2331 IC->replaceInstUsesWith(*I, FDiv);
2333 }
2334 FDiv->setMetadata(LLVMContext::MD_fpmath, R1FPMathMDNode);
2335 FDiv->copyFastMathFlags(R1FMF);
2336
2337 // Have a single sqrt call instruction that is representative of all of
2338 // instructions in R2 and get the most common fpmath metadata and fast-math
2339 // flags on it.
2340 auto *FSqrt = cast<CallInst>(CI->clone());
2341 FSqrt->insertBefore(CI->getIterator());
2342 auto *R2FPMathMDNode = (*R2.begin())->getMetadata(LLVMContext::MD_fpmath);
2343 FastMathFlags R2FMF = (*R2.begin())->getFastMathFlags(); // Common FMF
2344 for (Instruction *I : R2) {
2345 R2FPMathMDNode = MDNode::getMostGenericFPMath(
2346 R2FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2347 R2FMF &= I->getFastMathFlags();
2348 IC->replaceInstUsesWith(*I, FSqrt);
2350 }
2351 FSqrt->setMetadata(LLVMContext::MD_fpmath, R2FPMathMDNode);
2352 FSqrt->copyFastMathFlags(R2FMF);
2353
2355 // If X = -1/sqrt(a) initially,then FMul = -(FDiv * FSqrt)
2356 if (match(X, m_FDiv(m_SpecificFP(-1.0), m_Specific(CI)))) {
2357 Value *Mul = B.CreateFMul(FDiv, FSqrt);
2358 FMul = cast<Instruction>(B.CreateFNeg(Mul));
2359 } else
2360 FMul = cast<Instruction>(B.CreateFMul(FDiv, FSqrt));
2361 FMul->copyMetadata(*X);
2362 FMul->copyFastMathFlags(FastMathFlags::intersectRewrite(R1FMF, R2FMF) |
2363 FastMathFlags::unionValue(R1FMF, R2FMF));
2364 return IC->replaceInstUsesWith(*X, FMul);
2365}
2366
2368 Module *M = I.getModule();
2369
2370 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
2371 I.getFastMathFlags(),
2372 SQ.getWithInstruction(&I)))
2373 return replaceInstUsesWith(I, V);
2374
2376 return X;
2377
2379 return Phi;
2380
2381 if (Instruction *R = foldFDivConstantDivisor(I))
2382 return R;
2383
2385 return R;
2386
2387 if (Instruction *R = foldFPSignBitOps(I))
2388 return R;
2389
2390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2391
2392 // Convert
2393 // x = 1.0/sqrt(a)
2394 // r1 = x * x;
2395 // r2 = a/sqrt(a);
2396 //
2397 // TO
2398 //
2399 // r1 = 1/a
2400 // r2 = sqrt(a)
2401 // x = r1 * r2
2403 if (isFSqrtDivToFMulLegal(&I, R1, R2)) {
2404 CallInst *CI = cast<CallInst>(I.getOperand(1));
2405 if (Instruction *D = convertFSqrtDivIntoFMul(CI, &I, R1, R2, Builder, this))
2406 return D;
2407 }
2408
2409 if (isa<Constant>(Op0))
2411 if (Instruction *R = FoldOpIntoSelect(I, SI))
2412 return R;
2413
2414 if (isa<Constant>(Op1))
2416 if (Instruction *R = FoldOpIntoSelect(I, SI))
2417 return R;
2418
2419 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
2420 Value *X, *Y;
2421 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2422 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
2423 // (X / Y) / Z => X / (Y * Z)
2424 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
2425 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
2426 }
2427 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2428 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
2429 // Z / (X / Y) => (Y * Z) / X
2430 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
2431 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
2432 }
2433 // Z / (1.0 / Y) => (Y * Z)
2434 //
2435 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
2436 // m_OneUse check is avoided because even in the case of the multiple uses
2437 // for 1.0/Y, the number of instructions remain the same and a division is
2438 // replaced by a multiplication.
2439 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
2440 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
2441 }
2442
2443 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
2444 // sin(X) / cos(X) -> tan(X)
2445 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
2446 Value *X;
2447 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
2449 bool IsCot =
2450 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
2452
2453 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
2454 LibFunc_tanf, LibFunc_tanl)) {
2455 IRBuilder<> B(&I);
2457 B.setFastMathFlags(I.getFastMathFlags());
2458 AttributeList Attrs =
2459 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
2460 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
2461 LibFunc_tanl, B, Attrs);
2462 if (IsCot)
2463 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
2464 return replaceInstUsesWith(I, Res);
2465 }
2466 }
2467
2468 // X / (X * Y) --> 1.0 / Y
2469 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
2470 // We can ignore the possibility that X is infinity because INF/INF is NaN.
2471 Value *X, *Y;
2472 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
2473 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
2474 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
2475 replaceOperand(I, 1, Y);
2476 return &I;
2477 }
2478
2479 // X / fabs(X) -> copysign(1.0, X)
2480 // fabs(X) / X -> copysign(1.0, X)
2481 if (I.hasNoNaNs() && I.hasNoInfs() &&
2482 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
2483 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
2484 Value *V = Builder.CreateBinaryIntrinsic(
2485 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
2486 return replaceInstUsesWith(I, V);
2487 }
2488
2490 return Mul;
2491
2493 return Mul;
2494
2495 // pow(X, Y) / X --> pow(X, Y-1)
2496 if (I.hasAllowReassoc() &&
2498 m_Value(Y))))) {
2499 Value *Y1 =
2500 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
2501 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
2502 return replaceInstUsesWith(I, Pow);
2503 }
2504
2505 if (Instruction *FoldedPowi = foldPowiReassoc(I))
2506 return FoldedPowi;
2507
2508 return nullptr;
2509}
2510
2511// Variety of transform for:
2512// (urem/srem (mul X, Y), (mul X, Z))
2513// (urem/srem (shl X, Y), (shl X, Z))
2514// (urem/srem (shl Y, X), (shl Z, X))
2515// NB: The shift cases are really just extensions of the mul case. We treat
2516// shift as Val * (1 << Amt).
2518 InstCombinerImpl &IC) {
2519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
2520 APInt Y, Z;
2521 bool ShiftByX = false;
2522
2523 // If V is not nullptr, it will be matched using m_Specific.
2524 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C,
2525 bool &PreserveNSW) -> bool {
2526 const APInt *Tmp = nullptr;
2527 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
2528 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
2529 C = *Tmp;
2530 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
2531 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp))))) {
2532 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
2533 // We cannot preserve NSW when shifting by BW - 1.
2534 PreserveNSW = Tmp->ult(Tmp->getBitWidth() - 1);
2535 }
2536 if (Tmp != nullptr)
2537 return true;
2538
2539 // Reset `V` so we don't start with specific value on next match attempt.
2540 V = nullptr;
2541 return false;
2542 };
2543
2544 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
2545 const APInt *Tmp = nullptr;
2546 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
2547 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
2548 C = *Tmp;
2549 return true;
2550 }
2551
2552 // Reset `V` so we don't start with specific value on next match attempt.
2553 V = nullptr;
2554 return false;
2555 };
2556
2557 bool Op0PreserveNSW = true, Op1PreserveNSW = true;
2558 if (MatchShiftOrMulXC(Op0, X, Y, Op0PreserveNSW) &&
2559 MatchShiftOrMulXC(Op1, X, Z, Op1PreserveNSW)) {
2560 // pass
2561 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
2562 ShiftByX = true;
2563 } else {
2564 return nullptr;
2565 }
2566
2567 bool IsSRem = I.getOpcode() == Instruction::SRem;
2568
2570 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2571 // Z or Z >= Y.
2572 bool BO0HasNSW = Op0PreserveNSW && BO0->hasNoSignedWrap();
2573 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2574 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2575
2576 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
2577 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2578 // if (rem Y, Z) == 0
2579 // -> 0
2580 if (RemYZ.isZero() && BO0NoWrap)
2581 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
2582
2583 // Helper function to emit either (RemSimplificationC << X) or
2584 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2585 // (shl V, X) or (mul V, X) respectively.
2586 auto CreateMulOrShift =
2587 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2588 Value *RemSimplification =
2589 ConstantInt::get(I.getType(), RemSimplificationC);
2590 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2591 : BinaryOperator::CreateMul(X, RemSimplification);
2592 };
2593
2595 bool BO1HasNSW = Op1PreserveNSW && BO1->hasNoSignedWrap();
2596 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2597 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2598 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2599 // if (rem Y, Z) == Y
2600 // -> (mul nuw/nsw X, Y)
2601 if (RemYZ == Y && BO1NoWrap) {
2602 BinaryOperator *BO = CreateMulOrShift(Y);
2603 // Copy any overflow flags from Op0.
2604 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2605 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2606 return BO;
2607 }
2608
2609 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2610 // if Y >= Z
2611 // -> (mul {nuw} nsw X, (rem Y, Z))
2612 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2613 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2614 BO->setHasNoSignedWrap();
2615 BO->setHasNoUnsignedWrap(BO0HasNUW);
2616 return BO;
2617 }
2618
2619 return nullptr;
2620}
2621
2622/// This function implements the transforms common to both integer remainder
2623/// instructions (urem and srem). It is called by the visitors to those integer
2624/// remainder instructions.
2625/// Common integer remainder transforms
2628 return Res;
2629
2630 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2631
2632 if (isa<Constant>(Op1)) {
2633 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2634 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2635 if (Instruction *R = FoldOpIntoSelect(I, SI))
2636 return R;
2637 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2638 const APInt *Op1Int;
2639 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2640 (I.getOpcode() == Instruction::URem ||
2641 !Op1Int->isMinSignedValue())) {
2642 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2643 // predecessor blocks, so do this only if we know the srem or urem
2644 // will not fault.
2645 if (Instruction *NV = foldOpIntoPhi(I, PN))
2646 return NV;
2647 }
2648 }
2649
2650 // See if we can fold away this rem instruction.
2652 return &I;
2653 }
2654 }
2655
2656 if (Instruction *R = simplifyIRemMulShl(I, *this))
2657 return R;
2658
2659 return nullptr;
2660}
2661
2663 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2664 SQ.getWithInstruction(&I)))
2665 return replaceInstUsesWith(I, V);
2666
2668 return X;
2669
2670 if (Instruction *common = commonIRemTransforms(I))
2671 return common;
2672
2673 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2674 return NarrowRem;
2675
2676 // X urem Y -> X and Y-1, where Y is a power of 2,
2677 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2678 Type *Ty = I.getType();
2679 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2680 // This may increase instruction count, we don't enforce that Y is a
2681 // constant.
2683 Value *Add = Builder.CreateAdd(Op1, N1);
2684 return BinaryOperator::CreateAnd(Op0, Add);
2685 }
2686
2687 // 1 urem X -> zext(X != 1)
2688 if (match(Op0, m_One())) {
2689 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2690 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2691 }
2692
2693 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2694 // Op0 must be frozen because we are increasing its number of uses.
2695 if (match(Op1, m_Negative())) {
2696 Value *F0 = Op0;
2697 if (!isGuaranteedNotToBeUndef(Op0))
2698 F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2699 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2700 Value *Sub = Builder.CreateSub(F0, Op1);
2701 return createSelectInstWithUnknownProfile(Cmp, F0, Sub);
2702 }
2703
2704 // If the divisor is a sext of a boolean, then the divisor must be max
2705 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2706 // max unsigned value. In that case, the remainder is 0:
2707 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2708 Value *X;
2709 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2710 Value *FrozenOp0 = Op0;
2711 if (!isGuaranteedNotToBeUndef(Op0))
2712 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2713 Value *Cmp =
2714 Builder.CreateICmpEQ(FrozenOp0, ConstantInt::getAllOnesValue(Ty));
2715 return createSelectInstWithUnknownProfile(
2716 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2717 }
2718
2719 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2720 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2721 Value *Val =
2722 simplifyICmpInst(ICmpInst::ICMP_ULT, X, Op1, SQ.getWithInstruction(&I));
2723 if (Val && match(Val, m_One())) {
2724 Value *FrozenOp0 = Op0;
2725 if (!isGuaranteedNotToBeUndef(Op0))
2726 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2727 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2728 return createSelectInstWithUnknownProfile(
2729 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2730 }
2731 }
2732
2733 return nullptr;
2734}
2735
2737 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2738 SQ.getWithInstruction(&I)))
2739 return replaceInstUsesWith(I, V);
2740
2742 return X;
2743
2744 // Handle the integer rem common cases
2745 if (Instruction *Common = commonIRemTransforms(I))
2746 return Common;
2747
2748 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2749 {
2750 const APInt *Y;
2751 // X % -Y -> X % Y
2752 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2753 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2754 }
2755
2756 // -X srem Y --> -(X srem Y)
2757 Value *X, *Y;
2759 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
2760
2761 // If the sign bits of both operands are zero (i.e. we can prove they are
2762 // unsigned inputs), turn this into a urem.
2763 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2764 if (MaskedValueIsZero(Op1, Mask, &I) && MaskedValueIsZero(Op0, Mask, &I)) {
2765 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2766 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2767 }
2768
2769 // If it's a constant vector, flip any negative values positive.
2771 Constant *C = cast<Constant>(Op1);
2772 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2773
2774 bool hasNegative = false;
2775 bool hasMissing = false;
2776 for (unsigned i = 0; i != VWidth; ++i) {
2777 Constant *Elt = C->getAggregateElement(i);
2778 if (!Elt) {
2779 hasMissing = true;
2780 break;
2781 }
2782
2783 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2784 if (RHS->isNegative())
2785 hasNegative = true;
2786 }
2787
2788 if (hasNegative && !hasMissing) {
2789 SmallVector<Constant *, 16> Elts(VWidth);
2790 for (unsigned i = 0; i != VWidth; ++i) {
2791 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2792 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2793 if (RHS->isNegative())
2795 }
2796 }
2797
2798 Constant *NewRHSV = ConstantVector::get(Elts);
2799 if (NewRHSV != C) // Don't loop on -MININT
2800 return replaceOperand(I, 1, NewRHSV);
2801 }
2802 }
2803
2804 return nullptr;
2805}
2806
2808 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2809 I.getFastMathFlags(),
2810 SQ.getWithInstruction(&I)))
2811 return replaceInstUsesWith(I, V);
2812
2814 return X;
2815
2817 return Phi;
2818
2819 // Cases:
2820 // frem(x, -y) -> frem(x, y)
2821 // frem(x, |y|) -> frem(x, y)
2822 // frem(x, copysign(y, z)) -> frem(x, y)
2823 Value *Y = I.getOperand(1);
2824 Value *StrippedY = stripSignOnlyFPOps(Y);
2825 if (StrippedY != Y)
2826 return replaceOperand(I, 1, StrippedY);
2827
2828 return nullptr;
2829}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides internal interfaces used to implement the InstCombine.
static Instruction * convertFSqrtDivIntoFMul(CallInst *CI, Instruction *X, const SmallPtrSetImpl< Instruction * > &R1, const SmallPtrSetImpl< Instruction * > &R2, InstCombiner::BuilderTy &B, InstCombinerImpl *IC)
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 bool getFSqrtDivOptPattern(Instruction *Div, SmallPtrSetImpl< Instruction * > &R1, SmallPtrSetImpl< Instruction * > &R2)
static Value * foldMulSelectToNegate(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool isFSqrtDivToFMulLegal(Instruction *X, SmallPtrSetImpl< Instruction * > &R1, SmallPtrSetImpl< Instruction * > &R2)
static Instruction * foldFDivPowDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Negate the exponent of pow/exp to fold division-by-pow() into multiply.
static Value * simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, Instruction &CtxI)
The specific integer value is used in a context where it is known to be non-zero.
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 bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, bool IsSigned)
True if C1 is a multiple of C2. Quotient contains C1/C2.
static Instruction * foldFDivSqrtDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv instruction.
static Instruction * foldFDivConstantDividend(BinaryOperator &I)
Remove negation and try to reassociate constant math.
static Value * foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool isKnownExactFromRem(const BinaryOperator &Div, const SimplifyQuery &Q)
Return true if a matching remainder is known to be zero at the division.
This file provides the interface for the instcombine pass implementation.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
#define R2(n)
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
int64_t C1
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1928
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:413
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2052
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:271
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static BinaryOperator * CreateExact(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition InstrTypes.h:344
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:279
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:283
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:275
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:254
static LLVM_ABI BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Conditional Branch instruction.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI 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...
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags intersectRewrite(FastMathFlags LHS, FastMathFlags RHS)
Intersect rewrite-based flags.
Definition FMF.h:116
static FastMathFlags unionValue(FastMathFlags LHS, FastMathFlags RHS)
Union value flags.
Definition FMF.h:124
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Instruction * visitMul(BinaryOperator &I)
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)
bool SimplifyDemandedInstructionFPClass(Instruction &Inst)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold)
Take the exact integer log2 of the value.
Instruction * visitSRem(BinaryOperator &I)
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
Instruction * visitFDiv(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I)
Fold a divide or remainder with a select instruction divisor when one of the select operands is zero.
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * commonIDivRemTransforms(BinaryOperator &I)
Common integer divide/remainder transforms.
Value * tryGetLog2(Value *Op, bool AssumeNonZero)
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)
InstCombinerImpl(InstructionWorklist &Worklist, Function &F, AAResults *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, const DataLayout &DL, ReversePostOrderTraversal< BasicBlock * > &RPOT, const InstCombineCLOptions &CLOpts)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * visitFMul(BinaryOperator &I)
Instruction * foldFMulReassoc(BinaryOperator &I)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * foldPowiReassoc(BinaryOperator &I)
Instruction * visitSDiv(BinaryOperator &I)
Instruction * commonIRemTransforms(BinaryOperator &I)
This function implements the transforms common to both integer remainder instructions (urem and srem)...
SimplifyQuery SQ
const DataLayout & getDataLayout() const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
const DataLayout & DL
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
static Value * stripSignOnlyFPOps(Value *Val)
Ignore all operations which only change the sign of a value, returning the underlying magnitude value...
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool hasNoSignedZeros() const LLVM_READONLY
Determine whether the no-signed-zeros flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
A wrapper class for inspecting calls to intrinsic functions.
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:156
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
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.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< 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()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_UndefValue()
Match an arbitrary UndefValue constant.
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
AllowFmf_match< T, FastMathFlags::AllowReassoc > m_AllowReassoc(const T &SubPattern)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
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< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI 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.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI 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.
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
LLVM_ABI Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
LLVM_ABI 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.
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI 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,...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_ABI 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.
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI 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.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ Mul
Product of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI 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
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI 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:202
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI 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:881
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
Matching combinators.
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC