LLVM 17.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"
19#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
29#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
35#include <cassert>
36
37#define DEBUG_TYPE "instcombine"
39
40using namespace llvm;
41using namespace PatternMatch;
42
43/// The specific integer value is used in a context where it is known to be
44/// non-zero. If this allows us to simplify the computation, do so and return
45/// the new operand, otherwise return null.
47 Instruction &CxtI) {
48 // If V has multiple uses, then we would have to do more analysis to determine
49 // if this is safe. For example, the use could be in dynamically unreached
50 // code.
51 if (!V->hasOneUse()) return nullptr;
52
53 bool MadeChange = false;
54
55 // ((1 << A) >>u B) --> (1 << (A-B))
56 // Because V cannot be zero, we know that B is less than A.
57 Value *A = nullptr, *B = nullptr, *One = nullptr;
58 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
59 match(One, m_One())) {
60 A = IC.Builder.CreateSub(A, B);
61 return IC.Builder.CreateShl(One, A);
62 }
63
64 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
65 // inexact. Similarly for <<.
66 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
67 if (I && I->isLogicalShift() &&
68 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
69 // We know that this is an exact/nuw shift and that the input is a
70 // non-zero context as well.
71 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
72 IC.replaceOperand(*I, 0, V2);
73 MadeChange = true;
74 }
75
76 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
77 I->setIsExact();
78 MadeChange = true;
79 }
80
81 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
82 I->setHasNoUnsignedWrap();
83 MadeChange = true;
84 }
85 }
86
87 // TODO: Lots more we could do here:
88 // If V is a phi node, we can call this on each of its operands.
89 // "select cond, X, 0" can simplify to "X".
90
91 return MadeChange ? V : nullptr;
92}
93
94// TODO: This is a specific form of a much more general pattern.
95// We could detect a select with any binop identity constant, or we
96// could use SimplifyBinOp to see if either arm of the select reduces.
97// But that needs to be done carefully and/or while removing potential
98// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
100 InstCombiner::BuilderTy &Builder) {
101 Value *Cond, *OtherOp;
102
103 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
104 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
106 m_Value(OtherOp)))) {
107 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
108 Value *Neg = Builder.CreateNeg(OtherOp, "", false, HasAnyNoWrap);
109 return Builder.CreateSelect(Cond, OtherOp, Neg);
110 }
111 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
112 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
114 m_Value(OtherOp)))) {
115 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
116 Value *Neg = Builder.CreateNeg(OtherOp, "", false, HasAnyNoWrap);
117 return Builder.CreateSelect(Cond, Neg, OtherOp);
118 }
119
120 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
121 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
123 m_SpecificFP(-1.0))),
124 m_Value(OtherOp)))) {
126 Builder.setFastMathFlags(I.getFastMathFlags());
127 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
128 }
129
130 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
131 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
133 m_SpecificFP(1.0))),
134 m_Value(OtherOp)))) {
136 Builder.setFastMathFlags(I.getFastMathFlags());
137 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
138 }
139
140 return nullptr;
141}
142
143/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
144/// Callers are expected to call this twice to handle commuted patterns.
145static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
146 InstCombiner::BuilderTy &Builder) {
147 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
148 if (CommuteOperands)
149 std::swap(X, Y);
150
151 const bool HasNSW = Mul.hasNoSignedWrap();
152 const bool HasNUW = Mul.hasNoUnsignedWrap();
153
154 // X * (1 << Z) --> X << Z
155 Value *Z;
156 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
157 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
158 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
159 }
160
161 // Similar to above, but an increment of the shifted value becomes an add:
162 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
163 // This increases uses of X, so it may require a freeze, but that is still
164 // expected to be an improvement because it removes the multiply.
165 BinaryOperator *Shift;
166 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
167 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
168 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
169 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
170 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
171 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
172 }
173
174 // Similar to above, but a decrement of the shifted value is disguised as
175 // 'not' and becomes a sub:
176 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
177 // This increases uses of X, so it may require a freeze, but that is still
178 // expected to be an improvement because it removes the multiply.
180 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
181 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
182 return Builder.CreateSub(Shl, FrX, Mul.getName());
183 }
184
185 return nullptr;
186}
187
189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
190 if (Value *V =
191 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
193 return replaceInstUsesWith(I, V);
194
196 return &I;
197
199 return X;
200
202 return Phi;
203
205 return replaceInstUsesWith(I, V);
206
207 Type *Ty = I.getType();
208 const unsigned BitWidth = Ty->getScalarSizeInBits();
209 const bool HasNSW = I.hasNoSignedWrap();
210 const bool HasNUW = I.hasNoUnsignedWrap();
211
212 // X * -1 --> 0 - X
213 if (match(Op1, m_AllOnes())) {
214 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
216 }
217
218 // Also allow combining multiply instructions on vectors.
219 {
220 Value *NewOp;
221 Constant *C1, *C2;
222 const APInt *IVal;
223 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
224 m_Constant(C1))) &&
225 match(C1, m_APInt(IVal))) {
226 // ((X << C2)*C1) == (X * (C1 << C2))
227 Constant *Shl = ConstantExpr::getShl(C1, C2);
228 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
229 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
230 if (HasNUW && Mul->hasNoUnsignedWrap())
232 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
233 BO->setHasNoSignedWrap();
234 return BO;
235 }
236
237 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
238 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
239 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C1)) {
240 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
241
242 if (HasNUW)
244 if (HasNSW) {
245 const APInt *V;
246 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
247 Shl->setHasNoSignedWrap();
248 }
249
250 return Shl;
251 }
252 }
253 }
254
255 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
256 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
257 // The "* (1<<C)" thus becomes a potential shifting opportunity.
258 if (Value *NegOp0 = Negator::Negate(/*IsNegation*/ true, Op0, *this))
259 return BinaryOperator::CreateMul(
260 NegOp0, ConstantExpr::getNeg(cast<Constant>(Op1)), I.getName());
261
262 // Try to convert multiply of extended operand to narrow negate and shift
263 // for better analysis.
264 // This is valid if the shift amount (trailing zeros in the multiplier
265 // constant) clears more high bits than the bitwidth difference between
266 // source and destination types:
267 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
268 const APInt *NegPow2C;
269 Value *X;
270 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
271 match(Op1, m_APIntAllowUndef(NegPow2C))) {
272 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
273 unsigned ShiftAmt = NegPow2C->countr_zero();
274 if (ShiftAmt >= BitWidth - SrcWidth) {
275 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
276 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
277 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
278 }
279 }
280 }
281
282 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
283 return FoldedMul;
284
285 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
286 return replaceInstUsesWith(I, FoldedMul);
287
288 // Simplify mul instructions with a constant RHS.
289 Constant *MulC;
290 if (match(Op1, m_ImmConstant(MulC))) {
291 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
292 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
293 Value *X;
294 Constant *C1;
295 if ((match(Op0, m_OneUse(m_Add(m_Value(X), m_ImmConstant(C1))))) ||
296 (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C1)))) &&
297 haveNoCommonBitsSet(X, C1, DL, &AC, &I, &DT))) {
298 // C1*MulC simplifies to a tidier constant.
299 Value *NewC = Builder.CreateMul(C1, MulC);
300 auto *BOp0 = cast<BinaryOperator>(Op0);
301 bool Op0NUW =
302 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
303 Value *NewMul = Builder.CreateMul(X, MulC);
304 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
305 if (HasNUW && Op0NUW) {
306 // If NewMulBO is constant we also can set BO to nuw.
307 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
308 NewMulBO->setHasNoUnsignedWrap();
309 BO->setHasNoUnsignedWrap();
310 }
311 return BO;
312 }
313 }
314
315 // abs(X) * abs(X) -> X * X
316 // nabs(X) * nabs(X) -> X * X
317 if (Op0 == Op1) {
318 Value *X, *Y;
320 if (SPF == SPF_ABS || SPF == SPF_NABS)
321 return BinaryOperator::CreateMul(X, X);
322
323 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
324 return BinaryOperator::CreateMul(X, X);
325 }
326
327 // -X * C --> X * -C
328 Value *X, *Y;
329 Constant *Op1C;
330 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
331 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
332
333 // -X * -Y --> X * Y
334 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
335 auto *NewMul = BinaryOperator::CreateMul(X, Y);
336 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
337 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
338 NewMul->setHasNoSignedWrap();
339 return NewMul;
340 }
341
342 // -X * Y --> -(X * Y)
343 // X * -Y --> -(X * Y)
346
347 // (X / Y) * Y = X - (X % Y)
348 // (X / Y) * -Y = (X % Y) - X
349 {
350 Value *Y = Op1;
351 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
352 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
353 Div->getOpcode() != Instruction::SDiv)) {
354 Y = Op0;
355 Div = dyn_cast<BinaryOperator>(Op1);
356 }
357 Value *Neg = dyn_castNegVal(Y);
358 if (Div && Div->hasOneUse() &&
359 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
360 (Div->getOpcode() == Instruction::UDiv ||
361 Div->getOpcode() == Instruction::SDiv)) {
362 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
363
364 // If the division is exact, X % Y is zero, so we end up with X or -X.
365 if (Div->isExact()) {
366 if (DivOp1 == Y)
367 return replaceInstUsesWith(I, X);
369 }
370
371 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
372 : Instruction::SRem;
373 // X must be frozen because we are increasing its number of uses.
374 Value *XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
375 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
376 if (DivOp1 == Y)
377 return BinaryOperator::CreateSub(XFreeze, Rem);
378 return BinaryOperator::CreateSub(Rem, XFreeze);
379 }
380 }
381
382 // Fold the following two scenarios:
383 // 1) i1 mul -> i1 and.
384 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
385 // Note: We could use known bits to generalize this and related patterns with
386 // shifts/truncs
387 if (Ty->isIntOrIntVectorTy(1) ||
388 (match(Op0, m_And(m_Value(), m_One())) &&
389 match(Op1, m_And(m_Value(), m_One()))))
390 return BinaryOperator::CreateAnd(Op0, Op1);
391
392 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
393 return replaceInstUsesWith(I, R);
394 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
395 return replaceInstUsesWith(I, R);
396
397 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
398 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
399 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
400 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
401 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
402 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
403 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
404 Value *And = Builder.CreateAnd(X, Y, "mulbool");
405 return CastInst::Create(Instruction::ZExt, And, Ty);
406 }
407 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
408 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
409 // Note: -1 * 1 == 1 * -1 == -1
410 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
411 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
412 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
413 (Op0->hasOneUse() || Op1->hasOneUse())) {
414 Value *And = Builder.CreateAnd(X, Y, "mulbool");
415 return CastInst::Create(Instruction::SExt, And, Ty);
416 }
417
418 // (zext bool X) * Y --> X ? Y : 0
419 // Y * (zext bool X) --> X ? Y : 0
420 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
422 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
424
425 Constant *ImmC;
426 if (match(Op1, m_ImmConstant(ImmC))) {
427 // (sext bool X) * C --> X ? -C : 0
428 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
429 Constant *NegC = ConstantExpr::getNeg(ImmC);
431 }
432
433 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
434 const APInt *C;
435 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
436 *C == C->getBitWidth() - 1) {
437 Constant *NegC = ConstantExpr::getNeg(ImmC);
438 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
439 return SelectInst::Create(IsNeg, NegC, ConstantInt::getNullValue(Ty));
440 }
441 }
442
443 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
444 // TODO: We are not checking one-use because the elimination of the multiply
445 // is better for analysis?
446 const APInt *C;
447 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
448 *C == C->getBitWidth() - 1) {
449 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
451 }
452
453 // (and X, 1) * Y --> (trunc X) ? Y : 0
454 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
457 }
458
459 // ((ashr X, 31) | 1) * X --> abs(X)
460 // X * ((ashr X, 31) | 1) --> abs(X)
463 m_One()),
464 m_Deferred(X)))) {
466 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
467 Abs->takeName(&I);
468 return replaceInstUsesWith(I, Abs);
469 }
470
471 if (Instruction *Ext = narrowMathIfNoOverflow(I))
472 return Ext;
473
474 bool Changed = false;
475 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
476 Changed = true;
477 I.setHasNoSignedWrap(true);
478 }
479
480 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I)) {
481 Changed = true;
482 I.setHasNoUnsignedWrap(true);
483 }
484
485 return Changed ? &I : nullptr;
486}
487
488Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
489 BinaryOperator::BinaryOps Opcode = I.getOpcode();
490 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
491 "Expected fmul or fdiv");
492
493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
494 Value *X, *Y;
495
496 // -X * -Y --> X * Y
497 // -X / -Y --> X / Y
498 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
499 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
500
501 // fabs(X) * fabs(X) -> X * X
502 // fabs(X) / fabs(X) -> X / X
503 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
504 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
505
506 // fabs(X) * fabs(Y) --> fabs(X * Y)
507 // fabs(X) / fabs(Y) --> fabs(X / Y)
508 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
509 (Op0->hasOneUse() || Op1->hasOneUse())) {
511 Builder.setFastMathFlags(I.getFastMathFlags());
512 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
513 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
514 Fabs->takeName(&I);
515 return replaceInstUsesWith(I, Fabs);
516 }
517
518 return nullptr;
519}
520
522 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
523 I.getFastMathFlags(),
525 return replaceInstUsesWith(I, V);
526
528 return &I;
529
531 return X;
532
534 return Phi;
535
536 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
537 return FoldedMul;
538
539 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
540 return replaceInstUsesWith(I, FoldedMul);
541
542 if (Instruction *R = foldFPSignBitOps(I))
543 return R;
544
545 // X * -1.0 --> -X
546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
547 if (match(Op1, m_SpecificFP(-1.0)))
548 return UnaryOperator::CreateFNegFMF(Op0, &I);
549
550 // With no-nans: X * 0.0 --> copysign(0.0, X)
551 if (I.hasNoNaNs() && match(Op1, m_PosZeroFP())) {
552 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
553 {I.getType()}, {Op1, Op0}, &I);
554 return replaceInstUsesWith(I, CopySign);
555 }
556
557 // -X * C --> X * -C
558 Value *X, *Y;
559 Constant *C;
560 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
561 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
562 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
563
564 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
565 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
566 return replaceInstUsesWith(I, V);
567
568 if (I.hasAllowReassoc()) {
569 // Reassociate constant RHS with another constant to form constant
570 // expression.
571 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
572 Constant *C1;
573 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
574 // (C1 / X) * C --> (C * C1) / X
575 Constant *CC1 =
576 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
577 if (CC1 && CC1->isNormalFP())
578 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
579 }
580 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
581 // (X / C1) * C --> X * (C / C1)
582 Constant *CDivC1 =
583 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
584 if (CDivC1 && CDivC1->isNormalFP())
585 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
586
587 // If the constant was a denormal, try reassociating differently.
588 // (X / C1) * C --> X / (C1 / C)
589 Constant *C1DivC =
590 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
591 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
592 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
593 }
594
595 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
596 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
597 // further folds and (X * C) + C2 is 'fma'.
598 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
599 // (X + C1) * C --> (X * C) + (C * C1)
601 Instruction::FMul, C, C1, DL)) {
602 Value *XC = Builder.CreateFMulFMF(X, C, &I);
603 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
604 }
605 }
606 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
607 // (C1 - X) * C --> (C * C1) - (X * C)
609 Instruction::FMul, C, C1, DL)) {
610 Value *XC = Builder.CreateFMulFMF(X, C, &I);
611 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
612 }
613 }
614 }
615
616 Value *Z;
618 m_Value(Z)))) {
619 // Sink division: (X / Y) * Z --> (X * Z) / Y
620 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
621 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
622 }
623
624 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
625 // nnan disallows the possibility of returning a number if both operands are
626 // negative (in that case, we should return NaN).
627 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
628 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
629 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
630 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
631 return replaceInstUsesWith(I, Sqrt);
632 }
633
634 // The following transforms are done irrespective of the number of uses
635 // for the expression "1.0/sqrt(X)".
636 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
637 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
638 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
639 // has the necessary (reassoc) fast-math-flags.
640 if (I.hasNoSignedZeros() &&
641 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
642 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
644 if (I.hasNoSignedZeros() &&
645 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
646 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
648
649 // Like the similar transform in instsimplify, this requires 'nsz' because
650 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
651 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
652 Op0->hasNUses(2)) {
653 // Peek through fdiv to find squaring of square root:
654 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
655 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
656 Value *XX = Builder.CreateFMulFMF(X, X, &I);
657 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
658 }
659 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
660 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
661 Value *XX = Builder.CreateFMulFMF(X, X, &I);
662 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
663 }
664 }
665
666 // pow(X, Y) * X --> pow(X, Y+1)
667 // X * pow(X, Y) --> pow(X, Y+1)
668 if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Value(X),
669 m_Value(Y))),
670 m_Deferred(X)))) {
671 Value *Y1 =
672 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
673 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
674 return replaceInstUsesWith(I, Pow);
675 }
676
677 if (I.isOnlyUserOfAnyOperand()) {
678 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
679 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
680 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) {
681 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
682 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
683 return replaceInstUsesWith(I, NewPow);
684 }
685 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
686 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
687 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Value(Z), m_Specific(Y)))) {
688 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
689 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
690 return replaceInstUsesWith(I, NewPow);
691 }
692
693 // powi(x, y) * powi(x, z) -> powi(x, y + z)
694 if (match(Op0, m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y))) &&
695 match(Op1, m_Intrinsic<Intrinsic::powi>(m_Specific(X), m_Value(Z))) &&
696 Y->getType() == Z->getType()) {
697 auto *YZ = Builder.CreateAdd(Y, Z);
698 auto *NewPow = Builder.CreateIntrinsic(
699 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
700 return replaceInstUsesWith(I, NewPow);
701 }
702
703 // exp(X) * exp(Y) -> exp(X + Y)
704 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
705 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) {
706 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
707 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
708 return replaceInstUsesWith(I, Exp);
709 }
710
711 // exp2(X) * exp2(Y) -> exp2(X + Y)
712 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
713 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) {
714 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
715 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
716 return replaceInstUsesWith(I, Exp2);
717 }
718 }
719
720 // (X*Y) * X => (X*X) * Y where Y != X
721 // The purpose is two-fold:
722 // 1) to form a power expression (of X).
723 // 2) potentially shorten the critical path: After transformation, the
724 // latency of the instruction Y is amortized by the expression of X*X,
725 // and therefore Y is in a "less critical" position compared to what it
726 // was before the transformation.
727 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
728 Op1 != Y) {
729 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
730 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
731 }
732 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
733 Op0 != Y) {
734 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
735 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
736 }
737 }
738
739 // log2(X * 0.5) * Y = log2(X) * Y - Y
740 if (I.isFast()) {
741 IntrinsicInst *Log2 = nullptr;
742 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
743 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
744 Log2 = cast<IntrinsicInst>(Op0);
745 Y = Op1;
746 }
747 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
748 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
749 Log2 = cast<IntrinsicInst>(Op1);
750 Y = Op0;
751 }
752 if (Log2) {
753 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
754 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
755 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
756 }
757 }
758
759 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
760 // Given a phi node with entry value as 0 and it used in fmul operation,
761 // we can replace fmul with 0 safely and eleminate loop operation.
762 PHINode *PN = nullptr;
763 Value *Start = nullptr, *Step = nullptr;
764 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
765 I.hasNoSignedZeros() && match(Start, m_Zero()))
766 return replaceInstUsesWith(I, Start);
767
768 return nullptr;
769}
770
771/// Fold a divide or remainder with a select instruction divisor when one of the
772/// select operands is zero. In that case, we can use the other select operand
773/// because div/rem by zero is undefined.
775 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
776 if (!SI)
777 return false;
778
779 int NonNullOperand;
780 if (match(SI->getTrueValue(), m_Zero()))
781 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
782 NonNullOperand = 2;
783 else if (match(SI->getFalseValue(), m_Zero()))
784 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
785 NonNullOperand = 1;
786 else
787 return false;
788
789 // Change the div/rem to use 'Y' instead of the select.
790 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
791
792 // Okay, we know we replace the operand of the div/rem with 'Y' with no
793 // problem. However, the select, or the condition of the select may have
794 // multiple uses. Based on our knowledge that the operand must be non-zero,
795 // propagate the known value for the select into other uses of it, and
796 // propagate a known value of the condition into its other users.
797
798 // If the select and condition only have a single use, don't bother with this,
799 // early exit.
800 Value *SelectCond = SI->getCondition();
801 if (SI->use_empty() && SelectCond->hasOneUse())
802 return true;
803
804 // Scan the current block backward, looking for other uses of SI.
805 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
806 Type *CondTy = SelectCond->getType();
807 while (BBI != BBFront) {
808 --BBI;
809 // If we found an instruction that we can't assume will return, so
810 // information from below it cannot be propagated above it.
812 break;
813
814 // Replace uses of the select or its condition with the known values.
815 for (Use &Op : BBI->operands()) {
816 if (Op == SI) {
817 replaceUse(Op, SI->getOperand(NonNullOperand));
818 Worklist.push(&*BBI);
819 } else if (Op == SelectCond) {
820 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
821 : ConstantInt::getFalse(CondTy));
822 Worklist.push(&*BBI);
823 }
824 }
825
826 // If we past the instruction, quit looking for it.
827 if (&*BBI == SI)
828 SI = nullptr;
829 if (&*BBI == SelectCond)
830 SelectCond = nullptr;
831
832 // If we ran out of things to eliminate, break out of the loop.
833 if (!SelectCond && !SI)
834 break;
835
836 }
837 return true;
838}
839
840/// True if the multiply can not be expressed in an int this size.
841static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
842 bool IsSigned) {
843 bool Overflow;
844 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
845 return Overflow;
846}
847
848/// True if C1 is a multiple of C2. Quotient contains C1/C2.
849static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
850 bool IsSigned) {
851 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
852
853 // Bail if we will divide by zero.
854 if (C2.isZero())
855 return false;
856
857 // Bail if we would divide INT_MIN by -1.
858 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
859 return false;
860
861 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
862 if (IsSigned)
863 APInt::sdivrem(C1, C2, Quotient, Remainder);
864 else
865 APInt::udivrem(C1, C2, Quotient, Remainder);
866
867 return Remainder.isMinValue();
868}
869
871 InstCombiner::BuilderTy &Builder) {
872 assert((I.getOpcode() == Instruction::SDiv ||
873 I.getOpcode() == Instruction::UDiv) &&
874 "Expected integer divide");
875
876 bool IsSigned = I.getOpcode() == Instruction::SDiv;
877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
878 Type *Ty = I.getType();
879
880 Instruction *Ret = nullptr;
881 Value *X, *Y, *Z;
882
883 // With appropriate no-wrap constraints, remove a common factor in the
884 // dividend and divisor that is disguised as a left-shifted value.
885 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
886 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
887 // Both operands must have the matching no-wrap for this kind of division.
888 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
889 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
890 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
891 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
892
893 // (X * Y) u/ (X << Z) --> Y u>> Z
894 if (!IsSigned && HasNUW)
895 Ret = BinaryOperator::CreateLShr(Y, Z);
896
897 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
898 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
899 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
900 Ret = BinaryOperator::CreateSDiv(Y, Shl);
901 }
902 }
903
904 // With appropriate no-wrap constraints, remove a common factor in the
905 // dividend and divisor that is disguised as a left-shift amount.
906 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
907 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
908 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
909 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
910
911 // For unsigned div, we need 'nuw' on both shifts or
912 // 'nsw' on both shifts + 'nuw' on the dividend.
913 // (X << Z) / (Y << Z) --> X / Y
914 if (!IsSigned &&
915 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
916 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
917 Shl1->hasNoSignedWrap())))
918 Ret = BinaryOperator::CreateUDiv(X, Y);
919
920 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
921 // (X << Z) / (Y << Z) --> X / Y
922 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
923 Shl1->hasNoUnsignedWrap())
924 Ret = BinaryOperator::CreateSDiv(X, Y);
925 }
926
927 if (!Ret)
928 return nullptr;
929
930 Ret->setIsExact(I.isExact());
931 return Ret;
932}
933
934/// This function implements the transforms common to both integer division
935/// instructions (udiv and sdiv). It is called by the visitors to those integer
936/// division instructions.
937/// Common integer divide transforms
940 return Phi;
941
942 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
943 bool IsSigned = I.getOpcode() == Instruction::SDiv;
944 Type *Ty = I.getType();
945
946 // The RHS is known non-zero.
947 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
948 return replaceOperand(I, 1, V);
949
950 // Handle cases involving: [su]div X, (select Cond, Y, Z)
951 // This does not apply for fdiv.
953 return &I;
954
955 // If the divisor is a select-of-constants, try to constant fold all div ops:
956 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC)
957 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
958 if (match(Op0, m_ImmConstant()) &&
960 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
961 /*FoldWithMultiUse*/ true))
962 return R;
963 }
964
965 const APInt *C2;
966 if (match(Op1, m_APInt(C2))) {
967 Value *X;
968 const APInt *C1;
969
970 // (X / C1) / C2 -> X / (C1*C2)
971 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
972 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
973 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
974 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
975 return BinaryOperator::Create(I.getOpcode(), X,
976 ConstantInt::get(Ty, Product));
977 }
978
979 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
980 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
981 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
982
983 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
984 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
985 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
986 ConstantInt::get(Ty, Quotient));
987 NewDiv->setIsExact(I.isExact());
988 return NewDiv;
989 }
990
991 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
992 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
993 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
994 ConstantInt::get(Ty, Quotient));
995 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
996 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
997 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
998 return Mul;
999 }
1000 }
1001
1002 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1003 C1->ult(C1->getBitWidth() - 1)) ||
1004 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1005 C1->ult(C1->getBitWidth()))) {
1006 APInt C1Shifted = APInt::getOneBitSet(
1007 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1008
1009 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1010 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1011 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1012 ConstantInt::get(Ty, Quotient));
1013 BO->setIsExact(I.isExact());
1014 return BO;
1015 }
1016
1017 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1018 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1019 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1020 ConstantInt::get(Ty, Quotient));
1021 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1022 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1023 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1024 return Mul;
1025 }
1026 }
1027
1028 // Distribute div over add to eliminate a matching div/mul pair:
1029 // ((X * C2) + C1) / C2 --> X + C1/C2
1030 // We need a multiple of the divisor for a signed add constant, but
1031 // unsigned is fine with any constant pair.
1032 if (IsSigned &&
1034 m_APInt(C1))) &&
1035 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1036 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1037 }
1038 if (!IsSigned &&
1040 m_APInt(C1)))) {
1041 return BinaryOperator::CreateNUWAdd(X,
1042 ConstantInt::get(Ty, C1->udiv(*C2)));
1043 }
1044
1045 if (!C2->isZero()) // avoid X udiv 0
1046 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1047 return FoldedDiv;
1048 }
1049
1050 if (match(Op0, m_One())) {
1051 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1052 if (IsSigned) {
1053 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1054 // (Op1 + 1) u< 3 ? Op1 : 0
1055 // Op1 must be frozen because we are increasing its number of uses.
1056 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1057 Value *Inc = Builder.CreateAdd(F1, Op0);
1058 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1059 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1060 } else {
1061 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1062 // result is one, otherwise it's zero.
1063 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1064 }
1065 }
1066
1067 // See if we can fold away this div instruction.
1069 return &I;
1070
1071 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1072 Value *X, *Z;
1073 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1074 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1075 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1076 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1077
1078 // (X << Y) / X -> 1 << Y
1079 Value *Y;
1080 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1081 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1082 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1083 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1084
1085 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1086 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1087 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1088 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1089 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1090 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1091 replaceOperand(I, 1, Y);
1092 return &I;
1093 }
1094 }
1095
1096 // (X << Z) / (X * Y) -> (1 << Z) / Y
1097 // TODO: Handle sdiv.
1098 if (!IsSigned && Op1->hasOneUse() &&
1099 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1100 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1101 if (cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap()) {
1102 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1103 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1104 NewDiv->setIsExact(I.isExact());
1105 return NewDiv;
1106 }
1107
1108 if (Instruction *R = foldIDivShl(I, Builder))
1109 return R;
1110
1111 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1112 // after peeking through another divide:
1113 // ((Op1 * X) / Y) / Op1 --> X / Y
1114 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1115 m_Value(Y)))) {
1116 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1117 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1118 Instruction *NewDiv = nullptr;
1119 if (!IsSigned && Mul->hasNoUnsignedWrap())
1120 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1121 else if (IsSigned && Mul->hasNoSignedWrap())
1122 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1123
1124 // Exact propagates only if both of the original divides are exact.
1125 if (NewDiv) {
1126 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1127 return NewDiv;
1128 }
1129 }
1130
1131 return nullptr;
1132}
1133
1134static const unsigned MaxDepth = 6;
1135
1136// Take the exact integer log2 of the value. If DoFold is true, create the
1137// actual instructions, otherwise return a non-null dummy value. Return nullptr
1138// on failure.
1139static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
1140 bool DoFold) {
1141 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1142 if (!DoFold)
1143 return reinterpret_cast<Value *>(-1);
1144 return Fn();
1145 };
1146
1147 // FIXME: assert that Op1 isn't/doesn't contain undef.
1148
1149 // log2(2^C) -> C
1150 if (match(Op, m_Power2()))
1151 return IfFold([&]() {
1152 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op));
1153 if (!C)
1154 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1155 return C;
1156 });
1157
1158 // The remaining tests are all recursive, so bail out if we hit the limit.
1159 if (Depth++ == MaxDepth)
1160 return nullptr;
1161
1162 // log2(zext X) -> zext log2(X)
1163 // FIXME: Require one use?
1164 Value *X, *Y;
1165 if (match(Op, m_ZExt(m_Value(X))))
1166 if (Value *LogX = takeLog2(Builder, X, Depth, DoFold))
1167 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1168
1169 // log2(X << Y) -> log2(X) + Y
1170 // FIXME: Require one use unless X is 1?
1171 if (match(Op, m_Shl(m_Value(X), m_Value(Y))))
1172 if (Value *LogX = takeLog2(Builder, X, Depth, DoFold))
1173 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1174
1175 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1176 // FIXME: missed optimization: if one of the hands of select is/contains
1177 // undef, just directly pick the other one.
1178 // FIXME: can both hands contain undef?
1179 // FIXME: Require one use?
1180 if (SelectInst *SI = dyn_cast<SelectInst>(Op))
1181 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth, DoFold))
1182 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth, DoFold))
1183 return IfFold([&]() {
1184 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1185 });
1186
1187 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1188 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1189 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op);
1190 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned())
1191 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth, DoFold))
1192 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth, DoFold))
1193 return IfFold([&]() {
1194 return Builder.CreateBinaryIntrinsic(
1195 MinMax->getIntrinsicID(), LogX, LogY);
1196 });
1197
1198 return nullptr;
1199}
1200
1201/// If we have zero-extended operands of an unsigned div or rem, we may be able
1202/// to narrow the operation (sink the zext below the math).
1204 InstCombiner::BuilderTy &Builder) {
1205 Instruction::BinaryOps Opcode = I.getOpcode();
1206 Value *N = I.getOperand(0);
1207 Value *D = I.getOperand(1);
1208 Type *Ty = I.getType();
1209 Value *X, *Y;
1210 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1211 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1212 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1213 // urem (zext X), (zext Y) --> zext (urem X, Y)
1214 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1215 return new ZExtInst(NarrowOp, Ty);
1216 }
1217
1218 Constant *C;
1219 if (isa<Instruction>(N) && match(N, m_OneUse(m_ZExt(m_Value(X)))) &&
1220 match(D, m_Constant(C))) {
1221 // If the constant is the same in the smaller type, use the narrow version.
1222 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1223 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1224 return nullptr;
1225
1226 // udiv (zext X), C --> zext (udiv X, C')
1227 // urem (zext X), C --> zext (urem X, C')
1228 return new ZExtInst(Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1229 }
1230 if (isa<Instruction>(D) && match(D, m_OneUse(m_ZExt(m_Value(X)))) &&
1231 match(N, m_Constant(C))) {
1232 // If the constant is the same in the smaller type, use the narrow version.
1233 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1234 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1235 return nullptr;
1236
1237 // udiv C, (zext X) --> zext (udiv C', X)
1238 // urem C, (zext X) --> zext (urem C', X)
1239 return new ZExtInst(Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1240 }
1241
1242 return nullptr;
1243}
1244
1246 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1248 return replaceInstUsesWith(I, V);
1249
1251 return X;
1252
1253 // Handle the integer div common cases
1254 if (Instruction *Common = commonIDivTransforms(I))
1255 return Common;
1256
1257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1258 Value *X;
1259 const APInt *C1, *C2;
1260 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1261 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1262 bool Overflow;
1263 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1264 if (!Overflow) {
1265 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1266 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1267 X, ConstantInt::get(X->getType(), C2ShlC1));
1268 if (IsExact)
1269 BO->setIsExact();
1270 return BO;
1271 }
1272 }
1273
1274 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1275 // TODO: Could use isKnownNegative() to handle non-constant values.
1276 Type *Ty = I.getType();
1277 if (match(Op1, m_Negative())) {
1278 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1279 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1280 }
1281 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1282 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1284 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1285 }
1286
1287 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1288 return NarrowDiv;
1289
1290 // If the udiv operands are non-overflowing multiplies with a common operand,
1291 // then eliminate the common factor:
1292 // (A * B) / (A * X) --> B / X (and commuted variants)
1293 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1294 // TODO: If -reassociation handled this generally, we could remove this.
1295 Value *A, *B;
1296 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1297 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1298 match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1299 return BinaryOperator::CreateUDiv(B, X);
1300 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1301 match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1302 return BinaryOperator::CreateUDiv(A, X);
1303 }
1304
1305 // Look through a right-shift to find the common factor:
1306 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1307 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1308 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1309 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1310 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1311 Lshr->setIsExact();
1312 return Lshr;
1313 }
1314
1315 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
1316 if (takeLog2(Builder, Op1, /*Depth*/0, /*DoFold*/false)) {
1317 Value *Res = takeLog2(Builder, Op1, /*Depth*/0, /*DoFold*/true);
1318 return replaceInstUsesWith(
1319 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1320 }
1321
1322 return nullptr;
1323}
1324
1326 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1328 return replaceInstUsesWith(I, V);
1329
1331 return X;
1332
1333 // Handle the integer div common cases
1334 if (Instruction *Common = commonIDivTransforms(I))
1335 return Common;
1336
1337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1338 Type *Ty = I.getType();
1339 Value *X;
1340 // sdiv Op0, -1 --> -Op0
1341 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1342 if (match(Op1, m_AllOnes()) ||
1343 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1344 return BinaryOperator::CreateNeg(Op0);
1345
1346 // X / INT_MIN --> X == INT_MIN
1347 if (match(Op1, m_SignMask()))
1348 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1349
1350 if (I.isExact()) {
1351 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1352 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1353 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
1354 return BinaryOperator::CreateExactAShr(Op0, C);
1355 }
1356
1357 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1358 Value *ShAmt;
1359 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1360 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1361
1362 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1363 if (match(Op1, m_NegatedPower2())) {
1364 Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
1366 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1367 return BinaryOperator::CreateNeg(Ashr);
1368 }
1369 }
1370
1371 const APInt *Op1C;
1372 if (match(Op1, m_APInt(Op1C))) {
1373 // If the dividend is sign-extended and the constant divisor is small enough
1374 // to fit in the source type, shrink the division to the narrower type:
1375 // (sext X) sdiv C --> sext (X sdiv C)
1376 Value *Op0Src;
1377 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1378 Op0Src->getType()->getScalarSizeInBits() >=
1379 Op1C->getSignificantBits()) {
1380
1381 // In the general case, we need to make sure that the dividend is not the
1382 // minimum signed value because dividing that by -1 is UB. But here, we
1383 // know that the -1 divisor case is already handled above.
1384
1385 Constant *NarrowDivisor =
1386 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1387 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1388 return new SExtInst(NarrowOp, Ty);
1389 }
1390
1391 // -X / C --> X / -C (if the negation doesn't overflow).
1392 // TODO: This could be enhanced to handle arbitrary vector constants by
1393 // checking if all elements are not the min-signed-val.
1394 if (!Op1C->isMinSignedValue() &&
1395 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1396 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1397 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1398 BO->setIsExact(I.isExact());
1399 return BO;
1400 }
1401 }
1402
1403 // -X / Y --> -(X / Y)
1404 Value *Y;
1407 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1408
1409 // abs(X) / X --> X > -1 ? 1 : -1
1410 // X / abs(X) --> X > -1 ? 1 : -1
1411 if (match(&I, m_c_BinOp(
1412 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1413 m_Deferred(X)))) {
1417 }
1418
1419 KnownBits KnownDividend = computeKnownBits(Op0, 0, &I);
1420 if (!I.isExact() &&
1421 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1422 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1423 I.setIsExact();
1424 return &I;
1425 }
1426
1427 if (KnownDividend.isNonNegative()) {
1428 // If both operands are unsigned, turn this into a udiv.
1429 if (isKnownNonNegative(Op1, DL, 0, &AC, &I, &DT)) {
1430 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1431 BO->setIsExact(I.isExact());
1432 return BO;
1433 }
1434
1435 if (match(Op1, m_NegatedPower2())) {
1436 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1437 // -> -(X udiv (1 << C)) -> -(X u>> C)
1439 ConstantExpr::getNeg(cast<Constant>(Op1)));
1440 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1441 return BinaryOperator::CreateNeg(Shr);
1442 }
1443
1444 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1445 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1446 // Safe because the only negative value (1 << Y) can take on is
1447 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1448 // the sign bit set.
1449 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1450 BO->setIsExact(I.isExact());
1451 return BO;
1452 }
1453 }
1454
1455 return nullptr;
1456}
1457
1458/// Remove negation and try to convert division into multiplication.
1459Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1460 Constant *C;
1461 if (!match(I.getOperand(1), m_Constant(C)))
1462 return nullptr;
1463
1464 // -X / C --> X / -C
1465 Value *X;
1466 const DataLayout &DL = I.getModule()->getDataLayout();
1467 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1468 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1469 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1470
1471 // nnan X / +0.0 -> copysign(inf, X)
1472 if (I.hasNoNaNs() && match(I.getOperand(1), m_Zero())) {
1473 IRBuilder<> B(&I);
1474 // TODO: nnan nsz X / -0.0 -> copysign(inf, X)
1475 CallInst *CopySign = B.CreateIntrinsic(
1476 Intrinsic::copysign, {C->getType()},
1477 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1478 CopySign->takeName(&I);
1479 return replaceInstUsesWith(I, CopySign);
1480 }
1481
1482 // If the constant divisor has an exact inverse, this is always safe. If not,
1483 // then we can still create a reciprocal if fast-math-flags allow it and the
1484 // constant is a regular number (not zero, infinite, or denormal).
1485 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1486 return nullptr;
1487
1488 // Disallow denormal constants because we don't know what would happen
1489 // on all targets.
1490 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1491 // denorms are flushed?
1492 auto *RecipC = ConstantFoldBinaryOpOperands(
1493 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1494 if (!RecipC || !RecipC->isNormalFP())
1495 return nullptr;
1496
1497 // X / C --> X * (1 / C)
1498 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1499}
1500
1501/// Remove negation and try to reassociate constant math.
1503 Constant *C;
1504 if (!match(I.getOperand(0), m_Constant(C)))
1505 return nullptr;
1506
1507 // C / -X --> -C / X
1508 Value *X;
1509 const DataLayout &DL = I.getModule()->getDataLayout();
1510 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1511 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1512 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1513
1514 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1515 return nullptr;
1516
1517 // Try to reassociate C / X expressions where X includes another constant.
1518 Constant *C2, *NewC = nullptr;
1519 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1520 // C / (X * C2) --> (C / C2) / X
1521 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1522 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1523 // C / (X / C2) --> (C * C2) / X
1524 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1525 }
1526 // Disallow denormal constants because we don't know what would happen
1527 // on all targets.
1528 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1529 // denorms are flushed?
1530 if (!NewC || !NewC->isNormalFP())
1531 return nullptr;
1532
1533 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1534}
1535
1536/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1538 InstCombiner::BuilderTy &Builder) {
1539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1540 auto *II = dyn_cast<IntrinsicInst>(Op1);
1541 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1542 !I.hasAllowReciprocal())
1543 return nullptr;
1544
1545 // Z / pow(X, Y) --> Z * pow(X, -Y)
1546 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1547 // In the general case, this creates an extra instruction, but fmul allows
1548 // for better canonicalization and optimization than fdiv.
1549 Intrinsic::ID IID = II->getIntrinsicID();
1551 switch (IID) {
1552 case Intrinsic::pow:
1553 Args.push_back(II->getArgOperand(0));
1554 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1555 break;
1556 case Intrinsic::powi: {
1557 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1558 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1559 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1560 // non-standard results, so this corner case should be acceptable if the
1561 // code rules out INF values.
1562 if (!I.hasNoInfs())
1563 return nullptr;
1564 Args.push_back(II->getArgOperand(0));
1565 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1566 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1567 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1568 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1569 }
1570 case Intrinsic::exp:
1571 case Intrinsic::exp2:
1572 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1573 break;
1574 default:
1575 return nullptr;
1576 }
1577 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1578 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1579}
1580
1582 Module *M = I.getModule();
1583
1584 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
1585 I.getFastMathFlags(),
1587 return replaceInstUsesWith(I, V);
1588
1590 return X;
1591
1593 return Phi;
1594
1595 if (Instruction *R = foldFDivConstantDivisor(I))
1596 return R;
1597
1599 return R;
1600
1601 if (Instruction *R = foldFPSignBitOps(I))
1602 return R;
1603
1604 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1605 if (isa<Constant>(Op0))
1606 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1607 if (Instruction *R = FoldOpIntoSelect(I, SI))
1608 return R;
1609
1610 if (isa<Constant>(Op1))
1611 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1612 if (Instruction *R = FoldOpIntoSelect(I, SI))
1613 return R;
1614
1615 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1616 Value *X, *Y;
1617 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1618 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1619 // (X / Y) / Z => X / (Y * Z)
1620 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1621 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1622 }
1623 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1624 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1625 // Z / (X / Y) => (Y * Z) / X
1626 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1627 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1628 }
1629 // Z / (1.0 / Y) => (Y * Z)
1630 //
1631 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1632 // m_OneUse check is avoided because even in the case of the multiple uses
1633 // for 1.0/Y, the number of instructions remain the same and a division is
1634 // replaced by a multiplication.
1635 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1636 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1637 }
1638
1639 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1640 // sin(X) / cos(X) -> tan(X)
1641 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1642 Value *X;
1643 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1644 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1645 bool IsCot =
1646 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1647 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1648
1649 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
1650 LibFunc_tanf, LibFunc_tanl)) {
1651 IRBuilder<> B(&I);
1653 B.setFastMathFlags(I.getFastMathFlags());
1654 AttributeList Attrs =
1655 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1656 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1657 LibFunc_tanl, B, Attrs);
1658 if (IsCot)
1659 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1660 return replaceInstUsesWith(I, Res);
1661 }
1662 }
1663
1664 // X / (X * Y) --> 1.0 / Y
1665 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1666 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1667 Value *X, *Y;
1668 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1669 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1670 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1671 replaceOperand(I, 1, Y);
1672 return &I;
1673 }
1674
1675 // X / fabs(X) -> copysign(1.0, X)
1676 // fabs(X) / X -> copysign(1.0, X)
1677 if (I.hasNoNaNs() && I.hasNoInfs() &&
1678 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1679 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1681 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1682 return replaceInstUsesWith(I, V);
1683 }
1684
1686 return Mul;
1687
1688 // pow(X, Y) / X --> pow(X, Y-1)
1689 if (I.hasAllowReassoc() &&
1690 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Specific(Op1),
1691 m_Value(Y))))) {
1692 Value *Y1 =
1693 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
1694 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
1695 return replaceInstUsesWith(I, Pow);
1696 }
1697
1698 return nullptr;
1699}
1700
1701// Variety of transform for (urem/srem (mul/shl X, Y), (mul/shl X, Z))
1703 InstCombinerImpl &IC) {
1704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X;
1705 const APInt *Y, *Z;
1706 if (!(match(Op0, m_Mul(m_Value(X), m_APInt(Y))) &&
1707 match(Op1, m_c_Mul(m_Specific(X), m_APInt(Z)))) &&
1708 !(match(Op0, m_Mul(m_APInt(Y), m_Value(X))) &&
1709 match(Op1, m_c_Mul(m_Specific(X), m_APInt(Z)))))
1710 return nullptr;
1711
1712 bool IsSRem = I.getOpcode() == Instruction::SRem;
1713
1714 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Op0);
1715 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
1716 // Z or Z >= Y.
1717 bool BO0HasNSW = BO0->hasNoSignedWrap();
1718 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
1719 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
1720
1721 APInt RemYZ = IsSRem ? Y->srem(*Z) : Y->urem(*Z);
1722 // (rem (mul nuw/nsw X, Y), (mul X, Z))
1723 // if (rem Y, Z) == 0
1724 // -> 0
1725 if (RemYZ.isZero() && BO0NoWrap)
1726 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
1727
1728 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Op1);
1729 bool BO1HasNSW = BO1->hasNoSignedWrap();
1730 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
1731 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
1732 // (rem (mul X, Y), (mul nuw/nsw X, Z))
1733 // if (rem Y, Z) == Y
1734 // -> (mul nuw/nsw X, Y)
1735 if (RemYZ == *Y && BO1NoWrap) {
1736 BinaryOperator *BO =
1737 BinaryOperator::CreateMul(X, ConstantInt::get(I.getType(), *Y));
1738 // Copy any overflow flags from Op0.
1739 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
1740 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
1741 return BO;
1742 }
1743
1744 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
1745 // if Y >= Z
1746 // -> (mul {nuw} nsw X, (rem Y, Z))
1747 if (Y->uge(*Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
1748 BinaryOperator *BO =
1749 BinaryOperator::CreateMul(X, ConstantInt::get(I.getType(), RemYZ));
1750 BO->setHasNoSignedWrap();
1751 BO->setHasNoUnsignedWrap(BO0HasNUW);
1752 return BO;
1753 }
1754
1755 return nullptr;
1756}
1757
1758/// This function implements the transforms common to both integer remainder
1759/// instructions (urem and srem). It is called by the visitors to those integer
1760/// remainder instructions.
1761/// Common integer remainder transforms
1764 return Phi;
1765
1766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1767
1768 // The RHS is known non-zero.
1769 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1770 return replaceOperand(I, 1, V);
1771
1772 // Handle cases involving: rem X, (select Cond, Y, Z)
1774 return &I;
1775
1776 // If the divisor is a select-of-constants, try to constant fold all rem ops:
1777 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
1778 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1779 if (match(Op0, m_ImmConstant()) &&
1781 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1782 /*FoldWithMultiUse*/ true))
1783 return R;
1784 }
1785
1786 if (isa<Constant>(Op1)) {
1787 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1788 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1789 if (Instruction *R = FoldOpIntoSelect(I, SI))
1790 return R;
1791 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1792 const APInt *Op1Int;
1793 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1794 (I.getOpcode() == Instruction::URem ||
1795 !Op1Int->isMinSignedValue())) {
1796 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1797 // predecessor blocks, so do this only if we know the srem or urem
1798 // will not fault.
1799 if (Instruction *NV = foldOpIntoPhi(I, PN))
1800 return NV;
1801 }
1802 }
1803
1804 // See if we can fold away this rem instruction.
1806 return &I;
1807 }
1808 }
1809
1810 if (Instruction *R = simplifyIRemMulShl(I, *this))
1811 return R;
1812
1813 return nullptr;
1814}
1815
1817 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
1819 return replaceInstUsesWith(I, V);
1820
1822 return X;
1823
1824 if (Instruction *common = commonIRemTransforms(I))
1825 return common;
1826
1827 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1828 return NarrowRem;
1829
1830 // X urem Y -> X and Y-1, where Y is a power of 2,
1831 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1832 Type *Ty = I.getType();
1833 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1834 // This may increase instruction count, we don't enforce that Y is a
1835 // constant.
1837 Value *Add = Builder.CreateAdd(Op1, N1);
1838 return BinaryOperator::CreateAnd(Op0, Add);
1839 }
1840
1841 // 1 urem X -> zext(X != 1)
1842 if (match(Op0, m_One())) {
1843 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1844 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1845 }
1846
1847 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
1848 // Op0 must be frozen because we are increasing its number of uses.
1849 if (match(Op1, m_Negative())) {
1850 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
1851 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
1852 Value *Sub = Builder.CreateSub(F0, Op1);
1853 return SelectInst::Create(Cmp, F0, Sub);
1854 }
1855
1856 // If the divisor is a sext of a boolean, then the divisor must be max
1857 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1858 // max unsigned value. In that case, the remainder is 0:
1859 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1860 Value *X;
1861 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1863 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1864 }
1865
1866 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
1867 if (match(Op0, m_Add(m_Value(X), m_One()))) {
1868 Value *Val =
1870 if (Val && match(Val, m_One())) {
1871 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
1872 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
1873 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
1874 }
1875 }
1876
1877 return nullptr;
1878}
1879
1881 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
1883 return replaceInstUsesWith(I, V);
1884
1886 return X;
1887
1888 // Handle the integer rem common cases
1889 if (Instruction *Common = commonIRemTransforms(I))
1890 return Common;
1891
1892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1893 {
1894 const APInt *Y;
1895 // X % -Y -> X % Y
1896 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1897 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
1898 }
1899
1900 // -X srem Y --> -(X srem Y)
1901 Value *X, *Y;
1904
1905 // If the sign bits of both operands are zero (i.e. we can prove they are
1906 // unsigned inputs), turn this into a urem.
1907 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1908 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1909 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1910 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1911 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1912 }
1913
1914 // If it's a constant vector, flip any negative values positive.
1915 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1916 Constant *C = cast<Constant>(Op1);
1917 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
1918
1919 bool hasNegative = false;
1920 bool hasMissing = false;
1921 for (unsigned i = 0; i != VWidth; ++i) {
1922 Constant *Elt = C->getAggregateElement(i);
1923 if (!Elt) {
1924 hasMissing = true;
1925 break;
1926 }
1927
1928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1929 if (RHS->isNegative())
1930 hasNegative = true;
1931 }
1932
1933 if (hasNegative && !hasMissing) {
1934 SmallVector<Constant *, 16> Elts(VWidth);
1935 for (unsigned i = 0; i != VWidth; ++i) {
1936 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1937 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1938 if (RHS->isNegative())
1939 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1940 }
1941 }
1942
1943 Constant *NewRHSV = ConstantVector::get(Elts);
1944 if (NewRHSV != C) // Don't loop on -MININT
1945 return replaceOperand(I, 1, NewRHSV);
1946 }
1947 }
1948
1949 return nullptr;
1950}
1951
1953 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
1954 I.getFastMathFlags(),
1956 return replaceInstUsesWith(I, V);
1957
1959 return X;
1960
1962 return Phi;
1963
1964 return nullptr;
1965}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
assume Assume Builder
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides internal interfaces used to implement the InstCombine.
static Value * takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth, bool DoFold)
static Instruction * simplifyIRemMulShl(BinaryOperator &I, InstCombinerImpl &IC)
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 Instruction * narrowUDivURem(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
If we have zero-extended operands of an unsigned div or rem, we may be able to narrow the operation (...
static const unsigned MaxDepth
static Instruction * foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static Value * foldMulSelectToNegate(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
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 * foldFDivConstantDividend(BinaryOperator &I)
Remove negation and try to reassociate constant math.
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:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Value * RHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition: APInt.h:75
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1969
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1571
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition: APInt.cpp:1756
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:209
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:415
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1494
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1888
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:354
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:366
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:409
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1592
APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:1999
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1482
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1958
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:222
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:271
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition: InstrTypes.h:391
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Instruction *CopyO, const Twine &Name="", Instruction *InsertBefore=nullptr)
Definition: InstrTypes.h:248
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:266
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:261
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:256
This class represents a function call, abstracting a target machine's calling convention.
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1054
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:743
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2110
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2647
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2082
static 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...
Definition: Constants.cpp:2664
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2601
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:927
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1034
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:840
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:847
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1349
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:403
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
Definition: Constants.cpp:221
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
Definition: Constants.cpp:172
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
Value * CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1470
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:956
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2146
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1920
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1639
Value * CreateSRem(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1333
Value * CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1524
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:973
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2424
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1360
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2448
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:297
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2134
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1924
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2130
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition: IRBuilder.h:2443
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1267
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1339
CallInst * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Definition: IRBuilder.cpp:964
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1398
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1250
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1314
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1589
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2142
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1379
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1284
Instruction * visitMul(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
Instruction * visitUDiv(BinaryOperator &I)
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * visitURem(BinaryOperator &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * visitSRem(BinaryOperator &I)
Instruction * visitFDiv(BinaryOperator &I)
bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I)
Fold a divide or remainder with a select instruction divisor when one of the select operands is zero.
Instruction * commonIDivTransforms(BinaryOperator &I)
This function implements the transforms common to both integer division instructions (udiv and sdiv).
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * visitFRem(BinaryOperator &I)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * visitFMul(BinaryOperator &I)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * visitSDiv(BinaryOperator &I)
Instruction * commonIRemTransforms(BinaryOperator &I)
This function implements the transforms common to both integer remainder instructions (urem and srem)...
TargetLibraryInfo & TLI
Definition: InstCombiner.h:71
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, unsigned Depth=0, const Instruction *CxtI=nullptr)
Definition: InstCombiner.h:471
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:418
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:449
const SimplifyQuery SQ
Definition: InstCombiner.h:74
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:62
const DataLayout & DL
Definition: InstCombiner.h:73
AssumptionCache & AC
Definition: InstCombiner.h:70
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:442
DominatorTree & DT
Definition: InstCombiner.h:72
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:461
BuilderTy & Builder
Definition: InstCombiner.h:58
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:477
void push(Instruction *I)
Push the instruction onto the worklist stack.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static Value * Negate(bool LHSIsZero, 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:75
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:105
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:99
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="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:237
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", Instruction *InsertBefore=nullptr)
Definition: InstrTypes.h:163
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
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:434
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:148
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:381
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:453
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:854
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
Definition: PatternMatch.h:475
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:979
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:84
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.
Definition: PatternMatch.h:576
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
apint_match m_APIntAllowUndef(const APInt *&Res)
Match APInt while allowing undefs in splat vector constants.
Definition: PatternMatch.h:284
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:997
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:544
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:144
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:772
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
Definition: PatternMatch.h:485
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:517
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
Definition: PatternMatch.h:815
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
Definition: PatternMatch.h:985
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:790
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:751
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
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.
Definition: PatternMatch.h:552
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
specific_intval< true > m_SpecificIntAllowUndef(APInt V)
Definition: PatternMatch.h:862
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
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.
Definition: PatternMatch.h:673
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< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:537
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:991
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
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.
Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
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.
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,...
Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
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.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
Value * simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
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.
bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if LHS and RHS have no common bits set.
@ Mul
Product of integers.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
Value * simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for a UDiv, fold the result or return null.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
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:208
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:860
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:99
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:233
SelectPatternFlavor Flavor
SimplifyQuery getWithInstruction(Instruction *I) const