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