LLVM 22.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"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Instruction.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Operator.h"
30#include "llvm/IR/Type.h"
31#include "llvm/IR/Value.h"
36#include <cassert>
37
38#define DEBUG_TYPE "instcombine"
40
41using namespace llvm;
42using namespace PatternMatch;
43
44/// The specific integer value is used in a context where it is known to be
45/// non-zero. If this allows us to simplify the computation, do so and return
46/// the new operand, otherwise return null.
48 Instruction &CxtI) {
49 // If V has multiple uses, then we would have to do more analysis to determine
50 // if this is safe. For example, the use could be in dynamically unreached
51 // code.
52 if (!V->hasOneUse()) return nullptr;
53
54 bool MadeChange = false;
55
56 // ((1 << A) >>u B) --> (1 << (A-B))
57 // Because V cannot be zero, we know that B is less than A.
58 Value *A = nullptr, *B = nullptr, *One = nullptr;
59 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
60 match(One, m_One())) {
61 A = IC.Builder.CreateSub(A, B);
62 return IC.Builder.CreateShl(One, A);
63 }
64
65 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
66 // inexact. Similarly for <<.
68 if (I && I->isLogicalShift() &&
69 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, &CxtI)) {
70 // We know that this is an exact/nuw shift and that the input is a
71 // non-zero context as well.
72 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
73 IC.replaceOperand(*I, 0, V2);
74 MadeChange = true;
75 }
76
77 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
78 I->setIsExact();
79 MadeChange = true;
80 }
81
82 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
83 I->setHasNoUnsignedWrap();
84 MadeChange = true;
85 }
86 }
87
88 // TODO: Lots more we could do here:
89 // If V is a phi node, we can call this on each of its operands.
90 // "select cond, X, 0" can simplify to "X".
91
92 return MadeChange ? V : nullptr;
93}
94
95// TODO: This is a specific form of a much more general pattern.
96// We could detect a select with any binop identity constant, or we
97// could use SimplifyBinOp to see if either arm of the select reduces.
98// But that needs to be done carefully and/or while removing potential
99// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
101 InstCombiner::BuilderTy &Builder) {
102 Value *Cond, *OtherOp;
103
104 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
105 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
107 m_Value(OtherOp)))) {
108 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
109 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
110 return Builder.CreateSelect(Cond, OtherOp, Neg);
111 }
112 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
113 // 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, Neg, OtherOp);
119 }
120
121 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
122 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
124 m_SpecificFP(-1.0))),
125 m_Value(OtherOp))))
126 return Builder.CreateSelectFMF(Cond, OtherOp,
127 Builder.CreateFNegFMF(OtherOp, &I), &I);
128
129 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
130 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
132 m_SpecificFP(1.0))),
133 m_Value(OtherOp))))
134 return Builder.CreateSelectFMF(Cond, Builder.CreateFNegFMF(OtherOp, &I),
135 OtherOp, &I);
136
137 return nullptr;
138}
139
140/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
141/// Callers are expected to call this twice to handle commuted patterns.
142static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
143 InstCombiner::BuilderTy &Builder) {
144 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
145 if (CommuteOperands)
146 std::swap(X, Y);
147
148 const bool HasNSW = Mul.hasNoSignedWrap();
149 const bool HasNUW = Mul.hasNoUnsignedWrap();
150
151 // X * (1 << Z) --> X << Z
152 Value *Z;
153 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
154 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
155 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
156 }
157
158 // Similar to above, but an increment of the shifted value becomes an add:
159 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
160 // This increases uses of X, so it may require a freeze, but that is still
161 // expected to be an improvement because it removes the multiply.
162 BinaryOperator *Shift;
163 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
164 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
165 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
166 Value *FrX = X;
168 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
169 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
170 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
171 }
172
173 // Similar to above, but a decrement of the shifted value is disguised as
174 // 'not' and becomes a sub:
175 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
176 // This increases uses of X, so it may require a freeze, but that is still
177 // expected to be an improvement because it removes the multiply.
179 Value *FrX = X;
181 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
182 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
183 return Builder.CreateSub(Shl, FrX, Mul.getName());
184 }
185
186 return nullptr;
187}
188
190 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
191 if (Value *V =
192 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
193 SQ.getWithInstruction(&I)))
194 return replaceInstUsesWith(I, V);
195
197 return &I;
198
200 return X;
201
203 return Phi;
204
206 return replaceInstUsesWith(I, V);
207
208 Type *Ty = I.getType();
209 const unsigned BitWidth = Ty->getScalarSizeInBits();
210 const bool HasNSW = I.hasNoSignedWrap();
211 const bool HasNUW = I.hasNoUnsignedWrap();
212
213 // X * -1 --> 0 - X
214 if (match(Op1, m_AllOnes())) {
215 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
217 }
218
219 // Also allow combining multiply instructions on vectors.
220 {
221 Value *NewOp;
222 Constant *C1, *C2;
223 const APInt *IVal;
224 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_ImmConstant(C2)),
225 m_ImmConstant(C1))) &&
226 match(C1, m_APInt(IVal))) {
227 // ((X << C2)*C1) == (X * (C1 << C2))
228 Constant *Shl =
229 ConstantFoldBinaryOpOperands(Instruction::Shl, C1, C2, DL);
230 assert(Shl && "Constant folding of immediate constants failed");
231 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
232 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
233 if (HasNUW && Mul->hasNoUnsignedWrap())
235 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
236 BO->setHasNoSignedWrap();
237 return BO;
238 }
239
240 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
241 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
242 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C1)) {
243 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
244
245 if (HasNUW)
247 if (HasNSW) {
248 const APInt *V;
249 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
250 Shl->setHasNoSignedWrap();
251 }
252
253 return Shl;
254 }
255 }
256 }
257
258 // mul (shr exact X, N), (2^N + 1) -> add (X, shr exact (X, N))
259 {
260 Value *NewOp;
261 const APInt *ShiftC;
262 const APInt *MulAP;
263 if (BitWidth > 2 &&
264 match(&I, m_Mul(m_Exact(m_Shr(m_Value(NewOp), m_APInt(ShiftC))),
265 m_APInt(MulAP))) &&
266 (*MulAP - 1).isPowerOf2() && *ShiftC == MulAP->logBase2()) {
267 Value *BinOp = Op0;
269
270 // mul nuw (ashr exact X, N) -> add nuw (X, lshr exact (X, N))
271 if (HasNUW && OpBO->getOpcode() == Instruction::AShr && OpBO->hasOneUse())
272 BinOp = Builder.CreateLShr(NewOp, ConstantInt::get(Ty, *ShiftC), "",
273 /*isExact=*/true);
274
275 auto *NewAdd = BinaryOperator::CreateAdd(NewOp, BinOp);
276 if (HasNSW && (HasNUW || OpBO->getOpcode() == Instruction::LShr ||
277 ShiftC->getZExtValue() < BitWidth - 1))
278 NewAdd->setHasNoSignedWrap(true);
279
280 NewAdd->setHasNoUnsignedWrap(HasNUW);
281 return NewAdd;
282 }
283 }
284
285 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
286 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
287 // The "* (1<<C)" thus becomes a potential shifting opportunity.
288 if (Value *NegOp0 =
289 Negator::Negate(/*IsNegation*/ true, HasNSW, Op0, *this)) {
290 auto *Op1C = cast<Constant>(Op1);
291 return replaceInstUsesWith(
292 I, Builder.CreateMul(NegOp0, ConstantExpr::getNeg(Op1C), "",
293 /*HasNUW=*/false,
294 HasNSW && Op1C->isNotMinSignedValue()));
295 }
296
297 // Try to convert multiply of extended operand to narrow negate and shift
298 // for better analysis.
299 // This is valid if the shift amount (trailing zeros in the multiplier
300 // constant) clears more high bits than the bitwidth difference between
301 // source and destination types:
302 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
303 const APInt *NegPow2C;
304 Value *X;
305 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
306 match(Op1, m_APIntAllowPoison(NegPow2C))) {
307 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
308 unsigned ShiftAmt = NegPow2C->countr_zero();
309 if (ShiftAmt >= BitWidth - SrcWidth) {
310 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
311 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
312 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
313 }
314 }
315 }
316
317 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
318 return FoldedMul;
319
320 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(I))
321 return FoldedLogic;
322
323 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
324 return replaceInstUsesWith(I, FoldedMul);
325
326 // Simplify mul instructions with a constant RHS.
327 Constant *MulC;
328 if (match(Op1, m_ImmConstant(MulC))) {
329 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
330 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
331 Value *X;
332 Constant *C1;
333 if (match(Op0, m_OneUse(m_AddLike(m_Value(X), m_ImmConstant(C1))))) {
334 // C1*MulC simplifies to a tidier constant.
335 Value *NewC = Builder.CreateMul(C1, MulC);
336 auto *BOp0 = cast<BinaryOperator>(Op0);
337 bool Op0NUW =
338 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
339 Value *NewMul = Builder.CreateMul(X, MulC);
340 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
341 if (HasNUW && Op0NUW) {
342 // If NewMulBO is constant we also can set BO to nuw.
343 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
344 NewMulBO->setHasNoUnsignedWrap();
345 BO->setHasNoUnsignedWrap();
346 }
347 return BO;
348 }
349 }
350
351 // abs(X) * abs(X) -> X * X
352 Value *X;
353 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
354 return BinaryOperator::CreateMul(X, X);
355
356 {
357 Value *Y;
358 // abs(X) * abs(Y) -> abs(X * Y)
359 if (I.hasNoSignedWrap() &&
360 match(Op0,
363 return replaceInstUsesWith(
364 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
365 Builder.CreateNSWMul(X, Y),
366 Builder.getTrue()));
367 }
368
369 // -X * C --> X * -C
370 Value *Y;
371 Constant *Op1C;
372 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
373 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
374
375 // -X * -Y --> X * Y
376 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
377 auto *NewMul = BinaryOperator::CreateMul(X, Y);
378 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
380 NewMul->setHasNoSignedWrap();
381 return NewMul;
382 }
383
384 // -X * Y --> -(X * Y)
385 // X * -Y --> -(X * Y)
387 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
388
389 // (-X * Y) * -X --> (X * Y) * X
390 // (-X << Y) * -X --> (X << Y) * X
391 if (match(Op1, m_Neg(m_Value(X)))) {
392 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
393 return BinaryOperator::CreateMul(NegOp0, X);
394 }
395
396 if (Op0->hasOneUse()) {
397 // (mul (div exact X, C0), C1)
398 // -> (div exact X, C0 / C1)
399 // iff C0 % C1 == 0 and X / (C0 / C1) doesn't create UB.
400 const APInt *C1;
401 auto UDivCheck = [&C1](const APInt &C) { return C.urem(*C1).isZero(); };
402 auto SDivCheck = [&C1](const APInt &C) {
403 APInt Quot, Rem;
404 APInt::sdivrem(C, *C1, Quot, Rem);
405 return Rem.isZero() && !Quot.isAllOnes();
406 };
407 if (match(Op1, m_APInt(C1)) &&
408 (match(Op0, m_Exact(m_UDiv(m_Value(X), m_CheckedInt(UDivCheck)))) ||
409 match(Op0, m_Exact(m_SDiv(m_Value(X), m_CheckedInt(SDivCheck)))))) {
410 auto BOpc = cast<BinaryOperator>(Op0)->getOpcode();
412 BOpc, X,
413 Builder.CreateBinOp(BOpc, cast<BinaryOperator>(Op0)->getOperand(1),
414 Op1));
415 }
416 }
417
418 // (X / Y) * Y = X - (X % Y)
419 // (X / Y) * -Y = (X % Y) - X
420 {
421 Value *Y = Op1;
423 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
424 Div->getOpcode() != Instruction::SDiv)) {
425 Y = Op0;
426 Div = dyn_cast<BinaryOperator>(Op1);
427 }
428 Value *Neg = dyn_castNegVal(Y);
429 if (Div && Div->hasOneUse() &&
430 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
431 (Div->getOpcode() == Instruction::UDiv ||
432 Div->getOpcode() == Instruction::SDiv)) {
433 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
434
435 // If the division is exact, X % Y is zero, so we end up with X or -X.
436 if (Div->isExact()) {
437 if (DivOp1 == Y)
438 return replaceInstUsesWith(I, X);
440 }
441
442 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
443 : Instruction::SRem;
444 // X must be frozen because we are increasing its number of uses.
445 Value *XFreeze = X;
447 XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
448 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
449 if (DivOp1 == Y)
450 return BinaryOperator::CreateSub(XFreeze, Rem);
451 return BinaryOperator::CreateSub(Rem, XFreeze);
452 }
453 }
454
455 // Fold the following two scenarios:
456 // 1) i1 mul -> i1 and.
457 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
458 // Note: We could use known bits to generalize this and related patterns with
459 // shifts/truncs
460 if (Ty->isIntOrIntVectorTy(1) ||
461 (match(Op0, m_And(m_Value(), m_One())) &&
462 match(Op1, m_And(m_Value(), m_One()))))
463 return BinaryOperator::CreateAnd(Op0, Op1);
464
465 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
466 return replaceInstUsesWith(I, R);
467 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
468 return replaceInstUsesWith(I, R);
469
470 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
471 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
472 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
473 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
474 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
475 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
476 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
477 Value *And = Builder.CreateAnd(X, Y, "mulbool");
478 return CastInst::Create(Instruction::ZExt, And, Ty);
479 }
480 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
481 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
482 // Note: -1 * 1 == 1 * -1 == -1
483 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
484 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
485 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
486 (Op0->hasOneUse() || Op1->hasOneUse())) {
487 Value *And = Builder.CreateAnd(X, Y, "mulbool");
488 return CastInst::Create(Instruction::SExt, And, Ty);
489 }
490
491 // (zext bool X) * Y --> X ? Y : 0
492 // Y * (zext bool X) --> X ? Y : 0
493 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
495 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
497
498 // mul (sext X), Y -> select X, -Y, 0
499 // mul Y, (sext X) -> select X, -Y, 0
500 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
501 X->getType()->isIntOrIntVectorTy(1))
502 return SelectInst::Create(X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
504
505 Constant *ImmC;
506 if (match(Op1, m_ImmConstant(ImmC))) {
507 // (sext bool X) * C --> X ? -C : 0
508 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
509 Constant *NegC = ConstantExpr::getNeg(ImmC);
511 }
512
513 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
514 const APInt *C;
515 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
516 *C == C->getBitWidth() - 1) {
517 Constant *NegC = ConstantExpr::getNeg(ImmC);
518 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
519 return SelectInst::Create(IsNeg, NegC, ConstantInt::getNullValue(Ty));
520 }
521 }
522
523 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
524 // TODO: We are not checking one-use because the elimination of the multiply
525 // is better for analysis?
526 const APInt *C;
527 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
528 *C == C->getBitWidth() - 1) {
529 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
531 }
532
533 // (and X, 1) * Y --> (trunc X) ? Y : 0
534 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
535 Value *Tr = Builder.CreateTrunc(X, CmpInst::makeCmpResultType(Ty));
537 }
538
539 // ((ashr X, 31) | 1) * X --> abs(X)
540 // X * ((ashr X, 31) | 1) --> abs(X)
543 m_One()),
544 m_Deferred(X)))) {
545 Value *Abs = Builder.CreateBinaryIntrinsic(
546 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
547 Abs->takeName(&I);
548 return replaceInstUsesWith(I, Abs);
549 }
550
551 if (Instruction *Ext = narrowMathIfNoOverflow(I))
552 return Ext;
553
555 return Res;
556
557 // (mul Op0 Op1):
558 // if Log2(Op0) folds away ->
559 // (shl Op1, Log2(Op0))
560 // if Log2(Op1) folds away ->
561 // (shl Op0, Log2(Op1))
562 if (Value *Res = tryGetLog2(Op0, /*AssumeNonZero=*/false)) {
563 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
564 // We can only propegate nuw flag.
565 Shl->setHasNoUnsignedWrap(HasNUW);
566 return Shl;
567 }
568 if (Value *Res = tryGetLog2(Op1, /*AssumeNonZero=*/false)) {
569 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
570 // We can only propegate nuw flag.
571 Shl->setHasNoUnsignedWrap(HasNUW);
572 return Shl;
573 }
574
575 bool Changed = false;
576 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
577 Changed = true;
578 I.setHasNoSignedWrap(true);
579 }
580
581 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I, I.hasNoSignedWrap())) {
582 Changed = true;
583 I.setHasNoUnsignedWrap(true);
584 }
585
586 return Changed ? &I : nullptr;
587}
588
589Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
590 BinaryOperator::BinaryOps Opcode = I.getOpcode();
591 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
592 "Expected fmul or fdiv");
593
594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
595 Value *X, *Y;
596
597 // -X * -Y --> X * Y
598 // -X / -Y --> X / Y
599 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
600 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
601
602 // fabs(X) * fabs(X) -> X * X
603 // fabs(X) / fabs(X) -> X / X
604 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
605 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
606
607 // fabs(X) * fabs(Y) --> fabs(X * Y)
608 // fabs(X) / fabs(Y) --> fabs(X / Y)
609 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
610 (Op0->hasOneUse() || Op1->hasOneUse())) {
611 Value *XY = Builder.CreateBinOpFMF(Opcode, X, Y, &I);
612 Value *Fabs =
613 Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY, &I, I.getName());
614 return replaceInstUsesWith(I, Fabs);
615 }
616
617 return nullptr;
618}
619
621 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
622 Value *Y, Value *Z) {
623 InstCombiner::BuilderTy &Builder = IC.Builder;
624 Value *YZ = Builder.CreateAdd(Y, Z);
625 Instruction *NewPow = Builder.CreateIntrinsic(
626 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
627
628 return NewPow;
629 };
630
631 Value *X, *Y, *Z;
632 unsigned Opcode = I.getOpcode();
633 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
634 "Unexpected opcode");
635
636 // powi(X, Y) * X --> powi(X, Y+1)
637 // X * powi(X, Y) --> powi(X, Y+1)
639 m_Value(X), m_Value(Y)))),
640 m_Deferred(X)))) {
641 Constant *One = ConstantInt::get(Y->getType(), 1);
642 if (willNotOverflowSignedAdd(Y, One, I)) {
643 Instruction *NewPow = createPowiExpr(I, *this, X, Y, One);
644 return replaceInstUsesWith(I, NewPow);
645 }
646 }
647
648 // powi(x, y) * powi(x, z) -> powi(x, y + z)
649 Value *Op0 = I.getOperand(0);
650 Value *Op1 = I.getOperand(1);
651 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
655 m_Value(Z)))) &&
656 Y->getType() == Z->getType()) {
657 Instruction *NewPow = createPowiExpr(I, *this, X, Y, Z);
658 return replaceInstUsesWith(I, NewPow);
659 }
660
661 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
662 // powi(X, Y) / X --> powi(X, Y-1)
663 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
664 // nnan are required.
665 // TODO: Multi-use may be also better off creating Powi(x,y-1)
667 m_Specific(Op1), m_Value(Y))))) &&
668 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
669 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
670 Instruction *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
671 return replaceInstUsesWith(I, NewPow);
672 }
673
674 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
675 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
676 // nnan are required.
677 // TODO: Multi-use may be also better off creating Powi(x,y-1)
679 m_Value(X), m_Value(Y))))) &&
681 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
682 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
683 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
684 return BinaryOperator::CreateFDivFMF(NewPow, Z, &I);
685 }
686 }
687
688 return nullptr;
689}
690
691// If we have the following pattern,
692// X = 1.0/sqrt(a)
693// R1 = X * X
694// R2 = a/sqrt(a)
695// then this method collects all the instructions that match R1 and R2.
699 Value *A;
700 if (match(Div, m_FDiv(m_FPOne(), m_Sqrt(m_Value(A)))) ||
701 match(Div, m_FDiv(m_SpecificFP(-1.0), m_Sqrt(m_Value(A))))) {
702 for (User *U : Div->users()) {
704 if (match(I, m_FMul(m_Specific(Div), m_Specific(Div))))
705 R1.insert(I);
706 }
707
708 CallInst *CI = cast<CallInst>(Div->getOperand(1));
709 for (User *U : CI->users()) {
712 R2.insert(I);
713 }
714 }
715 return !R1.empty() && !R2.empty();
716}
717
718// Check legality for transforming
719// x = 1.0/sqrt(a)
720// r1 = x * x;
721// r2 = a/sqrt(a);
722//
723// TO
724//
725// r1 = 1/a
726// r2 = sqrt(a)
727// x = r1 * r2
728// This transform works only when 'a' is known positive.
732 // Check if the required pattern for the transformation exists.
733 if (!getFSqrtDivOptPattern(X, R1, R2))
734 return false;
735
736 BasicBlock *BBx = X->getParent();
737 BasicBlock *BBr1 = (*R1.begin())->getParent();
738 BasicBlock *BBr2 = (*R2.begin())->getParent();
739
740 CallInst *FSqrt = cast<CallInst>(X->getOperand(1));
741 if (!FSqrt->hasAllowReassoc() || !FSqrt->hasNoNaNs() ||
742 !FSqrt->hasNoSignedZeros() || !FSqrt->hasNoInfs())
743 return false;
744
745 // We change x = 1/sqrt(a) to x = sqrt(a) * 1/a . This change isn't allowed
746 // by recip fp as it is strictly meant to transform ops of type a/b to
747 // a * 1/b. So, this can be considered as algebraic rewrite and reassoc flag
748 // has been used(rather abused)in the past for algebraic rewrites.
749 if (!X->hasAllowReassoc() || !X->hasAllowReciprocal() || !X->hasNoInfs())
750 return false;
751
752 // Check the constraints on X, R1 and R2 combined.
753 // fdiv instruction and one of the multiplications must reside in the same
754 // block. If not, the optimized code may execute more ops than before and
755 // this may hamper the performance.
756 if (BBx != BBr1 && BBx != BBr2)
757 return false;
758
759 // Check the constraints on instructions in R1.
760 if (any_of(R1, [BBr1](Instruction *I) {
761 // When you have multiple instructions residing in R1 and R2
762 // respectively, it's difficult to generate combinations of (R1,R2) and
763 // then check if we have the required pattern. So, for now, just be
764 // conservative.
765 return (I->getParent() != BBr1 || !I->hasAllowReassoc());
766 }))
767 return false;
768
769 // Check the constraints on instructions in R2.
770 return all_of(R2, [BBr2](Instruction *I) {
771 // When you have multiple instructions residing in R1 and R2
772 // respectively, it's difficult to generate combination of (R1,R2) and
773 // then check if we have the required pattern. So, for now, just be
774 // conservative.
775 return (I->getParent() == BBr2 && I->hasAllowReassoc());
776 });
777}
778
780 Value *Op0 = I.getOperand(0);
781 Value *Op1 = I.getOperand(1);
782 Value *X, *Y;
783 Constant *C;
784 BinaryOperator *Op0BinOp;
785
786 // Reassociate constant RHS with another constant to form constant
787 // expression.
788 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
789 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
790 // Everything in this scope folds I with Op0, intersecting their FMF.
791 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
792 Constant *C1;
793 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
794 // (C1 / X) * C --> (C * C1) / X
795 Constant *CC1 =
796 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
797 if (CC1 && CC1->isNormalFP())
798 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
799 }
800 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
801 // FIXME: This seems like it should also be checking for arcp
802 // (X / C1) * C --> X * (C / C1)
803 Constant *CDivC1 =
804 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
805 if (CDivC1 && CDivC1->isNormalFP())
806 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
807
808 // If the constant was a denormal, try reassociating differently.
809 // (X / C1) * C --> X / (C1 / C)
810 Constant *C1DivC =
811 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
812 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
813 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
814 }
815
816 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
817 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
818 // further folds and (X * C) + C2 is 'fma'.
819 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
820 // (X + C1) * C --> (X * C) + (C * C1)
821 if (Constant *CC1 =
822 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
823 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
824 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
825 }
826 }
827 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
828 // (C1 - X) * C --> (C * C1) - (X * C)
829 if (Constant *CC1 =
830 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
831 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
832 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
833 }
834 }
835 }
836
837 Value *Z;
838 if (match(&I,
840 m_Value(Z)))) {
841 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
842 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
843 if (FMF.allowReassoc()) {
844 // Sink division: (X / Y) * Z --> (X * Z) / Y
845 auto *NewFMul = Builder.CreateFMulFMF(X, Z, FMF);
846 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
847 }
848 }
849
850 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
851 // nnan disallows the possibility of returning a number if both operands are
852 // negative (in that case, we should return NaN).
853 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
854 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
855 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
856 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
857 return replaceInstUsesWith(I, Sqrt);
858 }
859
860 // The following transforms are done irrespective of the number of uses
861 // for the expression "1.0/sqrt(X)".
862 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
863 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
864 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
865 // has the necessary (reassoc) fast-math-flags.
866 if (I.hasNoSignedZeros() &&
867 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
868 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
870 if (I.hasNoSignedZeros() &&
871 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
872 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
874
875 // Like the similar transform in instsimplify, this requires 'nsz' because
876 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
877 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
878 // Peek through fdiv to find squaring of square root:
879 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
880 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
881 Value *XX = Builder.CreateFMulFMF(X, X, &I);
882 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
883 }
884 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
885 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
886 Value *XX = Builder.CreateFMulFMF(X, X, &I);
887 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
888 }
889 }
890
891 // pow(X, Y) * X --> pow(X, Y+1)
892 // X * pow(X, Y) --> pow(X, Y+1)
894 m_Value(Y))),
895 m_Deferred(X)))) {
896 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
897 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
898 return replaceInstUsesWith(I, Pow);
899 }
900
901 if (Instruction *FoldedPowi = foldPowiReassoc(I))
902 return FoldedPowi;
903
904 if (I.isOnlyUserOfAnyOperand()) {
905 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
908 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
909 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
910 return replaceInstUsesWith(I, NewPow);
911 }
912 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
915 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
916 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
917 return replaceInstUsesWith(I, NewPow);
918 }
919
920 // exp(X) * exp(Y) -> exp(X + Y)
923 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
924 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
925 return replaceInstUsesWith(I, Exp);
926 }
927
928 // exp2(X) * exp2(Y) -> exp2(X + Y)
931 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
932 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
933 return replaceInstUsesWith(I, Exp2);
934 }
935 }
936
937 // (X*Y) * X => (X*X) * Y where Y != X
938 // The purpose is two-fold:
939 // 1) to form a power expression (of X).
940 // 2) potentially shorten the critical path: After transformation, the
941 // latency of the instruction Y is amortized by the expression of X*X,
942 // and therefore Y is in a "less critical" position compared to what it
943 // was before the transformation.
944 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
945 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
946 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
947 }
948 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
949 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
950 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
951 }
952
953 return nullptr;
954}
955
957 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
958 I.getFastMathFlags(),
959 SQ.getWithInstruction(&I)))
960 return replaceInstUsesWith(I, V);
961
963 return &I;
964
966 return X;
967
969 return Phi;
970
971 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
972 return FoldedMul;
973
974 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
975 return replaceInstUsesWith(I, FoldedMul);
976
977 if (Instruction *R = foldFPSignBitOps(I))
978 return R;
979
980 if (Instruction *R = foldFBinOpOfIntCasts(I))
981 return R;
982
983 // X * -1.0 --> -X
984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
985 if (match(Op1, m_SpecificFP(-1.0)))
986 return UnaryOperator::CreateFNegFMF(Op0, &I);
987
988 // With no-nans/no-infs:
989 // X * 0.0 --> copysign(0.0, X)
990 // X * -0.0 --> copysign(0.0, -X)
991 const APFloat *FPC;
992 if (match(Op1, m_APFloatAllowPoison(FPC)) && FPC->isZero() &&
993 ((I.hasNoInfs() && isKnownNeverNaN(Op0, SQ.getWithInstruction(&I))) ||
994 isKnownNeverNaN(&I, SQ.getWithInstruction(&I)))) {
995 if (FPC->isNegative())
996 Op0 = Builder.CreateFNegFMF(Op0, &I);
997 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
998 {I.getType()}, {Op1, Op0}, &I);
999 return replaceInstUsesWith(I, CopySign);
1000 }
1001
1002 // -X * C --> X * -C
1003 Value *X, *Y;
1004 Constant *C;
1005 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
1006 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1007 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
1008
1009 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
1010 // (uitofp bool X) * Y --> X ? Y : 0
1011 // Y * (uitofp bool X) --> X ? Y : 0
1012 // Note INF * 0 is NaN.
1013 if (match(Op0, m_UIToFP(m_Value(X))) &&
1014 X->getType()->isIntOrIntVectorTy(1)) {
1015 auto *SI = SelectInst::Create(X, Op1, ConstantFP::get(I.getType(), 0.0));
1016 SI->copyFastMathFlags(I.getFastMathFlags());
1017 return SI;
1018 }
1019 if (match(Op1, m_UIToFP(m_Value(X))) &&
1020 X->getType()->isIntOrIntVectorTy(1)) {
1021 auto *SI = SelectInst::Create(X, Op0, ConstantFP::get(I.getType(), 0.0));
1022 SI->copyFastMathFlags(I.getFastMathFlags());
1023 return SI;
1024 }
1025 }
1026
1027 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
1028 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1029 return replaceInstUsesWith(I, V);
1030
1031 if (I.hasAllowReassoc())
1032 if (Instruction *FoldedMul = foldFMulReassoc(I))
1033 return FoldedMul;
1034
1035 // log2(X * 0.5) * Y = log2(X) * Y - Y
1036 if (I.isFast()) {
1037 IntrinsicInst *Log2 = nullptr;
1039 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1041 Y = Op1;
1042 }
1044 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1046 Y = Op0;
1047 }
1048 if (Log2) {
1049 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
1050 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
1051 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
1052 }
1053 }
1054
1055 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
1056 // Given a phi node with entry value as 0 and it used in fmul operation,
1057 // we can replace fmul with 0 safely and eleminate loop operation.
1058 PHINode *PN = nullptr;
1059 Value *Start = nullptr, *Step = nullptr;
1060 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
1061 I.hasNoSignedZeros() && match(Start, m_Zero()))
1062 return replaceInstUsesWith(I, Start);
1063
1064 // minimum(X, Y) * maximum(X, Y) => X * Y.
1065 if (match(&I,
1068 m_Deferred(Y))))) {
1070 // We cannot preserve ninf if nnan flag is not set.
1071 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
1072 // while in optimized version NaN * Inf and this is a poison with ninf flag.
1073 if (!Result->hasNoNaNs())
1074 Result->setHasNoInfs(false);
1075 return Result;
1076 }
1077
1078 // tan(X) * cos(X) -> sin(X)
1079 if (I.hasAllowContract() &&
1080 match(&I,
1083 auto *Sin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, &I);
1084 if (auto *Metadata = I.getMetadata(LLVMContext::MD_fpmath)) {
1085 Sin->setMetadata(LLVMContext::MD_fpmath, Metadata);
1086 }
1087 return replaceInstUsesWith(I, Sin);
1088 }
1089
1090 return nullptr;
1091}
1092
1093/// Fold a divide or remainder with a select instruction divisor when one of the
1094/// select operands is zero. In that case, we can use the other select operand
1095/// because div/rem by zero is undefined.
1097 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
1098 if (!SI)
1099 return false;
1100
1101 int NonNullOperand;
1102 if (match(SI->getTrueValue(), m_Zero()))
1103 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1104 NonNullOperand = 2;
1105 else if (match(SI->getFalseValue(), m_Zero()))
1106 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1107 NonNullOperand = 1;
1108 else
1109 return false;
1110
1111 // Change the div/rem to use 'Y' instead of the select.
1112 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
1113
1114 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1115 // problem. However, the select, or the condition of the select may have
1116 // multiple uses. Based on our knowledge that the operand must be non-zero,
1117 // propagate the known value for the select into other uses of it, and
1118 // propagate a known value of the condition into its other users.
1119
1120 // If the select and condition only have a single use, don't bother with this,
1121 // early exit.
1122 Value *SelectCond = SI->getCondition();
1123 if (SI->use_empty() && SelectCond->hasOneUse())
1124 return true;
1125
1126 // Scan the current block backward, looking for other uses of SI.
1127 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
1128 Type *CondTy = SelectCond->getType();
1129 while (BBI != BBFront) {
1130 --BBI;
1131 // If we found an instruction that we can't assume will return, so
1132 // information from below it cannot be propagated above it.
1134 break;
1135
1136 // Replace uses of the select or its condition with the known values.
1137 for (Use &Op : BBI->operands()) {
1138 if (Op == SI) {
1139 replaceUse(Op, SI->getOperand(NonNullOperand));
1140 Worklist.push(&*BBI);
1141 } else if (Op == SelectCond) {
1142 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
1143 : ConstantInt::getFalse(CondTy));
1144 Worklist.push(&*BBI);
1145 }
1146 }
1147
1148 // If we past the instruction, quit looking for it.
1149 if (&*BBI == SI)
1150 SI = nullptr;
1151 if (&*BBI == SelectCond)
1152 SelectCond = nullptr;
1153
1154 // If we ran out of things to eliminate, break out of the loop.
1155 if (!SelectCond && !SI)
1156 break;
1157
1158 }
1159 return true;
1160}
1161
1162/// True if the multiply can not be expressed in an int this size.
1163static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1164 bool IsSigned) {
1165 bool Overflow;
1166 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
1167 return Overflow;
1168}
1169
1170/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1171static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1172 bool IsSigned) {
1173 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1174
1175 // Bail if we will divide by zero.
1176 if (C2.isZero())
1177 return false;
1178
1179 // Bail if we would divide INT_MIN by -1.
1180 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1181 return false;
1182
1183 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1184 if (IsSigned)
1185 APInt::sdivrem(C1, C2, Quotient, Remainder);
1186 else
1187 APInt::udivrem(C1, C2, Quotient, Remainder);
1188
1189 return Remainder.isMinValue();
1190}
1191
1193 assert((I.getOpcode() == Instruction::SDiv ||
1194 I.getOpcode() == Instruction::UDiv) &&
1195 "Expected integer divide");
1196
1197 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1198 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1199 Type *Ty = I.getType();
1200
1201 Value *X, *Y, *Z;
1202
1203 // With appropriate no-wrap constraints, remove a common factor in the
1204 // dividend and divisor that is disguised as a left-shifted value.
1205 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1206 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1207 // Both operands must have the matching no-wrap for this kind of division.
1209 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1210 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1211 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1212
1213 // (X * Y) u/ (X << Z) --> Y u>> Z
1214 if (!IsSigned && HasNUW)
1215 return Builder.CreateLShr(Y, Z, "", I.isExact());
1216
1217 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1218 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1219 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1220 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1221 }
1222 }
1223
1224 // With appropriate no-wrap constraints, remove a common factor in the
1225 // dividend and divisor that is disguised as a left-shift amount.
1226 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1227 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1228 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1229 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1230
1231 // For unsigned div, we need 'nuw' on both shifts or
1232 // 'nsw' on both shifts + 'nuw' on the dividend.
1233 // (X << Z) / (Y << Z) --> X / Y
1234 if (!IsSigned &&
1235 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1236 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1237 Shl1->hasNoSignedWrap())))
1238 return Builder.CreateUDiv(X, Y, "", I.isExact());
1239
1240 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1241 // (X << Z) / (Y << Z) --> X / Y
1242 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1243 Shl1->hasNoUnsignedWrap())
1244 return Builder.CreateSDiv(X, Y, "", I.isExact());
1245 }
1246
1247 // If X << Y and X << Z does not overflow, then:
1248 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1249 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1250 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1251 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1252 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1253
1254 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1255 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1256 Constant *One = ConstantInt::get(X->getType(), 1);
1257 // Only preserve the nsw flag if dividend has nsw
1258 // or divisor has nsw and operator is sdiv.
1259 Value *Dividend = Builder.CreateShl(
1260 One, Y, "shl.dividend",
1261 /*HasNUW=*/true,
1262 /*HasNSW=*/
1263 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1264 : Shl0->hasNoSignedWrap());
1265 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1266 }
1267 }
1268
1269 return nullptr;
1270}
1271
1272/// Common integer divide/remainder transforms
1274 assert(I.isIntDivRem() && "Unexpected instruction");
1275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1276
1277 // If any element of a constant divisor fixed width vector is zero or undef
1278 // the behavior is undefined and we can fold the whole op to poison.
1279 auto *Op1C = dyn_cast<Constant>(Op1);
1280 Type *Ty = I.getType();
1281 auto *VTy = dyn_cast<FixedVectorType>(Ty);
1282 if (Op1C && VTy) {
1283 unsigned NumElts = VTy->getNumElements();
1284 for (unsigned i = 0; i != NumElts; ++i) {
1285 Constant *Elt = Op1C->getAggregateElement(i);
1286 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
1288 }
1289 }
1290
1292 return Phi;
1293
1294 // The RHS is known non-zero.
1295 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1296 return replaceOperand(I, 1, V);
1297
1298 // Handle cases involving: div/rem X, (select Cond, Y, Z)
1300 return &I;
1301
1302 // If the divisor is a select-of-constants, try to constant fold all div ops:
1303 // C div/rem (select Cond, TrueC, FalseC) --> select Cond, (C div/rem TrueC),
1304 // (C div/rem FalseC)
1305 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1306 if (match(Op0, m_ImmConstant()) &&
1309 /*FoldWithMultiUse*/ true))
1310 return R;
1311 }
1312
1313 return nullptr;
1314}
1315
1316/// This function implements the transforms common to both integer division
1317/// instructions (udiv and sdiv). It is called by the visitors to those integer
1318/// division instructions.
1319/// Common integer divide transforms
1322 return Res;
1323
1324 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1325 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1326 Type *Ty = I.getType();
1327
1328 const APInt *C2;
1329 if (match(Op1, m_APInt(C2))) {
1330 Value *X;
1331 const APInt *C1;
1332
1333 // (X / C1) / C2 -> X / (C1*C2)
1334 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1335 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1336 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1337 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1338 return BinaryOperator::Create(I.getOpcode(), X,
1339 ConstantInt::get(Ty, Product));
1340 }
1341
1342 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1343 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1344 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1345
1346 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1347 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1348 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1349 ConstantInt::get(Ty, Quotient));
1350 NewDiv->setIsExact(I.isExact());
1351 return NewDiv;
1352 }
1353
1354 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1355 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1356 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1357 ConstantInt::get(Ty, Quotient));
1358 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1359 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1360 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1361 return Mul;
1362 }
1363 }
1364
1365 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1366 C1->ult(C1->getBitWidth() - 1)) ||
1367 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1368 C1->ult(C1->getBitWidth()))) {
1369 APInt C1Shifted = APInt::getOneBitSet(
1370 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1371
1372 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1373 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1374 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1375 ConstantInt::get(Ty, Quotient));
1376 BO->setIsExact(I.isExact());
1377 return BO;
1378 }
1379
1380 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1381 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1382 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1383 ConstantInt::get(Ty, Quotient));
1384 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1385 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1386 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1387 return Mul;
1388 }
1389 }
1390
1391 // Distribute div over add to eliminate a matching div/mul pair:
1392 // ((X * C2) + C1) / C2 --> X + C1/C2
1393 // We need a multiple of the divisor for a signed add constant, but
1394 // unsigned is fine with any constant pair.
1395 if (IsSigned &&
1397 m_APInt(C1))) &&
1398 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1399 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1400 }
1401 if (!IsSigned &&
1403 m_APInt(C1)))) {
1404 return BinaryOperator::CreateNUWAdd(X,
1405 ConstantInt::get(Ty, C1->udiv(*C2)));
1406 }
1407
1408 if (!C2->isZero()) // avoid X udiv 0
1409 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1410 return FoldedDiv;
1411 }
1412
1413 if (match(Op0, m_One())) {
1414 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1415 if (IsSigned) {
1416 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1417 // (Op1 + 1) u< 3 ? Op1 : 0
1418 // Op1 must be frozen because we are increasing its number of uses.
1419 Value *F1 = Op1;
1420 if (!isGuaranteedNotToBeUndef(Op1))
1421 F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1422 Value *Inc = Builder.CreateAdd(F1, Op0);
1423 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1424 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1425 } else {
1426 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1427 // result is one, otherwise it's zero.
1428 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1429 }
1430 }
1431
1432 // See if we can fold away this div instruction.
1434 return &I;
1435
1436 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1437 Value *X, *Z;
1438 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1439 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1440 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1441 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1442
1443 // (X << Y) / X -> 1 << Y
1444 Value *Y;
1445 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1446 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1447 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1448 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1449
1450 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1451 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1452 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1453 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1454 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1455 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1456 replaceOperand(I, 1, Y);
1457 return &I;
1458 }
1459 }
1460
1461 // (X << Z) / (X * Y) -> (1 << Z) / Y
1462 // TODO: Handle sdiv.
1463 if (!IsSigned && Op1->hasOneUse() &&
1464 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1465 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1467 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1468 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1469 NewDiv->setIsExact(I.isExact());
1470 return NewDiv;
1471 }
1472
1473 if (Value *R = foldIDivShl(I, Builder))
1474 return replaceInstUsesWith(I, R);
1475
1476 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1477 // after peeking through another divide:
1478 // ((Op1 * X) / Y) / Op1 --> X / Y
1479 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1480 m_Value(Y)))) {
1481 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1482 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1483 Instruction *NewDiv = nullptr;
1484 if (!IsSigned && Mul->hasNoUnsignedWrap())
1485 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1486 else if (IsSigned && Mul->hasNoSignedWrap())
1487 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1488
1489 // Exact propagates only if both of the original divides are exact.
1490 if (NewDiv) {
1491 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1492 return NewDiv;
1493 }
1494 }
1495
1496 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1497 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1498 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1499 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1500
1501 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1502 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1503 auto OB1HasNUW =
1504 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1505 const APInt *C1, *C2;
1506 if (IsSigned && OB0HasNSW) {
1507 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1508 return BinaryOperator::CreateSDiv(A, B);
1509 }
1510 if (!IsSigned && OB0HasNUW) {
1511 if (OB1HasNUW)
1512 return BinaryOperator::CreateUDiv(A, B);
1513 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1514 return BinaryOperator::CreateUDiv(A, B);
1515 }
1516 return nullptr;
1517 };
1518
1519 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1520 if (auto *Val = CreateDivOrNull(Y, Z))
1521 return Val;
1522 }
1523 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1524 if (auto *Val = CreateDivOrNull(X, Z))
1525 return Val;
1526 }
1527 }
1528 return nullptr;
1529}
1530
1531Value *InstCombinerImpl::takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero,
1532 bool DoFold) {
1533 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1534 if (!DoFold)
1535 return reinterpret_cast<Value *>(-1);
1536 return Fn();
1537 };
1538
1539 // FIXME: assert that Op1 isn't/doesn't contain undef.
1540
1541 // log2(2^C) -> C
1542 if (match(Op, m_Power2()))
1543 return IfFold([&]() {
1545 if (!C)
1546 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1547 return C;
1548 });
1549
1550 // The remaining tests are all recursive, so bail out if we hit the limit.
1552 return nullptr;
1553
1554 // log2(zext X) -> zext log2(X)
1555 // FIXME: Require one use?
1556 Value *X, *Y;
1557 if (match(Op, m_ZExt(m_Value(X))))
1558 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1559 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1560
1561 // log2(trunc x) -> trunc log2(X)
1562 // FIXME: Require one use?
1563 if (match(Op, m_Trunc(m_Value(X)))) {
1564 auto *TI = cast<TruncInst>(Op);
1565 if (AssumeNonZero || TI->hasNoUnsignedWrap())
1566 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1567 return IfFold([&]() {
1568 return Builder.CreateTrunc(LogX, Op->getType(), "",
1569 /*IsNUW=*/TI->hasNoUnsignedWrap());
1570 });
1571 }
1572
1573 // log2(X << Y) -> log2(X) + Y
1574 // FIXME: Require one use unless X is 1?
1575 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1577 // nuw will be set if the `shl` is trivially non-zero.
1578 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1579 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1580 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1581 }
1582
1583 // log2(X >>u Y) -> log2(X) - Y
1584 // FIXME: Require one use?
1585 if (match(Op, m_LShr(m_Value(X), m_Value(Y)))) {
1586 auto *PEO = cast<PossiblyExactOperator>(Op);
1587 if (AssumeNonZero || PEO->isExact())
1588 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1589 return IfFold([&]() { return Builder.CreateSub(LogX, Y); });
1590 }
1591
1592 // log2(X & Y) -> either log2(X) or log2(Y)
1593 // This requires `AssumeNonZero` as `X & Y` may be zero when X != Y.
1594 if (AssumeNonZero && match(Op, m_And(m_Value(X), m_Value(Y)))) {
1595 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1596 return IfFold([&]() { return LogX; });
1597 if (Value *LogY = takeLog2(Y, Depth, AssumeNonZero, DoFold))
1598 return IfFold([&]() { return LogY; });
1599 }
1600
1601 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1602 // FIXME: Require one use?
1604 if (Value *LogX = takeLog2(SI->getOperand(1), Depth, AssumeNonZero, DoFold))
1605 if (Value *LogY =
1606 takeLog2(SI->getOperand(2), Depth, AssumeNonZero, DoFold))
1607 return IfFold([&]() {
1608 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1609 });
1610
1611 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1612 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1614 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1615 // Use AssumeNonZero as false here. Otherwise we can hit case where
1616 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1617 if (Value *LogX = takeLog2(MinMax->getLHS(), Depth,
1618 /*AssumeNonZero*/ false, DoFold))
1619 if (Value *LogY = takeLog2(MinMax->getRHS(), Depth,
1620 /*AssumeNonZero*/ false, DoFold))
1621 return IfFold([&]() {
1622 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1623 LogY);
1624 });
1625 }
1626
1627 return nullptr;
1628}
1629
1630/// If we have zero-extended operands of an unsigned div or rem, we may be able
1631/// to narrow the operation (sink the zext below the math).
1633 InstCombinerImpl &IC) {
1634 Instruction::BinaryOps Opcode = I.getOpcode();
1635 Value *N = I.getOperand(0);
1636 Value *D = I.getOperand(1);
1637 Type *Ty = I.getType();
1638 Value *X, *Y;
1639 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1640 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1641 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1642 // urem (zext X), (zext Y) --> zext (urem X, Y)
1643 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1644 return new ZExtInst(NarrowOp, Ty);
1645 }
1646
1647 Constant *C;
1648 auto &DL = IC.getDataLayout();
1650 match(D, m_Constant(C))) {
1651 // If the constant is the same in the smaller type, use the narrow version.
1652 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1653 if (!TruncC)
1654 return nullptr;
1655
1656 // udiv (zext X), C --> zext (udiv X, C')
1657 // urem (zext X), C --> zext (urem X, C')
1658 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1659 }
1661 match(N, m_Constant(C))) {
1662 // If the constant is the same in the smaller type, use the narrow version.
1663 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1664 if (!TruncC)
1665 return nullptr;
1666
1667 // udiv C, (zext X) --> zext (udiv C', X)
1668 // urem C, (zext X) --> zext (urem C', X)
1669 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1670 }
1671
1672 return nullptr;
1673}
1674
1676 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1677 SQ.getWithInstruction(&I)))
1678 return replaceInstUsesWith(I, V);
1679
1681 return X;
1682
1683 // Handle the integer div common cases
1684 if (Instruction *Common = commonIDivTransforms(I))
1685 return Common;
1686
1687 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1688 Value *X;
1689 const APInt *C1, *C2;
1690 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1691 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1692 bool Overflow;
1693 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1694 if (!Overflow) {
1695 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1696 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1697 X, ConstantInt::get(X->getType(), C2ShlC1));
1698 if (IsExact)
1699 BO->setIsExact();
1700 return BO;
1701 }
1702 }
1703
1704 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1705 // TODO: Could use isKnownNegative() to handle non-constant values.
1706 Type *Ty = I.getType();
1707 if (match(Op1, m_Negative())) {
1708 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1709 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1710 }
1711 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1712 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1713 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1714 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1715 }
1716
1717 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1718 return NarrowDiv;
1719
1720 Value *A, *B;
1721
1722 // Look through a right-shift to find the common factor:
1723 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1724 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1725 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1726 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1727 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1728 Lshr->setIsExact();
1729 return Lshr;
1730 }
1731
1732 auto GetShiftableDenom = [&](Value *Denom) -> Value * {
1733 // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
1734 if (Value *Log2 = tryGetLog2(Op1, /*AssumeNonZero=*/true))
1735 return Log2;
1736
1737 // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
1738 if (isKnownToBeAPowerOfTwo(Denom, /*OrZero=*/true, &I))
1739 // This will increase instruction count but it's okay
1740 // since bitwise operations are substantially faster than
1741 // division.
1742 return Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Denom,
1743 Builder.getTrue());
1744
1745 return nullptr;
1746 };
1747
1748 if (auto *Res = GetShiftableDenom(Op1))
1749 return replaceInstUsesWith(
1750 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1751
1752 return nullptr;
1753}
1754
1756 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1757 SQ.getWithInstruction(&I)))
1758 return replaceInstUsesWith(I, V);
1759
1761 return X;
1762
1763 // Handle the integer div common cases
1764 if (Instruction *Common = commonIDivTransforms(I))
1765 return Common;
1766
1767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1768 Type *Ty = I.getType();
1769 Value *X;
1770 // sdiv Op0, -1 --> -Op0
1771 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1772 if (match(Op1, m_AllOnes()) ||
1773 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1774 return BinaryOperator::CreateNSWNeg(Op0);
1775
1776 // X / INT_MIN --> X == INT_MIN
1777 if (match(Op1, m_SignMask()))
1778 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1779
1780 if (I.isExact()) {
1781 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1782 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1784 return BinaryOperator::CreateExactAShr(Op0, C);
1785 }
1786
1787 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1788 Value *ShAmt;
1789 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1790 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1791
1792 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1793 if (match(Op1, m_NegatedPower2())) {
1796 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1797 return BinaryOperator::CreateNSWNeg(Ashr);
1798 }
1799 }
1800
1801 const APInt *Op1C;
1802 if (match(Op1, m_APInt(Op1C))) {
1803 // If the dividend is sign-extended and the constant divisor is small enough
1804 // to fit in the source type, shrink the division to the narrower type:
1805 // (sext X) sdiv C --> sext (X sdiv C)
1806 Value *Op0Src;
1807 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1808 Op0Src->getType()->getScalarSizeInBits() >=
1809 Op1C->getSignificantBits()) {
1810
1811 // In the general case, we need to make sure that the dividend is not the
1812 // minimum signed value because dividing that by -1 is UB. But here, we
1813 // know that the -1 divisor case is already handled above.
1814
1815 Constant *NarrowDivisor =
1817 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1818 return new SExtInst(NarrowOp, Ty);
1819 }
1820
1821 // -X / C --> X / -C (if the negation doesn't overflow).
1822 // TODO: This could be enhanced to handle arbitrary vector constants by
1823 // checking if all elements are not the min-signed-val.
1824 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
1825 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1826 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1827 BO->setIsExact(I.isExact());
1828 return BO;
1829 }
1830 }
1831
1832 // -X / Y --> -(X / Y)
1833 Value *Y;
1836 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1837
1838 // abs(X) / X --> X > -1 ? 1 : -1
1839 // X / abs(X) --> X > -1 ? 1 : -1
1840 if (match(&I, m_c_BinOp(
1842 m_Deferred(X)))) {
1843 Value *Cond = Builder.CreateIsNotNeg(X);
1844 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1846 }
1847
1848 KnownBits KnownDividend = computeKnownBits(Op0, &I);
1849 if (!I.isExact() &&
1850 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1851 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1852 I.setIsExact();
1853 return &I;
1854 }
1855
1856 if (KnownDividend.isNonNegative()) {
1857 // If both operands are unsigned, turn this into a udiv.
1858 if (isKnownNonNegative(Op1, SQ.getWithInstruction(&I))) {
1859 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1860 BO->setIsExact(I.isExact());
1861 return BO;
1862 }
1863
1864 if (match(Op1, m_NegatedPower2())) {
1865 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1866 // -> -(X udiv (1 << C)) -> -(X u>> C)
1869 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1870 return BinaryOperator::CreateNeg(Shr);
1871 }
1872
1873 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
1874 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1875 // Safe because the only negative value (1 << Y) can take on is
1876 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1877 // the sign bit set.
1878 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1879 BO->setIsExact(I.isExact());
1880 return BO;
1881 }
1882 }
1883
1884 // -X / X --> X == INT_MIN ? 1 : -1
1885 if (isKnownNegation(Op0, Op1)) {
1886 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1887 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1888 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1890 }
1891 return nullptr;
1892}
1893
1894/// Remove negation and try to convert division into multiplication.
1895Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1896 Constant *C;
1897 if (!match(I.getOperand(1), m_Constant(C)))
1898 return nullptr;
1899
1900 // -X / C --> X / -C
1901 Value *X;
1902 const DataLayout &DL = I.getDataLayout();
1903 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1904 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1905 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1906
1907 // nnan X / +0.0 -> copysign(inf, X)
1908 // nnan nsz X / -0.0 -> copysign(inf, X)
1909 if (I.hasNoNaNs() &&
1910 (match(I.getOperand(1), m_PosZeroFP()) ||
1911 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1912 IRBuilder<> B(&I);
1913 CallInst *CopySign = B.CreateIntrinsic(
1914 Intrinsic::copysign, {C->getType()},
1915 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1916 CopySign->takeName(&I);
1917 return replaceInstUsesWith(I, CopySign);
1918 }
1919
1920 // If the constant divisor has an exact inverse, this is always safe. If not,
1921 // then we can still create a reciprocal if fast-math-flags allow it and the
1922 // constant is a regular number (not zero, infinite, or denormal).
1923 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1924 return nullptr;
1925
1926 // Disallow denormal constants because we don't know what would happen
1927 // on all targets.
1928 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1929 // denorms are flushed?
1930 auto *RecipC = ConstantFoldBinaryOpOperands(
1931 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1932 if (!RecipC || !RecipC->isNormalFP())
1933 return nullptr;
1934
1935 // X / C --> X * (1 / C)
1936 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1937}
1938
1939/// Remove negation and try to reassociate constant math.
1941 Constant *C;
1942 if (!match(I.getOperand(0), m_Constant(C)))
1943 return nullptr;
1944
1945 // C / -X --> -C / X
1946 Value *X;
1947 const DataLayout &DL = I.getDataLayout();
1948 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1949 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1950 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1951
1952 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1953 return nullptr;
1954
1955 // Try to reassociate C / X expressions where X includes another constant.
1956 Constant *C2, *NewC = nullptr;
1957 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1958 // C / (X * C2) --> (C / C2) / X
1959 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1960 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1961 // C / (X / C2) --> (C * C2) / X
1962 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1963 }
1964 // Disallow denormal constants because we don't know what would happen
1965 // on all targets.
1966 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1967 // denorms are flushed?
1968 if (!NewC || !NewC->isNormalFP())
1969 return nullptr;
1970
1971 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1972}
1973
1974/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1976 InstCombiner::BuilderTy &Builder) {
1977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1978 auto *II = dyn_cast<IntrinsicInst>(Op1);
1979 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1980 !I.hasAllowReciprocal())
1981 return nullptr;
1982
1983 // Z / pow(X, Y) --> Z * pow(X, -Y)
1984 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1985 // In the general case, this creates an extra instruction, but fmul allows
1986 // for better canonicalization and optimization than fdiv.
1987 Intrinsic::ID IID = II->getIntrinsicID();
1989 switch (IID) {
1990 case Intrinsic::pow:
1991 Args.push_back(II->getArgOperand(0));
1992 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1993 break;
1994 case Intrinsic::powi: {
1995 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1996 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1997 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1998 // non-standard results, so this corner case should be acceptable if the
1999 // code rules out INF values.
2000 if (!I.hasNoInfs())
2001 return nullptr;
2002 Args.push_back(II->getArgOperand(0));
2003 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
2004 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
2005 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
2006 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2007 }
2008 case Intrinsic::exp:
2009 case Intrinsic::exp2:
2010 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
2011 break;
2012 default:
2013 return nullptr;
2014 }
2015 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
2016 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2017}
2018
2019/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
2020/// instruction.
2022 InstCombiner::BuilderTy &Builder) {
2023 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
2024 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2025 return nullptr;
2026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2027 auto *II = dyn_cast<IntrinsicInst>(Op1);
2028 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
2029 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
2030 return nullptr;
2031
2032 Value *Y, *Z;
2033 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
2034 if (!DivOp)
2035 return nullptr;
2036 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
2037 return nullptr;
2038 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
2039 !DivOp->hasOneUse())
2040 return nullptr;
2041 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
2042 Value *NewSqrt =
2043 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
2044 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
2045}
2046
2047// Change
2048// X = 1/sqrt(a)
2049// R1 = X * X
2050// R2 = a * X
2051//
2052// TO
2053//
2054// FDiv = 1/a
2055// FSqrt = sqrt(a)
2056// FMul = FDiv * FSqrt
2057// Replace Uses Of R1 With FDiv
2058// Replace Uses Of R2 With FSqrt
2059// Replace Uses Of X With FMul
2060static Instruction *
2065
2066 B.SetInsertPoint(X);
2067
2068 // Have an instruction that is representative of all of instructions in R1 and
2069 // get the most common fpmath metadata and fast-math flags on it.
2070 Value *SqrtOp = CI->getArgOperand(0);
2071 auto *FDiv = cast<Instruction>(
2072 B.CreateFDiv(ConstantFP::get(X->getType(), 1.0), SqrtOp));
2073 auto *R1FPMathMDNode = (*R1.begin())->getMetadata(LLVMContext::MD_fpmath);
2074 FastMathFlags R1FMF = (*R1.begin())->getFastMathFlags(); // Common FMF
2075 for (Instruction *I : R1) {
2076 R1FPMathMDNode = MDNode::getMostGenericFPMath(
2077 R1FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2078 R1FMF &= I->getFastMathFlags();
2079 IC->replaceInstUsesWith(*I, FDiv);
2081 }
2082 FDiv->setMetadata(LLVMContext::MD_fpmath, R1FPMathMDNode);
2083 FDiv->copyFastMathFlags(R1FMF);
2084
2085 // Have a single sqrt call instruction that is representative of all of
2086 // instructions in R2 and get the most common fpmath metadata and fast-math
2087 // flags on it.
2088 auto *FSqrt = cast<CallInst>(CI->clone());
2089 FSqrt->insertBefore(CI->getIterator());
2090 auto *R2FPMathMDNode = (*R2.begin())->getMetadata(LLVMContext::MD_fpmath);
2091 FastMathFlags R2FMF = (*R2.begin())->getFastMathFlags(); // Common FMF
2092 for (Instruction *I : R2) {
2093 R2FPMathMDNode = MDNode::getMostGenericFPMath(
2094 R2FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2095 R2FMF &= I->getFastMathFlags();
2096 IC->replaceInstUsesWith(*I, FSqrt);
2098 }
2099 FSqrt->setMetadata(LLVMContext::MD_fpmath, R2FPMathMDNode);
2100 FSqrt->copyFastMathFlags(R2FMF);
2101
2103 // If X = -1/sqrt(a) initially,then FMul = -(FDiv * FSqrt)
2104 if (match(X, m_FDiv(m_SpecificFP(-1.0), m_Specific(CI)))) {
2105 Value *Mul = B.CreateFMul(FDiv, FSqrt);
2106 FMul = cast<Instruction>(B.CreateFNeg(Mul));
2107 } else
2108 FMul = cast<Instruction>(B.CreateFMul(FDiv, FSqrt));
2109 FMul->copyMetadata(*X);
2110 FMul->copyFastMathFlags(FastMathFlags::intersectRewrite(R1FMF, R2FMF) |
2111 FastMathFlags::unionValue(R1FMF, R2FMF));
2112 return IC->replaceInstUsesWith(*X, FMul);
2113}
2114
2116 Module *M = I.getModule();
2117
2118 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
2119 I.getFastMathFlags(),
2120 SQ.getWithInstruction(&I)))
2121 return replaceInstUsesWith(I, V);
2122
2124 return X;
2125
2127 return Phi;
2128
2129 if (Instruction *R = foldFDivConstantDivisor(I))
2130 return R;
2131
2133 return R;
2134
2135 if (Instruction *R = foldFPSignBitOps(I))
2136 return R;
2137
2138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2139
2140 // Convert
2141 // x = 1.0/sqrt(a)
2142 // r1 = x * x;
2143 // r2 = a/sqrt(a);
2144 //
2145 // TO
2146 //
2147 // r1 = 1/a
2148 // r2 = sqrt(a)
2149 // x = r1 * r2
2151 if (isFSqrtDivToFMulLegal(&I, R1, R2)) {
2152 CallInst *CI = cast<CallInst>(I.getOperand(1));
2153 if (Instruction *D = convertFSqrtDivIntoFMul(CI, &I, R1, R2, Builder, this))
2154 return D;
2155 }
2156
2157 if (isa<Constant>(Op0))
2159 if (Instruction *R = FoldOpIntoSelect(I, SI))
2160 return R;
2161
2162 if (isa<Constant>(Op1))
2164 if (Instruction *R = FoldOpIntoSelect(I, SI))
2165 return R;
2166
2167 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
2168 Value *X, *Y;
2169 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2170 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
2171 // (X / Y) / Z => X / (Y * Z)
2172 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
2173 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
2174 }
2175 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2176 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
2177 // Z / (X / Y) => (Y * Z) / X
2178 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
2179 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
2180 }
2181 // Z / (1.0 / Y) => (Y * Z)
2182 //
2183 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
2184 // m_OneUse check is avoided because even in the case of the multiple uses
2185 // for 1.0/Y, the number of instructions remain the same and a division is
2186 // replaced by a multiplication.
2187 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
2188 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
2189 }
2190
2191 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
2192 // sin(X) / cos(X) -> tan(X)
2193 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
2194 Value *X;
2195 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
2197 bool IsCot =
2198 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
2200
2201 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
2202 LibFunc_tanf, LibFunc_tanl)) {
2203 IRBuilder<> B(&I);
2205 B.setFastMathFlags(I.getFastMathFlags());
2206 AttributeList Attrs =
2207 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
2208 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
2209 LibFunc_tanl, B, Attrs);
2210 if (IsCot)
2211 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
2212 return replaceInstUsesWith(I, Res);
2213 }
2214 }
2215
2216 // X / (X * Y) --> 1.0 / Y
2217 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
2218 // We can ignore the possibility that X is infinity because INF/INF is NaN.
2219 Value *X, *Y;
2220 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
2221 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
2222 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
2223 replaceOperand(I, 1, Y);
2224 return &I;
2225 }
2226
2227 // X / fabs(X) -> copysign(1.0, X)
2228 // fabs(X) / X -> copysign(1.0, X)
2229 if (I.hasNoNaNs() && I.hasNoInfs() &&
2230 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
2231 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
2232 Value *V = Builder.CreateBinaryIntrinsic(
2233 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
2234 return replaceInstUsesWith(I, V);
2235 }
2236
2238 return Mul;
2239
2241 return Mul;
2242
2243 // pow(X, Y) / X --> pow(X, Y-1)
2244 if (I.hasAllowReassoc() &&
2246 m_Value(Y))))) {
2247 Value *Y1 =
2248 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
2249 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
2250 return replaceInstUsesWith(I, Pow);
2251 }
2252
2253 if (Instruction *FoldedPowi = foldPowiReassoc(I))
2254 return FoldedPowi;
2255
2256 return nullptr;
2257}
2258
2259// Variety of transform for:
2260// (urem/srem (mul X, Y), (mul X, Z))
2261// (urem/srem (shl X, Y), (shl X, Z))
2262// (urem/srem (shl Y, X), (shl Z, X))
2263// NB: The shift cases are really just extensions of the mul case. We treat
2264// shift as Val * (1 << Amt).
2266 InstCombinerImpl &IC) {
2267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
2268 APInt Y, Z;
2269 bool ShiftByX = false;
2270
2271 // If V is not nullptr, it will be matched using m_Specific.
2272 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C,
2273 bool &PreserveNSW) -> bool {
2274 const APInt *Tmp = nullptr;
2275 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
2276 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
2277 C = *Tmp;
2278 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
2279 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp))))) {
2280 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
2281 // We cannot preserve NSW when shifting by BW - 1.
2282 PreserveNSW = Tmp->ult(Tmp->getBitWidth() - 1);
2283 }
2284 if (Tmp != nullptr)
2285 return true;
2286
2287 // Reset `V` so we don't start with specific value on next match attempt.
2288 V = nullptr;
2289 return false;
2290 };
2291
2292 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
2293 const APInt *Tmp = nullptr;
2294 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
2295 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
2296 C = *Tmp;
2297 return true;
2298 }
2299
2300 // Reset `V` so we don't start with specific value on next match attempt.
2301 V = nullptr;
2302 return false;
2303 };
2304
2305 bool Op0PreserveNSW = true, Op1PreserveNSW = true;
2306 if (MatchShiftOrMulXC(Op0, X, Y, Op0PreserveNSW) &&
2307 MatchShiftOrMulXC(Op1, X, Z, Op1PreserveNSW)) {
2308 // pass
2309 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
2310 ShiftByX = true;
2311 } else {
2312 return nullptr;
2313 }
2314
2315 bool IsSRem = I.getOpcode() == Instruction::SRem;
2316
2318 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2319 // Z or Z >= Y.
2320 bool BO0HasNSW = Op0PreserveNSW && BO0->hasNoSignedWrap();
2321 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2322 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2323
2324 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
2325 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2326 // if (rem Y, Z) == 0
2327 // -> 0
2328 if (RemYZ.isZero() && BO0NoWrap)
2329 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
2330
2331 // Helper function to emit either (RemSimplificationC << X) or
2332 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2333 // (shl V, X) or (mul V, X) respectively.
2334 auto CreateMulOrShift =
2335 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2336 Value *RemSimplification =
2337 ConstantInt::get(I.getType(), RemSimplificationC);
2338 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2339 : BinaryOperator::CreateMul(X, RemSimplification);
2340 };
2341
2343 bool BO1HasNSW = Op1PreserveNSW && BO1->hasNoSignedWrap();
2344 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2345 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2346 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2347 // if (rem Y, Z) == Y
2348 // -> (mul nuw/nsw X, Y)
2349 if (RemYZ == Y && BO1NoWrap) {
2350 BinaryOperator *BO = CreateMulOrShift(Y);
2351 // Copy any overflow flags from Op0.
2352 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2353 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2354 return BO;
2355 }
2356
2357 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2358 // if Y >= Z
2359 // -> (mul {nuw} nsw X, (rem Y, Z))
2360 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2361 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2362 BO->setHasNoSignedWrap();
2363 BO->setHasNoUnsignedWrap(BO0HasNUW);
2364 return BO;
2365 }
2366
2367 return nullptr;
2368}
2369
2370/// This function implements the transforms common to both integer remainder
2371/// instructions (urem and srem). It is called by the visitors to those integer
2372/// remainder instructions.
2373/// Common integer remainder transforms
2376 return Res;
2377
2378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2379
2380 if (isa<Constant>(Op1)) {
2381 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2383 if (Instruction *R = FoldOpIntoSelect(I, SI))
2384 return R;
2385 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2386 const APInt *Op1Int;
2387 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2388 (I.getOpcode() == Instruction::URem ||
2389 !Op1Int->isMinSignedValue())) {
2390 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2391 // predecessor blocks, so do this only if we know the srem or urem
2392 // will not fault.
2393 if (Instruction *NV = foldOpIntoPhi(I, PN))
2394 return NV;
2395 }
2396 }
2397
2398 // See if we can fold away this rem instruction.
2400 return &I;
2401 }
2402 }
2403
2404 if (Instruction *R = simplifyIRemMulShl(I, *this))
2405 return R;
2406
2407 return nullptr;
2408}
2409
2411 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2412 SQ.getWithInstruction(&I)))
2413 return replaceInstUsesWith(I, V);
2414
2416 return X;
2417
2418 if (Instruction *common = commonIRemTransforms(I))
2419 return common;
2420
2421 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2422 return NarrowRem;
2423
2424 // X urem Y -> X and Y-1, where Y is a power of 2,
2425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2426 Type *Ty = I.getType();
2427 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2428 // This may increase instruction count, we don't enforce that Y is a
2429 // constant.
2431 Value *Add = Builder.CreateAdd(Op1, N1);
2432 return BinaryOperator::CreateAnd(Op0, Add);
2433 }
2434
2435 // 1 urem X -> zext(X != 1)
2436 if (match(Op0, m_One())) {
2437 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2438 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2439 }
2440
2441 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2442 // Op0 must be frozen because we are increasing its number of uses.
2443 if (match(Op1, m_Negative())) {
2444 Value *F0 = Op0;
2445 if (!isGuaranteedNotToBeUndef(Op0))
2446 F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2447 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2448 Value *Sub = Builder.CreateSub(F0, Op1);
2449 return SelectInst::Create(Cmp, F0, Sub);
2450 }
2451
2452 // If the divisor is a sext of a boolean, then the divisor must be max
2453 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2454 // max unsigned value. In that case, the remainder is 0:
2455 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2456 Value *X;
2457 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2458 Value *FrozenOp0 = Op0;
2459 if (!isGuaranteedNotToBeUndef(Op0))
2460 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2461 Value *Cmp =
2462 Builder.CreateICmpEQ(FrozenOp0, ConstantInt::getAllOnesValue(Ty));
2463 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2464 }
2465
2466 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2467 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2468 Value *Val =
2469 simplifyICmpInst(ICmpInst::ICMP_ULT, X, Op1, SQ.getWithInstruction(&I));
2470 if (Val && match(Val, m_One())) {
2471 Value *FrozenOp0 = Op0;
2472 if (!isGuaranteedNotToBeUndef(Op0))
2473 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2474 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2475 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2476 }
2477 }
2478
2479 return nullptr;
2480}
2481
2483 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2484 SQ.getWithInstruction(&I)))
2485 return replaceInstUsesWith(I, V);
2486
2488 return X;
2489
2490 // Handle the integer rem common cases
2491 if (Instruction *Common = commonIRemTransforms(I))
2492 return Common;
2493
2494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2495 {
2496 const APInt *Y;
2497 // X % -Y -> X % Y
2498 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2499 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2500 }
2501
2502 // -X srem Y --> -(X srem Y)
2503 Value *X, *Y;
2505 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
2506
2507 // If the sign bits of both operands are zero (i.e. we can prove they are
2508 // unsigned inputs), turn this into a urem.
2509 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2510 if (MaskedValueIsZero(Op1, Mask, &I) && MaskedValueIsZero(Op0, Mask, &I)) {
2511 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2512 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2513 }
2514
2515 // If it's a constant vector, flip any negative values positive.
2517 Constant *C = cast<Constant>(Op1);
2518 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2519
2520 bool hasNegative = false;
2521 bool hasMissing = false;
2522 for (unsigned i = 0; i != VWidth; ++i) {
2523 Constant *Elt = C->getAggregateElement(i);
2524 if (!Elt) {
2525 hasMissing = true;
2526 break;
2527 }
2528
2529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2530 if (RHS->isNegative())
2531 hasNegative = true;
2532 }
2533
2534 if (hasNegative && !hasMissing) {
2535 SmallVector<Constant *, 16> Elts(VWidth);
2536 for (unsigned i = 0; i != VWidth; ++i) {
2537 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2538 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2539 if (RHS->isNegative())
2541 }
2542 }
2543
2544 Constant *NewRHSV = ConstantVector::get(Elts);
2545 if (NewRHSV != C) // Don't loop on -MININT
2546 return replaceOperand(I, 1, NewRHSV);
2547 }
2548 }
2549
2550 return nullptr;
2551}
2552
2554 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2555 I.getFastMathFlags(),
2556 SQ.getWithInstruction(&I)))
2557 return replaceInstUsesWith(I, V);
2558
2560 return X;
2561
2563 return Phi;
2564
2565 return nullptr;
2566}
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
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 Value * simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, Instruction &CxtI)
The specific integer value is used in a context where it is known to be non-zero.
static 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 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)
This file provides the interface for the instcombine pass implementation.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition MD5.cpp:57
#define R2(n)
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
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")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
BinaryOperator * Mul
bool isNegative() const
Definition APFloat.h:1431
bool isZero() const
Definition APFloat.h:1427
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1573
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1758
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1541
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1890
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1489
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1112
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:418
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1640
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2005
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1532
unsigned logBase2() const
Definition APInt.h:1762
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1960
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1151
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:236
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:374
static BinaryOperator * CreateExact(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition InstrTypes.h:309
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:244
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:248
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:240
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:219
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.
Definition InstrTypes.h:982
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
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 Constant * 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:43
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 Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
LLVM_ABI bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:90
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
static FastMathFlags intersectRewrite(FastMathFlags LHS, FastMathFlags RHS)
Intersect rewrite-based flags.
Definition FMF.h:112
static FastMathFlags unionValue(FastMathFlags LHS, FastMathFlags RHS)
Union value flags.
Definition FMF.h:120
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:1420
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1492
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1708
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2794
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)
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,...
InstCombinerImpl(InstructionWorklist &Worklist, BuilderTy &Builder, 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)
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)
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
IRBuilder< TargetFolder, IRBuilderCallbackInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
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
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CxtI=nullptr, unsigned Depth=0) const
BuilderTy & Builder
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
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.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
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:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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:111
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:105
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.
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:45
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:147
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:233
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:150
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
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
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
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)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
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)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
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)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
AllowReassoc_match< T > m_AllowReassoc(const T &SubPattern)
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.
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)
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)
ap_match< APFloat > m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
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)
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
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.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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.
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:1737
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.
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 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:1744
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.
@ 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 bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
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:197
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:872
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:108
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:242
Matching combinators.