LLVM 23.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))
498 return createSelectInstWithUnknownProfile(X, Op1,
500 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
501 return createSelectInstWithUnknownProfile(X, Op0,
503
504 // mul (sext X), Y -> select X, -Y, 0
505 // mul Y, (sext X) -> select X, -Y, 0
506 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
507 X->getType()->isIntOrIntVectorTy(1))
508 return createSelectInstWithUnknownProfile(
509 X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
511
512 Constant *ImmC;
513 if (match(Op1, m_ImmConstant(ImmC))) {
514 // (sext bool X) * C --> X ? -C : 0
515 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
516 Constant *NegC = ConstantExpr::getNeg(ImmC);
517 return createSelectInstWithUnknownProfile(X, NegC,
519 }
520
521 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
522 const APInt *C;
523 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
524 *C == C->getBitWidth() - 1) {
525 Constant *NegC = ConstantExpr::getNeg(ImmC);
526 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
527 return createSelectInstWithUnknownProfile(IsNeg, NegC,
529 }
530 }
531
532 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
533 // TODO: We are not checking one-use because the elimination of the multiply
534 // is better for analysis?
535 const APInt *C;
536 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
537 *C == C->getBitWidth() - 1) {
538 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
539 return createSelectInstWithUnknownProfile(IsNeg, Y,
541 }
542
543 // (and X, 1) * Y --> (trunc X) ? Y : 0
544 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
545 Value *Tr = Builder.CreateTrunc(X, CmpInst::makeCmpResultType(Ty));
546 return createSelectInstWithUnknownProfile(Tr, Y,
548 }
549
550 // ((ashr X, 31) | 1) * X --> abs(X)
551 // X * ((ashr X, 31) | 1) --> abs(X)
554 m_One()),
555 m_Deferred(X)))) {
556 Value *Abs = Builder.CreateBinaryIntrinsic(
557 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
558 Abs->takeName(&I);
559 return replaceInstUsesWith(I, Abs);
560 }
561
562 if (Instruction *Ext = narrowMathIfNoOverflow(I))
563 return Ext;
564
566 return Res;
567
568 // (mul Op0 Op1):
569 // if Log2(Op0) folds away ->
570 // (shl Op1, Log2(Op0))
571 // if Log2(Op1) folds away ->
572 // (shl Op0, Log2(Op1))
573 if (Value *Res = tryGetLog2(Op0, /*AssumeNonZero=*/false)) {
574 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
575 // We can only propegate nuw flag.
576 Shl->setHasNoUnsignedWrap(HasNUW);
577 return Shl;
578 }
579 if (Value *Res = tryGetLog2(Op1, /*AssumeNonZero=*/false)) {
580 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
581 // We can only propegate nuw flag.
582 Shl->setHasNoUnsignedWrap(HasNUW);
583 return Shl;
584 }
585
586 bool Changed = false;
587 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
588 Changed = true;
589 I.setHasNoSignedWrap(true);
590 }
591
592 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I, I.hasNoSignedWrap())) {
593 Changed = true;
594 I.setHasNoUnsignedWrap(true);
595 }
596
597 return Changed ? &I : nullptr;
598}
599
600Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
601 BinaryOperator::BinaryOps Opcode = I.getOpcode();
602 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
603 "Expected fmul or fdiv");
604
605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
606 Value *X, *Y;
607
608 // -X * -Y --> X * Y
609 // -X / -Y --> X / Y
610 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
611 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
612
613 // fabs(X) * fabs(X) -> X * X
614 // fabs(X) / fabs(X) -> X / X
615 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
616 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
617
618 // fabs(X) * fabs(Y) --> fabs(X * Y)
619 // fabs(X) / fabs(Y) --> fabs(X / Y)
620 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
621 (Op0->hasOneUse() || Op1->hasOneUse())) {
622 Value *XY = Builder.CreateBinOpFMF(Opcode, X, Y, &I);
623 Value *Fabs =
624 Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY, &I, I.getName());
625 return replaceInstUsesWith(I, Fabs);
626 }
627
628 return nullptr;
629}
630
632 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
633 Value *Y, Value *Z) {
634 InstCombiner::BuilderTy &Builder = IC.Builder;
635 Value *YZ = Builder.CreateAdd(Y, Z);
636 Instruction *NewPow = Builder.CreateIntrinsic(
637 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
638
639 return NewPow;
640 };
641
642 Value *X, *Y, *Z;
643 unsigned Opcode = I.getOpcode();
644 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
645 "Unexpected opcode");
646
647 // powi(X, Y) * X --> powi(X, Y+1)
648 // X * powi(X, Y) --> powi(X, Y+1)
650 m_Value(X), m_Value(Y)))),
651 m_Deferred(X)))) {
652 Constant *One = ConstantInt::get(Y->getType(), 1);
653 if (willNotOverflowSignedAdd(Y, One, I)) {
654 Instruction *NewPow = createPowiExpr(I, *this, X, Y, One);
655 return replaceInstUsesWith(I, NewPow);
656 }
657 }
658
659 // powi(x, y) * powi(x, z) -> powi(x, y + z)
660 Value *Op0 = I.getOperand(0);
661 Value *Op1 = I.getOperand(1);
662 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
666 m_Value(Z)))) &&
667 Y->getType() == Z->getType()) {
668 Instruction *NewPow = createPowiExpr(I, *this, X, Y, Z);
669 return replaceInstUsesWith(I, NewPow);
670 }
671
672 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
673 // powi(X, Y) / X --> powi(X, Y-1)
674 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
675 // nnan are required.
676 // TODO: Multi-use may be also better off creating Powi(x,y-1)
678 m_Specific(Op1), m_Value(Y))))) &&
679 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
680 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
681 Instruction *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
682 return replaceInstUsesWith(I, NewPow);
683 }
684
685 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
686 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
687 // nnan are required.
688 // TODO: Multi-use may be also better off creating Powi(x,y-1)
690 m_Value(X), m_Value(Y))))) &&
692 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
693 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
694 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
695 return BinaryOperator::CreateFDivFMF(NewPow, Z, &I);
696 }
697 }
698
699 return nullptr;
700}
701
702// If we have the following pattern,
703// X = 1.0/sqrt(a)
704// R1 = X * X
705// R2 = a/sqrt(a)
706// then this method collects all the instructions that match R1 and R2.
710 Value *A;
711 if (match(Div, m_FDiv(m_FPOne(), m_Sqrt(m_Value(A)))) ||
712 match(Div, m_FDiv(m_SpecificFP(-1.0), m_Sqrt(m_Value(A))))) {
713 for (User *U : Div->users()) {
715 if (match(I, m_FMul(m_Specific(Div), m_Specific(Div))))
716 R1.insert(I);
717 }
718
719 CallInst *CI = cast<CallInst>(Div->getOperand(1));
720 for (User *U : CI->users()) {
723 R2.insert(I);
724 }
725 }
726 return !R1.empty() && !R2.empty();
727}
728
729// Check legality for transforming
730// x = 1.0/sqrt(a)
731// r1 = x * x;
732// r2 = a/sqrt(a);
733//
734// TO
735//
736// r1 = 1/a
737// r2 = sqrt(a)
738// x = r1 * r2
739// This transform works only when 'a' is known positive.
743 // Check if the required pattern for the transformation exists.
744 if (!getFSqrtDivOptPattern(X, R1, R2))
745 return false;
746
747 BasicBlock *BBx = X->getParent();
748 BasicBlock *BBr1 = (*R1.begin())->getParent();
749 BasicBlock *BBr2 = (*R2.begin())->getParent();
750
751 CallInst *FSqrt = cast<CallInst>(X->getOperand(1));
752 if (!FSqrt->hasAllowReassoc() || !FSqrt->hasNoNaNs() ||
753 !FSqrt->hasNoSignedZeros() || !FSqrt->hasNoInfs())
754 return false;
755
756 // We change x = 1/sqrt(a) to x = sqrt(a) * 1/a . This change isn't allowed
757 // by recip fp as it is strictly meant to transform ops of type a/b to
758 // a * 1/b. So, this can be considered as algebraic rewrite and reassoc flag
759 // has been used(rather abused)in the past for algebraic rewrites.
760 if (!X->hasAllowReassoc() || !X->hasAllowReciprocal() || !X->hasNoInfs())
761 return false;
762
763 // Check the constraints on X, R1 and R2 combined.
764 // fdiv instruction and one of the multiplications must reside in the same
765 // block. If not, the optimized code may execute more ops than before and
766 // this may hamper the performance.
767 if (BBx != BBr1 && BBx != BBr2)
768 return false;
769
770 // Check the constraints on instructions in R1.
771 if (any_of(R1, [BBr1](Instruction *I) {
772 // When you have multiple instructions residing in R1 and R2
773 // respectively, it's difficult to generate combinations of (R1,R2) and
774 // then check if we have the required pattern. So, for now, just be
775 // conservative.
776 return (I->getParent() != BBr1 || !I->hasAllowReassoc());
777 }))
778 return false;
779
780 // Check the constraints on instructions in R2.
781 return all_of(R2, [BBr2](Instruction *I) {
782 // When you have multiple instructions residing in R1 and R2
783 // respectively, it's difficult to generate combination of (R1,R2) and
784 // then check if we have the required pattern. So, for now, just be
785 // conservative.
786 return (I->getParent() == BBr2 && I->hasAllowReassoc());
787 });
788}
789
791 Value *Op0 = I.getOperand(0);
792 Value *Op1 = I.getOperand(1);
793 Value *X, *Y;
794 Constant *C;
795 BinaryOperator *Op0BinOp;
796
797 // Reassociate constant RHS with another constant to form constant
798 // expression.
799 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
800 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
801 // Everything in this scope folds I with Op0, intersecting their FMF.
802 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
803 Constant *C1;
804 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
805 // (C1 / X) * C --> (C * C1) / X
806 Constant *CC1 =
807 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
808 if (CC1 && CC1->isNormalFP())
809 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
810 }
811 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
812 // FIXME: This seems like it should also be checking for arcp
813 // (X / C1) * C --> X * (C / C1)
814 Constant *CDivC1 =
815 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
816 if (CDivC1 && CDivC1->isNormalFP())
817 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
818
819 // If the constant was a denormal, try reassociating differently.
820 // (X / C1) * C --> X / (C1 / C)
821 Constant *C1DivC =
822 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
823 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
824 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
825 }
826
827 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
828 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
829 // further folds and (X * C) + C2 is 'fma'.
830 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
831 // (X + C1) * C --> (X * C) + (C * C1)
832 if (Constant *CC1 =
833 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
834 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
835 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
836 }
837 }
838 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
839 // (C1 - X) * C --> (C * C1) - (X * C)
840 if (Constant *CC1 =
841 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
842 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
843 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
844 }
845 }
846 }
847
848 Value *Z;
849 if (match(&I,
851 m_Value(Z)))) {
852 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
853 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
854 if (FMF.allowReassoc()) {
855 // Sink division: (X / Y) * Z --> (X * Z) / Y
856 auto *NewFMul = Builder.CreateFMulFMF(X, Z, FMF);
857 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
858 }
859 }
860
861 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
862 // nnan disallows the possibility of returning a number if both operands are
863 // negative (in that case, we should return NaN).
864 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
865 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
866 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
867 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
868 return replaceInstUsesWith(I, Sqrt);
869 }
870
871 // The following transforms are done irrespective of the number of uses
872 // for the expression "1.0/sqrt(X)".
873 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
874 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
875 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
876 // has the necessary (reassoc) fast-math-flags.
877 if (I.hasNoSignedZeros() &&
878 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
879 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
881 if (I.hasNoSignedZeros() &&
882 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
883 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
885
886 // Like the similar transform in instsimplify, this requires 'nsz' because
887 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
888 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
889 // Peek through fdiv to find squaring of square root:
890 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
891 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
892 Value *XX = Builder.CreateFMulFMF(X, X, &I);
893 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
894 }
895 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
896 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
897 Value *XX = Builder.CreateFMulFMF(X, X, &I);
898 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
899 }
900 }
901
902 // pow(X, Y) * X --> pow(X, Y+1)
903 // X * pow(X, Y) --> pow(X, Y+1)
905 m_Value(Y))),
906 m_Deferred(X)))) {
907 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
908 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
909 return replaceInstUsesWith(I, Pow);
910 }
911
912 if (Instruction *FoldedPowi = foldPowiReassoc(I))
913 return FoldedPowi;
914
915 if (I.isOnlyUserOfAnyOperand()) {
916 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
919 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
920 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
921 return replaceInstUsesWith(I, NewPow);
922 }
923 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
926 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
927 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
928 return replaceInstUsesWith(I, NewPow);
929 }
930
931 // exp(X) * exp(Y) -> exp(X + Y)
934 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
935 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
936 return replaceInstUsesWith(I, Exp);
937 }
938
939 // exp2(X) * exp2(Y) -> exp2(X + Y)
942 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
943 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
944 return replaceInstUsesWith(I, Exp2);
945 }
946 }
947
948 // (X*Y) * X => (X*X) * Y where Y != X
949 // The purpose is two-fold:
950 // 1) to form a power expression (of X).
951 // 2) potentially shorten the critical path: After transformation, the
952 // latency of the instruction Y is amortized by the expression of X*X,
953 // and therefore Y is in a "less critical" position compared to what it
954 // was before the transformation.
955 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
956 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
957 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
958 }
959 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
960 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
961 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
962 }
963
964 return nullptr;
965}
966
968 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
969 I.getFastMathFlags(),
970 SQ.getWithInstruction(&I)))
971 return replaceInstUsesWith(I, V);
972
974 return &I;
975
977 return X;
978
980 return Phi;
981
982 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
983 return FoldedMul;
984
985 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
986 return replaceInstUsesWith(I, FoldedMul);
987
988 if (Instruction *R = foldFPSignBitOps(I))
989 return R;
990
991 if (Instruction *R = foldFBinOpOfIntCasts(I))
992 return R;
993
994 // X * -1.0 --> -X
995 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
996 if (match(Op1, m_SpecificFP(-1.0)))
997 return UnaryOperator::CreateFNegFMF(Op0, &I);
998
999 // With no-nans/no-infs:
1000 // X * 0.0 --> copysign(0.0, X)
1001 // X * -0.0 --> copysign(0.0, -X)
1002 const APFloat *FPC;
1003 if (match(Op1, m_APFloatAllowPoison(FPC)) && FPC->isZero() &&
1004 ((I.hasNoInfs() && isKnownNeverNaN(Op0, SQ.getWithInstruction(&I))) ||
1005 isKnownNeverNaN(&I, SQ.getWithInstruction(&I)))) {
1006 if (FPC->isNegative())
1007 Op0 = Builder.CreateFNegFMF(Op0, &I);
1008 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
1009 {I.getType()}, {Op1, Op0}, &I);
1010 return replaceInstUsesWith(I, CopySign);
1011 }
1012
1013 // -X * C --> X * -C
1014 Value *X, *Y;
1015 Constant *C;
1016 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
1017 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1018 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
1019
1020 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
1021 // (uitofp bool X) * Y --> X ? Y : 0
1022 // Y * (uitofp bool X) --> X ? Y : 0
1023 // Note INF * 0 is NaN.
1024 if (match(Op0, m_UIToFP(m_Value(X))) &&
1025 X->getType()->isIntOrIntVectorTy(1)) {
1026 auto *SI = createSelectInstWithUnknownProfile(
1027 X, Op1, ConstantFP::get(I.getType(), 0.0));
1028 SI->copyFastMathFlags(I.getFastMathFlags());
1029 return SI;
1030 }
1031 if (match(Op1, m_UIToFP(m_Value(X))) &&
1032 X->getType()->isIntOrIntVectorTy(1)) {
1033 auto *SI = createSelectInstWithUnknownProfile(
1034 X, Op0, ConstantFP::get(I.getType(), 0.0));
1035 SI->copyFastMathFlags(I.getFastMathFlags());
1036 return SI;
1037 }
1038 }
1039
1040 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
1041 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1042 return replaceInstUsesWith(I, V);
1043
1044 if (I.hasAllowReassoc())
1045 if (Instruction *FoldedMul = foldFMulReassoc(I))
1046 return FoldedMul;
1047
1048 // log2(X * 0.5) * Y = log2(X) * Y - Y
1049 if (I.isFast()) {
1050 IntrinsicInst *Log2 = nullptr;
1052 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1054 Y = Op1;
1055 }
1057 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1059 Y = Op0;
1060 }
1061 if (Log2) {
1062 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
1063 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
1064 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
1065 }
1066 }
1067
1068 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
1069 // Given a phi node with entry value as 0 and it used in fmul operation,
1070 // we can replace fmul with 0 safely and eleminate loop operation.
1071 PHINode *PN = nullptr;
1072 Value *Start = nullptr, *Step = nullptr;
1073 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
1074 I.hasNoSignedZeros() && match(Start, m_Zero()))
1075 return replaceInstUsesWith(I, Start);
1076
1077 // minimum(X, Y) * maximum(X, Y) => X * Y.
1078 if (match(&I,
1081 m_Deferred(Y))))) {
1083 // We cannot preserve ninf if nnan flag is not set.
1084 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
1085 // while in optimized version NaN * Inf and this is a poison with ninf flag.
1086 if (!Result->hasNoNaNs())
1087 Result->setHasNoInfs(false);
1088 return Result;
1089 }
1090
1091 // tan(X) * cos(X) -> sin(X)
1092 if (I.hasAllowContract() &&
1093 match(&I,
1096 auto *Sin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, &I);
1097 if (auto *Metadata = I.getMetadata(LLVMContext::MD_fpmath)) {
1098 Sin->setMetadata(LLVMContext::MD_fpmath, Metadata);
1099 }
1100 return replaceInstUsesWith(I, Sin);
1101 }
1102
1103 return nullptr;
1104}
1105
1106/// Fold a divide or remainder with a select instruction divisor when one of the
1107/// select operands is zero. In that case, we can use the other select operand
1108/// because div/rem by zero is undefined.
1110 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
1111 if (!SI)
1112 return false;
1113
1114 int NonNullOperand;
1115 if (match(SI->getTrueValue(), m_Zero()))
1116 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1117 NonNullOperand = 2;
1118 else if (match(SI->getFalseValue(), m_Zero()))
1119 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1120 NonNullOperand = 1;
1121 else
1122 return false;
1123
1124 // Change the div/rem to use 'Y' instead of the select.
1125 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
1126
1127 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1128 // problem. However, the select, or the condition of the select may have
1129 // multiple uses. Based on our knowledge that the operand must be non-zero,
1130 // propagate the known value for the select into other uses of it, and
1131 // propagate a known value of the condition into its other users.
1132
1133 // If the select and condition only have a single use, don't bother with this,
1134 // early exit.
1135 Value *SelectCond = SI->getCondition();
1136 if (SI->use_empty() && SelectCond->hasOneUse())
1137 return true;
1138
1139 // Scan the current block backward, looking for other uses of SI.
1140 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
1141 Type *CondTy = SelectCond->getType();
1142 while (BBI != BBFront) {
1143 --BBI;
1144 // If we found an instruction that we can't assume will return, so
1145 // information from below it cannot be propagated above it.
1147 break;
1148
1149 // Replace uses of the select or its condition with the known values.
1150 for (Use &Op : BBI->operands()) {
1151 if (Op == SI) {
1152 replaceUse(Op, SI->getOperand(NonNullOperand));
1153 Worklist.push(&*BBI);
1154 } else if (Op == SelectCond) {
1155 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
1156 : ConstantInt::getFalse(CondTy));
1157 Worklist.push(&*BBI);
1158 }
1159 }
1160
1161 // If we past the instruction, quit looking for it.
1162 if (&*BBI == SI)
1163 SI = nullptr;
1164 if (&*BBI == SelectCond)
1165 SelectCond = nullptr;
1166
1167 // If we ran out of things to eliminate, break out of the loop.
1168 if (!SelectCond && !SI)
1169 break;
1170
1171 }
1172 return true;
1173}
1174
1175/// True if the multiply can not be expressed in an int this size.
1176static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1177 bool IsSigned) {
1178 bool Overflow;
1179 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
1180 return Overflow;
1181}
1182
1183/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1184static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1185 bool IsSigned) {
1186 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1187
1188 // Bail if we will divide by zero.
1189 if (C2.isZero())
1190 return false;
1191
1192 // Bail if we would divide INT_MIN by -1.
1193 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1194 return false;
1195
1196 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1197 if (IsSigned)
1198 APInt::sdivrem(C1, C2, Quotient, Remainder);
1199 else
1200 APInt::udivrem(C1, C2, Quotient, Remainder);
1201
1202 return Remainder.isMinValue();
1203}
1204
1206 assert((I.getOpcode() == Instruction::SDiv ||
1207 I.getOpcode() == Instruction::UDiv) &&
1208 "Expected integer divide");
1209
1210 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1212 Type *Ty = I.getType();
1213
1214 Value *X, *Y, *Z;
1215
1216 // With appropriate no-wrap constraints, remove a common factor in the
1217 // dividend and divisor that is disguised as a left-shifted value.
1218 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1219 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1220 // Both operands must have the matching no-wrap for this kind of division.
1222 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1223 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1224 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1225
1226 // (X * Y) u/ (X << Z) --> Y u>> Z
1227 if (!IsSigned && HasNUW)
1228 return Builder.CreateLShr(Y, Z, "", I.isExact());
1229
1230 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1231 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1232 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1233 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1234 }
1235 }
1236
1237 // With appropriate no-wrap constraints, remove a common factor in the
1238 // dividend and divisor that is disguised as a left-shift amount.
1239 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1240 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1241 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1242 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1243
1244 // For unsigned div, we need 'nuw' on both shifts or
1245 // 'nsw' on both shifts + 'nuw' on the dividend.
1246 // (X << Z) / (Y << Z) --> X / Y
1247 if (!IsSigned &&
1248 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1249 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1250 Shl1->hasNoSignedWrap())))
1251 return Builder.CreateUDiv(X, Y, "", I.isExact());
1252
1253 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1254 // (X << Z) / (Y << Z) --> X / Y
1255 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1256 Shl1->hasNoUnsignedWrap())
1257 return Builder.CreateSDiv(X, Y, "", I.isExact());
1258 }
1259
1260 // If X << Y and X << Z does not overflow, then:
1261 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1262 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1263 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1264 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1265 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1266
1267 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1268 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1269 Constant *One = ConstantInt::get(X->getType(), 1);
1270 // Only preserve the nsw flag if dividend has nsw
1271 // or divisor has nsw and operator is sdiv.
1272 Value *Dividend = Builder.CreateShl(
1273 One, Y, "shl.dividend",
1274 /*HasNUW=*/true,
1275 /*HasNSW=*/
1276 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1277 : Shl0->hasNoSignedWrap());
1278 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1279 }
1280 }
1281
1282 return nullptr;
1283}
1284
1285/// Common integer divide/remainder transforms
1287 assert(I.isIntDivRem() && "Unexpected instruction");
1288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1289
1290 // If any element of a constant divisor fixed width vector is zero or undef
1291 // the behavior is undefined and we can fold the whole op to poison.
1292 auto *Op1C = dyn_cast<Constant>(Op1);
1293 Type *Ty = I.getType();
1294 auto *VTy = dyn_cast<FixedVectorType>(Ty);
1295 if (Op1C && VTy) {
1296 unsigned NumElts = VTy->getNumElements();
1297 for (unsigned i = 0; i != NumElts; ++i) {
1298 Constant *Elt = Op1C->getAggregateElement(i);
1299 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
1301 }
1302 }
1303
1305 return Phi;
1306
1307 // The RHS is known non-zero.
1308 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1309 return replaceOperand(I, 1, V);
1310
1311 // Handle cases involving: div/rem X, (select Cond, Y, Z)
1313 return &I;
1314
1315 // If the divisor is a select-of-constants, try to constant fold all div ops:
1316 // C div/rem (select Cond, TrueC, FalseC) --> select Cond, (C div/rem TrueC),
1317 // (C div/rem FalseC)
1318 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1319 if (match(Op0, m_ImmConstant()) &&
1322 /*FoldWithMultiUse*/ true))
1323 return R;
1324 }
1325
1326 return nullptr;
1327}
1328
1329/// This function implements the transforms common to both integer division
1330/// instructions (udiv and sdiv). It is called by the visitors to those integer
1331/// division instructions.
1332/// Common integer divide transforms
1335 return Res;
1336
1337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1338 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1339 Type *Ty = I.getType();
1340
1341 const APInt *C2;
1342 if (match(Op1, m_APInt(C2))) {
1343 Value *X;
1344 const APInt *C1;
1345
1346 // (X / C1) / C2 -> X / (C1*C2)
1347 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1348 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1349 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1350 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1351 return BinaryOperator::Create(I.getOpcode(), X,
1352 ConstantInt::get(Ty, Product));
1353 }
1354
1355 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1356 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1357 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1358
1359 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1360 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1361 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1362 ConstantInt::get(Ty, Quotient));
1363 NewDiv->setIsExact(I.isExact());
1364 return NewDiv;
1365 }
1366
1367 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1368 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1369 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1370 ConstantInt::get(Ty, Quotient));
1371 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1372 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1373 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1374 return Mul;
1375 }
1376 }
1377
1378 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1379 C1->ult(C1->getBitWidth() - 1)) ||
1380 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1381 C1->ult(C1->getBitWidth()))) {
1382 APInt C1Shifted = APInt::getOneBitSet(
1383 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1384
1385 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1386 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1387 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1388 ConstantInt::get(Ty, Quotient));
1389 BO->setIsExact(I.isExact());
1390 return BO;
1391 }
1392
1393 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1394 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1395 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1396 ConstantInt::get(Ty, Quotient));
1397 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1398 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1399 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1400 return Mul;
1401 }
1402 }
1403
1404 // Distribute div over add to eliminate a matching div/mul pair:
1405 // ((X * C2) + C1) / C2 --> X + C1/C2
1406 // We need a multiple of the divisor for a signed add constant, but
1407 // unsigned is fine with any constant pair.
1408 if (IsSigned &&
1410 m_APInt(C1))) &&
1411 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1412 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1413 }
1414 if (!IsSigned &&
1416 m_APInt(C1)))) {
1417 return BinaryOperator::CreateNUWAdd(X,
1418 ConstantInt::get(Ty, C1->udiv(*C2)));
1419 }
1420
1421 if (!C2->isZero()) // avoid X udiv 0
1422 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1423 return FoldedDiv;
1424 }
1425
1426 if (match(Op0, m_One())) {
1427 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1428 if (IsSigned) {
1429 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1430 // (Op1 + 1) u< 3 ? Op1 : 0
1431 // Op1 must be frozen because we are increasing its number of uses.
1432 Value *F1 = Op1;
1433 if (!isGuaranteedNotToBeUndef(Op1))
1434 F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1435 Value *Inc = Builder.CreateAdd(F1, Op0);
1436 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1437 return createSelectInstWithUnknownProfile(Cmp, F1,
1438 ConstantInt::get(Ty, 0));
1439 } else {
1440 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1441 // result is one, otherwise it's zero.
1442 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1443 }
1444 }
1445
1446 // See if we can fold away this div instruction.
1448 return &I;
1449
1450 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1451 Value *X, *Z;
1452 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1453 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1454 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1455 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1456
1457 // (X << Y) / X -> 1 << Y
1458 Value *Y;
1459 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1460 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1461 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1462 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1463
1464 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1465 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1466 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1467 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1468 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1469 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1470 replaceOperand(I, 1, Y);
1471 return &I;
1472 }
1473 }
1474
1475 // (X << Z) / (X * Y) -> (1 << Z) / Y
1476 // TODO: Handle sdiv.
1477 if (!IsSigned && Op1->hasOneUse() &&
1478 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1479 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1481 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1482 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1483 NewDiv->setIsExact(I.isExact());
1484 return NewDiv;
1485 }
1486
1487 if (Value *R = foldIDivShl(I, Builder))
1488 return replaceInstUsesWith(I, R);
1489
1490 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1491 // after peeking through another divide:
1492 // ((Op1 * X) / Y) / Op1 --> X / Y
1493 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1494 m_Value(Y)))) {
1495 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1496 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1497 Instruction *NewDiv = nullptr;
1498 if (!IsSigned && Mul->hasNoUnsignedWrap())
1499 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1500 else if (IsSigned && Mul->hasNoSignedWrap())
1501 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1502
1503 // Exact propagates only if both of the original divides are exact.
1504 if (NewDiv) {
1505 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1506 return NewDiv;
1507 }
1508 }
1509
1510 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1511 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1512 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1513 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1514
1515 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1516 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1517 auto OB1HasNUW =
1518 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1519 const APInt *C1, *C2;
1520 if (IsSigned && OB0HasNSW) {
1521 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1522 return BinaryOperator::CreateSDiv(A, B);
1523 }
1524 if (!IsSigned && OB0HasNUW) {
1525 if (OB1HasNUW)
1526 return BinaryOperator::CreateUDiv(A, B);
1527 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1528 return BinaryOperator::CreateUDiv(A, B);
1529 }
1530 return nullptr;
1531 };
1532
1533 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1534 if (auto *Val = CreateDivOrNull(Y, Z))
1535 return Val;
1536 }
1537 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1538 if (auto *Val = CreateDivOrNull(X, Z))
1539 return Val;
1540 }
1541 }
1542 return nullptr;
1543}
1544
1545Value *InstCombinerImpl::takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero,
1546 bool DoFold) {
1547 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1548 if (!DoFold)
1549 return reinterpret_cast<Value *>(-1);
1550 return Fn();
1551 };
1552
1553 // FIXME: assert that Op1 isn't/doesn't contain undef.
1554
1555 // log2(2^C) -> C
1556 if (match(Op, m_Power2()))
1557 return IfFold([&]() {
1559 if (!C)
1560 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1561 return C;
1562 });
1563
1564 // The remaining tests are all recursive, so bail out if we hit the limit.
1566 return nullptr;
1567
1568 // log2(zext X) -> zext log2(X)
1569 // FIXME: Require one use?
1570 Value *X, *Y;
1571 if (match(Op, m_ZExt(m_Value(X))))
1572 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1573 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1574
1575 // log2(trunc x) -> trunc log2(X)
1576 // FIXME: Require one use?
1577 if (match(Op, m_Trunc(m_Value(X)))) {
1578 auto *TI = cast<TruncInst>(Op);
1579 if (AssumeNonZero || TI->hasNoUnsignedWrap())
1580 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1581 return IfFold([&]() {
1582 return Builder.CreateTrunc(LogX, Op->getType(), "",
1583 /*IsNUW=*/TI->hasNoUnsignedWrap());
1584 });
1585 }
1586
1587 // log2(X << Y) -> log2(X) + Y
1588 // FIXME: Require one use unless X is 1?
1589 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1591 // nuw will be set if the `shl` is trivially non-zero.
1592 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1593 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1594 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1595 }
1596
1597 // log2(X >>u Y) -> log2(X) - Y
1598 // FIXME: Require one use?
1599 if (match(Op, m_LShr(m_Value(X), m_Value(Y)))) {
1600 auto *PEO = cast<PossiblyExactOperator>(Op);
1601 if (AssumeNonZero || PEO->isExact())
1602 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1603 return IfFold([&]() { return Builder.CreateSub(LogX, Y); });
1604 }
1605
1606 // log2(X & Y) -> either log2(X) or log2(Y)
1607 // This requires `AssumeNonZero` as `X & Y` may be zero when X != Y.
1608 if (AssumeNonZero && match(Op, m_And(m_Value(X), m_Value(Y)))) {
1609 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1610 return IfFold([&]() { return LogX; });
1611 if (Value *LogY = takeLog2(Y, Depth, AssumeNonZero, DoFold))
1612 return IfFold([&]() { return LogY; });
1613 }
1614
1615 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1616 // FIXME: Require one use?
1618 if (Value *LogX = takeLog2(SI->getOperand(1), Depth, AssumeNonZero, DoFold))
1619 if (Value *LogY =
1620 takeLog2(SI->getOperand(2), Depth, AssumeNonZero, DoFold))
1621 return IfFold([&]() {
1622 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1623 });
1624
1625 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1626 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1628 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1629 // Use AssumeNonZero as false here. Otherwise we can hit case where
1630 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1631 if (Value *LogX = takeLog2(MinMax->getLHS(), Depth,
1632 /*AssumeNonZero*/ false, DoFold))
1633 if (Value *LogY = takeLog2(MinMax->getRHS(), Depth,
1634 /*AssumeNonZero*/ false, DoFold))
1635 return IfFold([&]() {
1636 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1637 LogY);
1638 });
1639 }
1640
1641 return nullptr;
1642}
1643
1644/// If we have zero-extended operands of an unsigned div or rem, we may be able
1645/// to narrow the operation (sink the zext below the math).
1647 InstCombinerImpl &IC) {
1648 Instruction::BinaryOps Opcode = I.getOpcode();
1649 Value *N = I.getOperand(0);
1650 Value *D = I.getOperand(1);
1651 Type *Ty = I.getType();
1652 Value *X, *Y;
1653 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1654 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1655 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1656 // urem (zext X), (zext Y) --> zext (urem X, Y)
1657 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1658 return new ZExtInst(NarrowOp, Ty);
1659 }
1660
1661 Constant *C;
1662 auto &DL = IC.getDataLayout();
1664 match(D, m_Constant(C))) {
1665 // If the constant is the same in the smaller type, use the narrow version.
1666 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1667 if (!TruncC)
1668 return nullptr;
1669
1670 // udiv (zext X), C --> zext (udiv X, C')
1671 // urem (zext X), C --> zext (urem X, C')
1672 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1673 }
1675 match(N, m_Constant(C))) {
1676 // If the constant is the same in the smaller type, use the narrow version.
1677 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1678 if (!TruncC)
1679 return nullptr;
1680
1681 // udiv C, (zext X) --> zext (udiv C', X)
1682 // urem C, (zext X) --> zext (urem C', X)
1683 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1684 }
1685
1686 return nullptr;
1687}
1688
1690 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1691 SQ.getWithInstruction(&I)))
1692 return replaceInstUsesWith(I, V);
1693
1695 return X;
1696
1697 // Handle the integer div common cases
1698 if (Instruction *Common = commonIDivTransforms(I))
1699 return Common;
1700
1701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1702 Value *X;
1703 const APInt *C1, *C2;
1704 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1705 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1706 bool Overflow;
1707 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1708 if (!Overflow) {
1709 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1710 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1711 X, ConstantInt::get(X->getType(), C2ShlC1));
1712 if (IsExact)
1713 BO->setIsExact();
1714 return BO;
1715 }
1716 }
1717
1718 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1719 // TODO: Could use isKnownNegative() to handle non-constant values.
1720 Type *Ty = I.getType();
1721 if (match(Op1, m_Negative())) {
1722 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1723 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1724 }
1725 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1726 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1727 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1728 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1729 }
1730
1731 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1732 return NarrowDiv;
1733
1734 Value *A, *B;
1735
1736 // Look through a right-shift to find the common factor:
1737 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1738 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1739 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1740 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1741 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1742 Lshr->setIsExact();
1743 return Lshr;
1744 }
1745
1746 auto GetShiftableDenom = [&](Value *Denom) -> Value * {
1747 // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
1748 if (Value *Log2 = tryGetLog2(Op1, /*AssumeNonZero=*/true))
1749 return Log2;
1750
1751 // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
1752 if (isKnownToBeAPowerOfTwo(Denom, /*OrZero=*/true, &I))
1753 // This will increase instruction count but it's okay
1754 // since bitwise operations are substantially faster than
1755 // division.
1756 return Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Denom,
1757 Builder.getTrue());
1758
1759 return nullptr;
1760 };
1761
1762 if (auto *Res = GetShiftableDenom(Op1))
1763 return replaceInstUsesWith(
1764 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1765
1766 return nullptr;
1767}
1768
1770 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1771 SQ.getWithInstruction(&I)))
1772 return replaceInstUsesWith(I, V);
1773
1775 return X;
1776
1777 // Handle the integer div common cases
1778 if (Instruction *Common = commonIDivTransforms(I))
1779 return Common;
1780
1781 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1782 Type *Ty = I.getType();
1783 Value *X;
1784 // sdiv Op0, -1 --> -Op0
1785 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1786 if (match(Op1, m_AllOnes()) ||
1787 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1788 return BinaryOperator::CreateNSWNeg(Op0);
1789
1790 // X / INT_MIN --> X == INT_MIN
1791 if (match(Op1, m_SignMask()))
1792 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1793
1794 if (I.isExact()) {
1795 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1796 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1798 return BinaryOperator::CreateExactAShr(Op0, C);
1799 }
1800
1801 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1802 Value *ShAmt;
1803 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1804 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1805
1806 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1807 if (match(Op1, m_NegatedPower2())) {
1810 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1811 return BinaryOperator::CreateNSWNeg(Ashr);
1812 }
1813 }
1814
1815 const APInt *Op1C;
1816 if (match(Op1, m_APInt(Op1C))) {
1817 // If the dividend is sign-extended and the constant divisor is small enough
1818 // to fit in the source type, shrink the division to the narrower type:
1819 // (sext X) sdiv C --> sext (X sdiv C)
1820 Value *Op0Src;
1821 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1822 Op0Src->getType()->getScalarSizeInBits() >=
1823 Op1C->getSignificantBits()) {
1824
1825 // In the general case, we need to make sure that the dividend is not the
1826 // minimum signed value because dividing that by -1 is UB. But here, we
1827 // know that the -1 divisor case is already handled above.
1828
1829 Constant *NarrowDivisor =
1831 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1832 return new SExtInst(NarrowOp, Ty);
1833 }
1834
1835 // -X / C --> X / -C (if the negation doesn't overflow).
1836 // TODO: This could be enhanced to handle arbitrary vector constants by
1837 // checking if all elements are not the min-signed-val.
1838 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
1839 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1840 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1841 BO->setIsExact(I.isExact());
1842 return BO;
1843 }
1844 }
1845
1846 // -X / Y --> -(X / Y)
1847 Value *Y;
1850 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1851
1852 // abs(X) / X --> X > -1 ? 1 : -1
1853 // X / abs(X) --> X > -1 ? 1 : -1
1854 if (match(&I, m_c_BinOp(
1856 m_Deferred(X)))) {
1857 Value *Cond = Builder.CreateIsNotNeg(X);
1858 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
1860 }
1861
1862 KnownBits KnownDividend = computeKnownBits(Op0, &I);
1863 if (!I.isExact() &&
1864 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1865 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1866 I.setIsExact();
1867 return &I;
1868 }
1869
1870 if (KnownDividend.isNonNegative()) {
1871 // If both operands are unsigned, turn this into a udiv.
1872 if (isKnownNonNegative(Op1, SQ.getWithInstruction(&I))) {
1873 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1874 BO->setIsExact(I.isExact());
1875 return BO;
1876 }
1877
1878 if (match(Op1, m_NegatedPower2())) {
1879 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1880 // -> -(X udiv (1 << C)) -> -(X u>> C)
1883 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1884 return BinaryOperator::CreateNeg(Shr);
1885 }
1886
1887 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
1888 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1889 // Safe because the only negative value (1 << Y) can take on is
1890 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1891 // the sign bit set.
1892 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1893 BO->setIsExact(I.isExact());
1894 return BO;
1895 }
1896 }
1897
1898 // -X / X --> X == INT_MIN ? 1 : -1
1899 if (isKnownNegation(Op0, Op1)) {
1900 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1901 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1902 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
1904 }
1905 return nullptr;
1906}
1907
1908/// Remove negation and try to convert division into multiplication.
1909Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1910 Constant *C;
1911 if (!match(I.getOperand(1), m_Constant(C)))
1912 return nullptr;
1913
1914 // -X / C --> X / -C
1915 Value *X;
1916 const DataLayout &DL = I.getDataLayout();
1917 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1918 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1919 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1920
1921 // nnan X / +0.0 -> copysign(inf, X)
1922 // nnan nsz X / -0.0 -> copysign(inf, X)
1923 if (I.hasNoNaNs() &&
1924 (match(I.getOperand(1), m_PosZeroFP()) ||
1925 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1926 IRBuilder<> B(&I);
1927 CallInst *CopySign = B.CreateIntrinsic(
1928 Intrinsic::copysign, {C->getType()},
1929 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1930 CopySign->takeName(&I);
1931 return replaceInstUsesWith(I, CopySign);
1932 }
1933
1934 // If the constant divisor has an exact inverse, this is always safe. If not,
1935 // then we can still create a reciprocal if fast-math-flags allow it and the
1936 // constant is a regular number (not zero, infinite, or denormal).
1937 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1938 return nullptr;
1939
1940 // Disallow denormal constants because we don't know what would happen
1941 // on all targets.
1942 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1943 // denorms are flushed?
1944 auto *RecipC = ConstantFoldBinaryOpOperands(
1945 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1946 if (!RecipC || !RecipC->isNormalFP())
1947 return nullptr;
1948
1949 // X / C --> X * (1 / C)
1950 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1951}
1952
1953/// Remove negation and try to reassociate constant math.
1955 Constant *C;
1956 if (!match(I.getOperand(0), m_Constant(C)))
1957 return nullptr;
1958
1959 // C / -X --> -C / X
1960 Value *X;
1961 const DataLayout &DL = I.getDataLayout();
1962 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1963 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1964 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1965
1966 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1967 return nullptr;
1968
1969 // Try to reassociate C / X expressions where X includes another constant.
1970 Constant *C2, *NewC = nullptr;
1971 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1972 // C / (X * C2) --> (C / C2) / X
1973 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1974 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1975 // C / (X / C2) --> (C * C2) / X
1976 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1977 }
1978 // Disallow denormal constants because we don't know what would happen
1979 // on all targets.
1980 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1981 // denorms are flushed?
1982 if (!NewC || !NewC->isNormalFP())
1983 return nullptr;
1984
1985 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1986}
1987
1988/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1990 InstCombiner::BuilderTy &Builder) {
1991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1992 auto *II = dyn_cast<IntrinsicInst>(Op1);
1993 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1994 !I.hasAllowReciprocal())
1995 return nullptr;
1996
1997 // Z / pow(X, Y) --> Z * pow(X, -Y)
1998 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1999 // In the general case, this creates an extra instruction, but fmul allows
2000 // for better canonicalization and optimization than fdiv.
2001 Intrinsic::ID IID = II->getIntrinsicID();
2003 switch (IID) {
2004 case Intrinsic::pow:
2005 Args.push_back(II->getArgOperand(0));
2006 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
2007 break;
2008 case Intrinsic::powi: {
2009 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
2010 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
2011 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
2012 // non-standard results, so this corner case should be acceptable if the
2013 // code rules out INF values.
2014 if (!I.hasNoInfs())
2015 return nullptr;
2016 Args.push_back(II->getArgOperand(0));
2017 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
2018 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
2019 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
2020 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2021 }
2022 case Intrinsic::exp:
2023 case Intrinsic::exp2:
2024 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
2025 break;
2026 default:
2027 return nullptr;
2028 }
2029 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
2030 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2031}
2032
2033/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
2034/// instruction.
2036 InstCombiner::BuilderTy &Builder) {
2037 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
2038 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2039 return nullptr;
2040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2041 auto *II = dyn_cast<IntrinsicInst>(Op1);
2042 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
2043 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
2044 return nullptr;
2045
2046 Value *Y, *Z;
2047 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
2048 if (!DivOp)
2049 return nullptr;
2050 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
2051 return nullptr;
2052 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
2053 !DivOp->hasOneUse())
2054 return nullptr;
2055 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
2056 Value *NewSqrt =
2057 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
2058 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
2059}
2060
2061// Change
2062// X = 1/sqrt(a)
2063// R1 = X * X
2064// R2 = a * X
2065//
2066// TO
2067//
2068// FDiv = 1/a
2069// FSqrt = sqrt(a)
2070// FMul = FDiv * FSqrt
2071// Replace Uses Of R1 With FDiv
2072// Replace Uses Of R2 With FSqrt
2073// Replace Uses Of X With FMul
2074static Instruction *
2079
2080 B.SetInsertPoint(X);
2081
2082 // Have an instruction that is representative of all of instructions in R1 and
2083 // get the most common fpmath metadata and fast-math flags on it.
2084 Value *SqrtOp = CI->getArgOperand(0);
2085 auto *FDiv = cast<Instruction>(
2086 B.CreateFDiv(ConstantFP::get(X->getType(), 1.0), SqrtOp));
2087 auto *R1FPMathMDNode = (*R1.begin())->getMetadata(LLVMContext::MD_fpmath);
2088 FastMathFlags R1FMF = (*R1.begin())->getFastMathFlags(); // Common FMF
2089 for (Instruction *I : R1) {
2090 R1FPMathMDNode = MDNode::getMostGenericFPMath(
2091 R1FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2092 R1FMF &= I->getFastMathFlags();
2093 IC->replaceInstUsesWith(*I, FDiv);
2095 }
2096 FDiv->setMetadata(LLVMContext::MD_fpmath, R1FPMathMDNode);
2097 FDiv->copyFastMathFlags(R1FMF);
2098
2099 // Have a single sqrt call instruction that is representative of all of
2100 // instructions in R2 and get the most common fpmath metadata and fast-math
2101 // flags on it.
2102 auto *FSqrt = cast<CallInst>(CI->clone());
2103 FSqrt->insertBefore(CI->getIterator());
2104 auto *R2FPMathMDNode = (*R2.begin())->getMetadata(LLVMContext::MD_fpmath);
2105 FastMathFlags R2FMF = (*R2.begin())->getFastMathFlags(); // Common FMF
2106 for (Instruction *I : R2) {
2107 R2FPMathMDNode = MDNode::getMostGenericFPMath(
2108 R2FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2109 R2FMF &= I->getFastMathFlags();
2110 IC->replaceInstUsesWith(*I, FSqrt);
2112 }
2113 FSqrt->setMetadata(LLVMContext::MD_fpmath, R2FPMathMDNode);
2114 FSqrt->copyFastMathFlags(R2FMF);
2115
2117 // If X = -1/sqrt(a) initially,then FMul = -(FDiv * FSqrt)
2118 if (match(X, m_FDiv(m_SpecificFP(-1.0), m_Specific(CI)))) {
2119 Value *Mul = B.CreateFMul(FDiv, FSqrt);
2120 FMul = cast<Instruction>(B.CreateFNeg(Mul));
2121 } else
2122 FMul = cast<Instruction>(B.CreateFMul(FDiv, FSqrt));
2123 FMul->copyMetadata(*X);
2124 FMul->copyFastMathFlags(FastMathFlags::intersectRewrite(R1FMF, R2FMF) |
2125 FastMathFlags::unionValue(R1FMF, R2FMF));
2126 return IC->replaceInstUsesWith(*X, FMul);
2127}
2128
2130 Module *M = I.getModule();
2131
2132 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
2133 I.getFastMathFlags(),
2134 SQ.getWithInstruction(&I)))
2135 return replaceInstUsesWith(I, V);
2136
2138 return X;
2139
2141 return Phi;
2142
2143 if (Instruction *R = foldFDivConstantDivisor(I))
2144 return R;
2145
2147 return R;
2148
2149 if (Instruction *R = foldFPSignBitOps(I))
2150 return R;
2151
2152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2153
2154 // Convert
2155 // x = 1.0/sqrt(a)
2156 // r1 = x * x;
2157 // r2 = a/sqrt(a);
2158 //
2159 // TO
2160 //
2161 // r1 = 1/a
2162 // r2 = sqrt(a)
2163 // x = r1 * r2
2165 if (isFSqrtDivToFMulLegal(&I, R1, R2)) {
2166 CallInst *CI = cast<CallInst>(I.getOperand(1));
2167 if (Instruction *D = convertFSqrtDivIntoFMul(CI, &I, R1, R2, Builder, this))
2168 return D;
2169 }
2170
2171 if (isa<Constant>(Op0))
2173 if (Instruction *R = FoldOpIntoSelect(I, SI))
2174 return R;
2175
2176 if (isa<Constant>(Op1))
2178 if (Instruction *R = FoldOpIntoSelect(I, SI))
2179 return R;
2180
2181 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
2182 Value *X, *Y;
2183 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2184 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
2185 // (X / Y) / Z => X / (Y * Z)
2186 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
2187 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
2188 }
2189 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2190 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
2191 // Z / (X / Y) => (Y * Z) / X
2192 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
2193 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
2194 }
2195 // Z / (1.0 / Y) => (Y * Z)
2196 //
2197 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
2198 // m_OneUse check is avoided because even in the case of the multiple uses
2199 // for 1.0/Y, the number of instructions remain the same and a division is
2200 // replaced by a multiplication.
2201 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
2202 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
2203 }
2204
2205 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
2206 // sin(X) / cos(X) -> tan(X)
2207 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
2208 Value *X;
2209 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
2211 bool IsCot =
2212 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
2214
2215 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
2216 LibFunc_tanf, LibFunc_tanl)) {
2217 IRBuilder<> B(&I);
2219 B.setFastMathFlags(I.getFastMathFlags());
2220 AttributeList Attrs =
2221 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
2222 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
2223 LibFunc_tanl, B, Attrs);
2224 if (IsCot)
2225 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
2226 return replaceInstUsesWith(I, Res);
2227 }
2228 }
2229
2230 // X / (X * Y) --> 1.0 / Y
2231 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
2232 // We can ignore the possibility that X is infinity because INF/INF is NaN.
2233 Value *X, *Y;
2234 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
2235 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
2236 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
2237 replaceOperand(I, 1, Y);
2238 return &I;
2239 }
2240
2241 // X / fabs(X) -> copysign(1.0, X)
2242 // fabs(X) / X -> copysign(1.0, X)
2243 if (I.hasNoNaNs() && I.hasNoInfs() &&
2244 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
2245 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
2246 Value *V = Builder.CreateBinaryIntrinsic(
2247 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
2248 return replaceInstUsesWith(I, V);
2249 }
2250
2252 return Mul;
2253
2255 return Mul;
2256
2257 // pow(X, Y) / X --> pow(X, Y-1)
2258 if (I.hasAllowReassoc() &&
2260 m_Value(Y))))) {
2261 Value *Y1 =
2262 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
2263 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
2264 return replaceInstUsesWith(I, Pow);
2265 }
2266
2267 if (Instruction *FoldedPowi = foldPowiReassoc(I))
2268 return FoldedPowi;
2269
2270 return nullptr;
2271}
2272
2273// Variety of transform for:
2274// (urem/srem (mul X, Y), (mul X, Z))
2275// (urem/srem (shl X, Y), (shl X, Z))
2276// (urem/srem (shl Y, X), (shl Z, X))
2277// NB: The shift cases are really just extensions of the mul case. We treat
2278// shift as Val * (1 << Amt).
2280 InstCombinerImpl &IC) {
2281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
2282 APInt Y, Z;
2283 bool ShiftByX = false;
2284
2285 // If V is not nullptr, it will be matched using m_Specific.
2286 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C,
2287 bool &PreserveNSW) -> bool {
2288 const APInt *Tmp = nullptr;
2289 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
2290 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
2291 C = *Tmp;
2292 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
2293 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp))))) {
2294 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
2295 // We cannot preserve NSW when shifting by BW - 1.
2296 PreserveNSW = Tmp->ult(Tmp->getBitWidth() - 1);
2297 }
2298 if (Tmp != nullptr)
2299 return true;
2300
2301 // Reset `V` so we don't start with specific value on next match attempt.
2302 V = nullptr;
2303 return false;
2304 };
2305
2306 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
2307 const APInt *Tmp = nullptr;
2308 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
2309 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
2310 C = *Tmp;
2311 return true;
2312 }
2313
2314 // Reset `V` so we don't start with specific value on next match attempt.
2315 V = nullptr;
2316 return false;
2317 };
2318
2319 bool Op0PreserveNSW = true, Op1PreserveNSW = true;
2320 if (MatchShiftOrMulXC(Op0, X, Y, Op0PreserveNSW) &&
2321 MatchShiftOrMulXC(Op1, X, Z, Op1PreserveNSW)) {
2322 // pass
2323 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
2324 ShiftByX = true;
2325 } else {
2326 return nullptr;
2327 }
2328
2329 bool IsSRem = I.getOpcode() == Instruction::SRem;
2330
2332 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2333 // Z or Z >= Y.
2334 bool BO0HasNSW = Op0PreserveNSW && BO0->hasNoSignedWrap();
2335 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2336 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2337
2338 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
2339 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2340 // if (rem Y, Z) == 0
2341 // -> 0
2342 if (RemYZ.isZero() && BO0NoWrap)
2343 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
2344
2345 // Helper function to emit either (RemSimplificationC << X) or
2346 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2347 // (shl V, X) or (mul V, X) respectively.
2348 auto CreateMulOrShift =
2349 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2350 Value *RemSimplification =
2351 ConstantInt::get(I.getType(), RemSimplificationC);
2352 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2353 : BinaryOperator::CreateMul(X, RemSimplification);
2354 };
2355
2357 bool BO1HasNSW = Op1PreserveNSW && BO1->hasNoSignedWrap();
2358 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2359 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2360 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2361 // if (rem Y, Z) == Y
2362 // -> (mul nuw/nsw X, Y)
2363 if (RemYZ == Y && BO1NoWrap) {
2364 BinaryOperator *BO = CreateMulOrShift(Y);
2365 // Copy any overflow flags from Op0.
2366 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2367 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2368 return BO;
2369 }
2370
2371 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2372 // if Y >= Z
2373 // -> (mul {nuw} nsw X, (rem Y, Z))
2374 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2375 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2376 BO->setHasNoSignedWrap();
2377 BO->setHasNoUnsignedWrap(BO0HasNUW);
2378 return BO;
2379 }
2380
2381 return nullptr;
2382}
2383
2384/// This function implements the transforms common to both integer remainder
2385/// instructions (urem and srem). It is called by the visitors to those integer
2386/// remainder instructions.
2387/// Common integer remainder transforms
2390 return Res;
2391
2392 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2393
2394 if (isa<Constant>(Op1)) {
2395 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2396 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2397 if (Instruction *R = FoldOpIntoSelect(I, SI))
2398 return R;
2399 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2400 const APInt *Op1Int;
2401 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2402 (I.getOpcode() == Instruction::URem ||
2403 !Op1Int->isMinSignedValue())) {
2404 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2405 // predecessor blocks, so do this only if we know the srem or urem
2406 // will not fault.
2407 if (Instruction *NV = foldOpIntoPhi(I, PN))
2408 return NV;
2409 }
2410 }
2411
2412 // See if we can fold away this rem instruction.
2414 return &I;
2415 }
2416 }
2417
2418 if (Instruction *R = simplifyIRemMulShl(I, *this))
2419 return R;
2420
2421 return nullptr;
2422}
2423
2425 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2426 SQ.getWithInstruction(&I)))
2427 return replaceInstUsesWith(I, V);
2428
2430 return X;
2431
2432 if (Instruction *common = commonIRemTransforms(I))
2433 return common;
2434
2435 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2436 return NarrowRem;
2437
2438 // X urem Y -> X and Y-1, where Y is a power of 2,
2439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2440 Type *Ty = I.getType();
2441 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2442 // This may increase instruction count, we don't enforce that Y is a
2443 // constant.
2445 Value *Add = Builder.CreateAdd(Op1, N1);
2446 return BinaryOperator::CreateAnd(Op0, Add);
2447 }
2448
2449 // 1 urem X -> zext(X != 1)
2450 if (match(Op0, m_One())) {
2451 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2452 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2453 }
2454
2455 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2456 // Op0 must be frozen because we are increasing its number of uses.
2457 if (match(Op1, m_Negative())) {
2458 Value *F0 = Op0;
2459 if (!isGuaranteedNotToBeUndef(Op0))
2460 F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2461 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2462 Value *Sub = Builder.CreateSub(F0, Op1);
2463 return createSelectInstWithUnknownProfile(Cmp, F0, Sub);
2464 }
2465
2466 // If the divisor is a sext of a boolean, then the divisor must be max
2467 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2468 // max unsigned value. In that case, the remainder is 0:
2469 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2470 Value *X;
2471 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2472 Value *FrozenOp0 = Op0;
2473 if (!isGuaranteedNotToBeUndef(Op0))
2474 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2475 Value *Cmp =
2476 Builder.CreateICmpEQ(FrozenOp0, ConstantInt::getAllOnesValue(Ty));
2477 return createSelectInstWithUnknownProfile(
2478 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2479 }
2480
2481 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2482 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2483 Value *Val =
2484 simplifyICmpInst(ICmpInst::ICMP_ULT, X, Op1, SQ.getWithInstruction(&I));
2485 if (Val && match(Val, m_One())) {
2486 Value *FrozenOp0 = Op0;
2487 if (!isGuaranteedNotToBeUndef(Op0))
2488 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2489 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2490 return createSelectInstWithUnknownProfile(
2491 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2492 }
2493 }
2494
2495 return nullptr;
2496}
2497
2499 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2500 SQ.getWithInstruction(&I)))
2501 return replaceInstUsesWith(I, V);
2502
2504 return X;
2505
2506 // Handle the integer rem common cases
2507 if (Instruction *Common = commonIRemTransforms(I))
2508 return Common;
2509
2510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2511 {
2512 const APInt *Y;
2513 // X % -Y -> X % Y
2514 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2515 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2516 }
2517
2518 // -X srem Y --> -(X srem Y)
2519 Value *X, *Y;
2521 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
2522
2523 // If the sign bits of both operands are zero (i.e. we can prove they are
2524 // unsigned inputs), turn this into a urem.
2525 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2526 if (MaskedValueIsZero(Op1, Mask, &I) && MaskedValueIsZero(Op0, Mask, &I)) {
2527 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2528 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2529 }
2530
2531 // If it's a constant vector, flip any negative values positive.
2533 Constant *C = cast<Constant>(Op1);
2534 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2535
2536 bool hasNegative = false;
2537 bool hasMissing = false;
2538 for (unsigned i = 0; i != VWidth; ++i) {
2539 Constant *Elt = C->getAggregateElement(i);
2540 if (!Elt) {
2541 hasMissing = true;
2542 break;
2543 }
2544
2545 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2546 if (RHS->isNegative())
2547 hasNegative = true;
2548 }
2549
2550 if (hasNegative && !hasMissing) {
2551 SmallVector<Constant *, 16> Elts(VWidth);
2552 for (unsigned i = 0; i != VWidth; ++i) {
2553 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2555 if (RHS->isNegative())
2557 }
2558 }
2559
2560 Constant *NewRHSV = ConstantVector::get(Elts);
2561 if (NewRHSV != C) // Don't loop on -MININT
2562 return replaceOperand(I, 1, NewRHSV);
2563 }
2564 }
2565
2566 return nullptr;
2567}
2568
2570 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2571 I.getFastMathFlags(),
2572 SQ.getWithInstruction(&I)))
2573 return replaceInstUsesWith(I, V);
2574
2576 return X;
2577
2579 return Phi;
2580
2581 return nullptr;
2582}
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:1512
bool isZero() const
Definition APFloat.h:1508
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1982
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1584
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1769
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:1549
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1901
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:1497
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:1648
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:2016
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1540
unsigned logBase2() const
Definition APInt.h:1770
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
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:1424
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1496
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1712
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:2776
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.
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:207
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:255
Matching combinators.