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