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/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/InstructionSimplify.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" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/Operator.h" 28 #include "llvm/IR/PatternMatch.h" 29 #include "llvm/IR/Type.h" 30 #include "llvm/IR/Value.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/KnownBits.h" 34 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 35 #include "llvm/Transforms/InstCombine/InstCombiner.h" 36 #include "llvm/Transforms/Utils/BuildLibCalls.h" 37 #include <cassert> 38 #include <cstddef> 39 #include <cstdint> 40 #include <utility> 41 42 using namespace llvm; 43 using namespace PatternMatch; 44 45 #define DEBUG_TYPE "instcombine" 46 47 /// The specific integer value is used in a context where it is known to be 48 /// non-zero. If this allows us to simplify the computation, do so and return 49 /// the new operand, otherwise return null. 50 static Value *simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, 51 Instruction &CxtI) { 52 // If V has multiple uses, then we would have to do more analysis to determine 53 // if this is safe. For example, the use could be in dynamically unreached 54 // code. 55 if (!V->hasOneUse()) return nullptr; 56 57 bool MadeChange = false; 58 59 // ((1 << A) >>u B) --> (1 << (A-B)) 60 // Because V cannot be zero, we know that B is less than A. 61 Value *A = nullptr, *B = nullptr, *One = nullptr; 62 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) && 63 match(One, m_One())) { 64 A = IC.Builder.CreateSub(A, B); 65 return IC.Builder.CreateShl(One, A); 66 } 67 68 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 69 // inexact. Similarly for <<. 70 BinaryOperator *I = dyn_cast<BinaryOperator>(V); 71 if (I && I->isLogicalShift() && 72 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) { 73 // We know that this is an exact/nuw shift and that the input is a 74 // non-zero context as well. 75 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) { 76 IC.replaceOperand(*I, 0, V2); 77 MadeChange = true; 78 } 79 80 if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 81 I->setIsExact(); 82 MadeChange = true; 83 } 84 85 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 86 I->setHasNoUnsignedWrap(); 87 MadeChange = true; 88 } 89 } 90 91 // TODO: Lots more we could do here: 92 // If V is a phi node, we can call this on each of its operands. 93 // "select cond, X, 0" can simplify to "X". 94 95 return MadeChange ? V : nullptr; 96 } 97 98 /// A helper routine of InstCombiner::visitMul(). 99 /// 100 /// If C is a scalar/fixed width vector of known powers of 2, then this 101 /// function returns a new scalar/fixed width vector obtained from logBase2 102 /// of C. 103 /// Return a null pointer otherwise. 104 static Constant *getLogBase2(Type *Ty, Constant *C) { 105 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N. 106 // FIXME: just assert that C there is no undef in \p C. 107 108 const APInt *IVal; 109 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2()) 110 return ConstantInt::get(Ty, IVal->logBase2()); 111 112 // FIXME: We can extract pow of 2 of splat constant for scalable vectors. 113 if (!isa<FixedVectorType>(Ty)) 114 return nullptr; 115 116 SmallVector<Constant *, 4> Elts; 117 for (unsigned I = 0, E = cast<FixedVectorType>(Ty)->getNumElements(); I != E; 118 ++I) { 119 Constant *Elt = C->getAggregateElement(I); 120 if (!Elt) 121 return nullptr; 122 if (isa<UndefValue>(Elt)) { 123 Elts.push_back(UndefValue::get(Ty->getScalarType())); 124 continue; 125 } 126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2()) 127 return nullptr; 128 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2())); 129 } 130 131 return ConstantVector::get(Elts); 132 } 133 134 // TODO: This is a specific form of a much more general pattern. 135 // We could detect a select with any binop identity constant, or we 136 // could use SimplifyBinOp to see if either arm of the select reduces. 137 // But that needs to be done carefully and/or while removing potential 138 // reverse canonicalizations as in InstCombiner::foldSelectIntoOp(). 139 static Value *foldMulSelectToNegate(BinaryOperator &I, 140 InstCombiner::BuilderTy &Builder) { 141 Value *Cond, *OtherOp; 142 143 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp 144 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp 145 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())), 146 m_Value(OtherOp)))) 147 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp)); 148 149 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp 150 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp 151 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())), 152 m_Value(OtherOp)))) 153 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp); 154 155 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp 156 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp 157 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0), 158 m_SpecificFP(-1.0))), 159 m_Value(OtherOp)))) { 160 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 161 Builder.setFastMathFlags(I.getFastMathFlags()); 162 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp)); 163 } 164 165 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp 166 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp 167 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0), 168 m_SpecificFP(1.0))), 169 m_Value(OtherOp)))) { 170 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 171 Builder.setFastMathFlags(I.getFastMathFlags()); 172 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp); 173 } 174 175 return nullptr; 176 } 177 178 Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) { 179 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1), 180 SQ.getWithInstruction(&I))) 181 return replaceInstUsesWith(I, V); 182 183 if (SimplifyAssociativeOrCommutative(I)) 184 return &I; 185 186 if (Instruction *X = foldVectorBinop(I)) 187 return X; 188 189 if (Value *V = SimplifyUsingDistributiveLaws(I)) 190 return replaceInstUsesWith(I, V); 191 192 // X * -1 == 0 - X 193 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 194 if (match(Op1, m_AllOnes())) { 195 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName()); 196 if (I.hasNoSignedWrap()) 197 BO->setHasNoSignedWrap(); 198 return BO; 199 } 200 201 // Also allow combining multiply instructions on vectors. 202 { 203 Value *NewOp; 204 Constant *C1, *C2; 205 const APInt *IVal; 206 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)), 207 m_Constant(C1))) && 208 match(C1, m_APInt(IVal))) { 209 // ((X << C2)*C1) == (X * (C1 << C2)) 210 Constant *Shl = ConstantExpr::getShl(C1, C2); 211 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0)); 212 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl); 213 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap()) 214 BO->setHasNoUnsignedWrap(); 215 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() && 216 Shl->isNotMinSignedValue()) 217 BO->setHasNoSignedWrap(); 218 return BO; 219 } 220 221 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) { 222 // Replace X*(2^C) with X << C, where C is either a scalar or a vector. 223 // Note that we need to sanitize undef multipliers to 1, 224 // to avoid introducing poison. 225 Constant *SafeC1 = Constant::replaceUndefsWith( 226 C1, ConstantInt::get(C1->getType()->getScalarType(), 1)); 227 if (Constant *NewCst = getLogBase2(NewOp->getType(), SafeC1)) { 228 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst); 229 230 if (I.hasNoUnsignedWrap()) 231 Shl->setHasNoUnsignedWrap(); 232 if (I.hasNoSignedWrap()) { 233 const APInt *V; 234 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1) 235 Shl->setHasNoSignedWrap(); 236 } 237 238 return Shl; 239 } 240 } 241 } 242 243 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) { 244 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation. 245 // The "* (1<<C)" thus becomes a potential shifting opportunity. 246 if (Value *NegOp0 = Negator::Negate(/*IsNegation*/ true, Op0, *this)) 247 return BinaryOperator::CreateMul( 248 NegOp0, ConstantExpr::getNeg(cast<Constant>(Op1)), I.getName()); 249 } 250 251 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I)) 252 return FoldedMul; 253 254 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder)) 255 return replaceInstUsesWith(I, FoldedMul); 256 257 // Simplify mul instructions with a constant RHS. 258 if (isa<Constant>(Op1)) { 259 // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 260 Value *X; 261 Constant *C1; 262 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) { 263 Value *Mul = Builder.CreateMul(C1, Op1); 264 // Only go forward with the transform if C1*CI simplifies to a tidier 265 // constant. 266 if (!match(Mul, m_Mul(m_Value(), m_Value()))) 267 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul); 268 } 269 } 270 271 // abs(X) * abs(X) -> X * X 272 // nabs(X) * nabs(X) -> X * X 273 if (Op0 == Op1) { 274 Value *X, *Y; 275 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor; 276 if (SPF == SPF_ABS || SPF == SPF_NABS) 277 return BinaryOperator::CreateMul(X, X); 278 } 279 280 // -X * C --> X * -C 281 Value *X, *Y; 282 Constant *Op1C; 283 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C))) 284 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C)); 285 286 // -X * -Y --> X * Y 287 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) { 288 auto *NewMul = BinaryOperator::CreateMul(X, Y); 289 if (I.hasNoSignedWrap() && 290 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() && 291 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap()) 292 NewMul->setHasNoSignedWrap(); 293 return NewMul; 294 } 295 296 // -X * Y --> -(X * Y) 297 // X * -Y --> -(X * Y) 298 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y)))) 299 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y)); 300 301 // (X / Y) * Y = X - (X % Y) 302 // (X / Y) * -Y = (X % Y) - X 303 { 304 Value *Y = Op1; 305 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0); 306 if (!Div || (Div->getOpcode() != Instruction::UDiv && 307 Div->getOpcode() != Instruction::SDiv)) { 308 Y = Op0; 309 Div = dyn_cast<BinaryOperator>(Op1); 310 } 311 Value *Neg = dyn_castNegVal(Y); 312 if (Div && Div->hasOneUse() && 313 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) && 314 (Div->getOpcode() == Instruction::UDiv || 315 Div->getOpcode() == Instruction::SDiv)) { 316 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1); 317 318 // If the division is exact, X % Y is zero, so we end up with X or -X. 319 if (Div->isExact()) { 320 if (DivOp1 == Y) 321 return replaceInstUsesWith(I, X); 322 return BinaryOperator::CreateNeg(X); 323 } 324 325 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem 326 : Instruction::SRem; 327 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1); 328 if (DivOp1 == Y) 329 return BinaryOperator::CreateSub(X, Rem); 330 return BinaryOperator::CreateSub(Rem, X); 331 } 332 } 333 334 /// i1 mul -> i1 and. 335 if (I.getType()->isIntOrIntVectorTy(1)) 336 return BinaryOperator::CreateAnd(Op0, Op1); 337 338 // X*(1 << Y) --> X << Y 339 // (1 << Y)*X --> X << Y 340 { 341 Value *Y; 342 BinaryOperator *BO = nullptr; 343 bool ShlNSW = false; 344 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) { 345 BO = BinaryOperator::CreateShl(Op1, Y); 346 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap(); 347 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) { 348 BO = BinaryOperator::CreateShl(Op0, Y); 349 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap(); 350 } 351 if (BO) { 352 if (I.hasNoUnsignedWrap()) 353 BO->setHasNoUnsignedWrap(); 354 if (I.hasNoSignedWrap() && ShlNSW) 355 BO->setHasNoSignedWrap(); 356 return BO; 357 } 358 } 359 360 // (zext bool X) * (zext bool Y) --> zext (and X, Y) 361 // (sext bool X) * (sext bool Y) --> zext (and X, Y) 362 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same) 363 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) || 364 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) && 365 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() && 366 (Op0->hasOneUse() || Op1->hasOneUse())) { 367 Value *And = Builder.CreateAnd(X, Y, "mulbool"); 368 return CastInst::Create(Instruction::ZExt, And, I.getType()); 369 } 370 // (sext bool X) * (zext bool Y) --> sext (and X, Y) 371 // (zext bool X) * (sext bool Y) --> sext (and X, Y) 372 // Note: -1 * 1 == 1 * -1 == -1 373 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) || 374 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) && 375 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() && 376 (Op0->hasOneUse() || Op1->hasOneUse())) { 377 Value *And = Builder.CreateAnd(X, Y, "mulbool"); 378 return CastInst::Create(Instruction::SExt, And, I.getType()); 379 } 380 381 // (bool X) * Y --> X ? Y : 0 382 // Y * (bool X) --> X ? Y : 0 383 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 384 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0)); 385 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 386 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0)); 387 388 // (lshr X, 31) * Y --> (ashr X, 31) & Y 389 // Y * (lshr X, 31) --> (ashr X, 31) & Y 390 // TODO: We are not checking one-use because the elimination of the multiply 391 // is better for analysis? 392 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be 393 // more similar to what we're doing above. 394 const APInt *C; 395 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1) 396 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1); 397 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1) 398 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0); 399 400 if (Instruction *Ext = narrowMathIfNoOverflow(I)) 401 return Ext; 402 403 bool Changed = false; 404 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) { 405 Changed = true; 406 I.setHasNoSignedWrap(true); 407 } 408 409 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) { 410 Changed = true; 411 I.setHasNoUnsignedWrap(true); 412 } 413 414 return Changed ? &I : nullptr; 415 } 416 417 Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) { 418 BinaryOperator::BinaryOps Opcode = I.getOpcode(); 419 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) && 420 "Expected fmul or fdiv"); 421 422 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 423 Value *X, *Y; 424 425 // -X * -Y --> X * Y 426 // -X / -Y --> X / Y 427 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 428 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I); 429 430 // fabs(X) * fabs(X) -> X * X 431 // fabs(X) / fabs(X) -> X / X 432 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X)))) 433 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I); 434 435 // fabs(X) * fabs(Y) --> fabs(X * Y) 436 // fabs(X) / fabs(Y) --> fabs(X / Y) 437 if (match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))) && 438 match(Op1, m_Intrinsic<Intrinsic::fabs>(m_Value(Y))) && 439 (Op0->hasOneUse() || Op1->hasOneUse())) { 440 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 441 Builder.setFastMathFlags(I.getFastMathFlags()); 442 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 443 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY); 444 Fabs->takeName(&I); 445 return replaceInstUsesWith(I, Fabs); 446 } 447 448 return nullptr; 449 } 450 451 Instruction *InstCombinerImpl::visitFMul(BinaryOperator &I) { 452 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1), 453 I.getFastMathFlags(), 454 SQ.getWithInstruction(&I))) 455 return replaceInstUsesWith(I, V); 456 457 if (SimplifyAssociativeOrCommutative(I)) 458 return &I; 459 460 if (Instruction *X = foldVectorBinop(I)) 461 return X; 462 463 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I)) 464 return FoldedMul; 465 466 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder)) 467 return replaceInstUsesWith(I, FoldedMul); 468 469 if (Instruction *R = foldFPSignBitOps(I)) 470 return R; 471 472 // X * -1.0 --> -X 473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 474 if (match(Op1, m_SpecificFP(-1.0))) 475 return UnaryOperator::CreateFNegFMF(Op0, &I); 476 477 // -X * C --> X * -C 478 Value *X, *Y; 479 Constant *C; 480 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C))) 481 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I); 482 483 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E) 484 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1)) 485 return replaceInstUsesWith(I, V); 486 487 if (I.hasAllowReassoc()) { 488 // Reassociate constant RHS with another constant to form constant 489 // expression. 490 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) { 491 Constant *C1; 492 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) { 493 // (C1 / X) * C --> (C * C1) / X 494 Constant *CC1 = ConstantExpr::getFMul(C, C1); 495 if (CC1->isNormalFP()) 496 return BinaryOperator::CreateFDivFMF(CC1, X, &I); 497 } 498 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) { 499 // (X / C1) * C --> X * (C / C1) 500 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1); 501 if (CDivC1->isNormalFP()) 502 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I); 503 504 // If the constant was a denormal, try reassociating differently. 505 // (X / C1) * C --> X / (C1 / C) 506 Constant *C1DivC = ConstantExpr::getFDiv(C1, C); 507 if (Op0->hasOneUse() && C1DivC->isNormalFP()) 508 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I); 509 } 510 511 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are 512 // canonicalized to 'fadd X, C'. Distributing the multiply may allow 513 // further folds and (X * C) + C2 is 'fma'. 514 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) { 515 // (X + C1) * C --> (X * C) + (C * C1) 516 Constant *CC1 = ConstantExpr::getFMul(C, C1); 517 Value *XC = Builder.CreateFMulFMF(X, C, &I); 518 return BinaryOperator::CreateFAddFMF(XC, CC1, &I); 519 } 520 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) { 521 // (C1 - X) * C --> (C * C1) - (X * C) 522 Constant *CC1 = ConstantExpr::getFMul(C, C1); 523 Value *XC = Builder.CreateFMulFMF(X, C, &I); 524 return BinaryOperator::CreateFSubFMF(CC1, XC, &I); 525 } 526 } 527 528 Value *Z; 529 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))), 530 m_Value(Z)))) { 531 // Sink division: (X / Y) * Z --> (X * Z) / Y 532 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I); 533 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I); 534 } 535 536 // sqrt(X) * sqrt(Y) -> sqrt(X * Y) 537 // nnan disallows the possibility of returning a number if both operands are 538 // negative (in that case, we should return NaN). 539 if (I.hasNoNaNs() && 540 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) && 541 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) { 542 Value *XY = Builder.CreateFMulFMF(X, Y, &I); 543 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I); 544 return replaceInstUsesWith(I, Sqrt); 545 } 546 547 // The following transforms are done irrespective of the number of uses 548 // for the expression "1.0/sqrt(X)". 549 // 1) 1.0/sqrt(X) * X -> X/sqrt(X) 550 // 2) X * 1.0/sqrt(X) -> X/sqrt(X) 551 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it 552 // has the necessary (reassoc) fast-math-flags. 553 if (I.hasNoSignedZeros() && 554 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 555 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op1 == X) 556 return BinaryOperator::CreateFDivFMF(X, Y, &I); 557 if (I.hasNoSignedZeros() && 558 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) && 559 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op0 == X) 560 return BinaryOperator::CreateFDivFMF(X, Y, &I); 561 562 // Like the similar transform in instsimplify, this requires 'nsz' because 563 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0. 564 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && 565 Op0->hasNUses(2)) { 566 // Peek through fdiv to find squaring of square root: 567 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y 568 if (match(Op0, m_FDiv(m_Value(X), 569 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) { 570 Value *XX = Builder.CreateFMulFMF(X, X, &I); 571 return BinaryOperator::CreateFDivFMF(XX, Y, &I); 572 } 573 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X) 574 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)), 575 m_Value(X)))) { 576 Value *XX = Builder.CreateFMulFMF(X, X, &I); 577 return BinaryOperator::CreateFDivFMF(Y, XX, &I); 578 } 579 } 580 581 // exp(X) * exp(Y) -> exp(X + Y) 582 // Match as long as at least one of exp has only one use. 583 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) && 584 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) && 585 (Op0->hasOneUse() || Op1->hasOneUse())) { 586 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 587 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I); 588 return replaceInstUsesWith(I, Exp); 589 } 590 591 // exp2(X) * exp2(Y) -> exp2(X + Y) 592 // Match as long as at least one of exp2 has only one use. 593 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) && 594 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) && 595 (Op0->hasOneUse() || Op1->hasOneUse())) { 596 Value *XY = Builder.CreateFAddFMF(X, Y, &I); 597 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I); 598 return replaceInstUsesWith(I, Exp2); 599 } 600 601 // (X*Y) * X => (X*X) * Y where Y != X 602 // The purpose is two-fold: 603 // 1) to form a power expression (of X). 604 // 2) potentially shorten the critical path: After transformation, the 605 // latency of the instruction Y is amortized by the expression of X*X, 606 // and therefore Y is in a "less critical" position compared to what it 607 // was before the transformation. 608 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && 609 Op1 != Y) { 610 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I); 611 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 612 } 613 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && 614 Op0 != Y) { 615 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I); 616 return BinaryOperator::CreateFMulFMF(XX, Y, &I); 617 } 618 } 619 620 // log2(X * 0.5) * Y = log2(X) * Y - Y 621 if (I.isFast()) { 622 IntrinsicInst *Log2 = nullptr; 623 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>( 624 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 625 Log2 = cast<IntrinsicInst>(Op0); 626 Y = Op1; 627 } 628 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>( 629 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) { 630 Log2 = cast<IntrinsicInst>(Op1); 631 Y = Op0; 632 } 633 if (Log2) { 634 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I); 635 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I); 636 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I); 637 } 638 } 639 640 return nullptr; 641 } 642 643 /// Fold a divide or remainder with a select instruction divisor when one of the 644 /// select operands is zero. In that case, we can use the other select operand 645 /// because div/rem by zero is undefined. 646 bool InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) { 647 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1)); 648 if (!SI) 649 return false; 650 651 int NonNullOperand; 652 if (match(SI->getTrueValue(), m_Zero())) 653 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 654 NonNullOperand = 2; 655 else if (match(SI->getFalseValue(), m_Zero())) 656 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 657 NonNullOperand = 1; 658 else 659 return false; 660 661 // Change the div/rem to use 'Y' instead of the select. 662 replaceOperand(I, 1, SI->getOperand(NonNullOperand)); 663 664 // Okay, we know we replace the operand of the div/rem with 'Y' with no 665 // problem. However, the select, or the condition of the select may have 666 // multiple uses. Based on our knowledge that the operand must be non-zero, 667 // propagate the known value for the select into other uses of it, and 668 // propagate a known value of the condition into its other users. 669 670 // If the select and condition only have a single use, don't bother with this, 671 // early exit. 672 Value *SelectCond = SI->getCondition(); 673 if (SI->use_empty() && SelectCond->hasOneUse()) 674 return true; 675 676 // Scan the current block backward, looking for other uses of SI. 677 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin(); 678 Type *CondTy = SelectCond->getType(); 679 while (BBI != BBFront) { 680 --BBI; 681 // If we found an instruction that we can't assume will return, so 682 // information from below it cannot be propagated above it. 683 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 684 break; 685 686 // Replace uses of the select or its condition with the known values. 687 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 688 I != E; ++I) { 689 if (*I == SI) { 690 replaceUse(*I, SI->getOperand(NonNullOperand)); 691 Worklist.push(&*BBI); 692 } else if (*I == SelectCond) { 693 replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy) 694 : ConstantInt::getFalse(CondTy)); 695 Worklist.push(&*BBI); 696 } 697 } 698 699 // If we past the instruction, quit looking for it. 700 if (&*BBI == SI) 701 SI = nullptr; 702 if (&*BBI == SelectCond) 703 SelectCond = nullptr; 704 705 // If we ran out of things to eliminate, break out of the loop. 706 if (!SelectCond && !SI) 707 break; 708 709 } 710 return true; 711 } 712 713 /// True if the multiply can not be expressed in an int this size. 714 static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, 715 bool IsSigned) { 716 bool Overflow; 717 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow); 718 return Overflow; 719 } 720 721 /// True if C1 is a multiple of C2. Quotient contains C1/C2. 722 static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, 723 bool IsSigned) { 724 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal"); 725 726 // Bail if we will divide by zero. 727 if (C2.isNullValue()) 728 return false; 729 730 // Bail if we would divide INT_MIN by -1. 731 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue()) 732 return false; 733 734 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned); 735 if (IsSigned) 736 APInt::sdivrem(C1, C2, Quotient, Remainder); 737 else 738 APInt::udivrem(C1, C2, Quotient, Remainder); 739 740 return Remainder.isMinValue(); 741 } 742 743 /// This function implements the transforms common to both integer division 744 /// instructions (udiv and sdiv). It is called by the visitors to those integer 745 /// division instructions. 746 /// Common integer divide transforms 747 Instruction *InstCombinerImpl::commonIDivTransforms(BinaryOperator &I) { 748 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 749 bool IsSigned = I.getOpcode() == Instruction::SDiv; 750 Type *Ty = I.getType(); 751 752 // The RHS is known non-zero. 753 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 754 return replaceOperand(I, 1, V); 755 756 // Handle cases involving: [su]div X, (select Cond, Y, Z) 757 // This does not apply for fdiv. 758 if (simplifyDivRemOfSelectWithZeroOp(I)) 759 return &I; 760 761 const APInt *C2; 762 if (match(Op1, m_APInt(C2))) { 763 Value *X; 764 const APInt *C1; 765 766 // (X / C1) / C2 -> X / (C1*C2) 767 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) || 768 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) { 769 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 770 if (!multiplyOverflows(*C1, *C2, Product, IsSigned)) 771 return BinaryOperator::Create(I.getOpcode(), X, 772 ConstantInt::get(Ty, Product)); 773 } 774 775 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) || 776 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) { 777 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 778 779 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1. 780 if (isMultiple(*C2, *C1, Quotient, IsSigned)) { 781 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X, 782 ConstantInt::get(Ty, Quotient)); 783 NewDiv->setIsExact(I.isExact()); 784 return NewDiv; 785 } 786 787 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2. 788 if (isMultiple(*C1, *C2, Quotient, IsSigned)) { 789 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 790 ConstantInt::get(Ty, Quotient)); 791 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 792 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 793 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 794 return Mul; 795 } 796 } 797 798 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) && 799 *C1 != C1->getBitWidth() - 1) || 800 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) { 801 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned); 802 APInt C1Shifted = APInt::getOneBitSet( 803 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue())); 804 805 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1. 806 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) { 807 auto *BO = BinaryOperator::Create(I.getOpcode(), X, 808 ConstantInt::get(Ty, Quotient)); 809 BO->setIsExact(I.isExact()); 810 return BO; 811 } 812 813 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2. 814 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) { 815 auto *Mul = BinaryOperator::Create(Instruction::Mul, X, 816 ConstantInt::get(Ty, Quotient)); 817 auto *OBO = cast<OverflowingBinaryOperator>(Op0); 818 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap()); 819 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap()); 820 return Mul; 821 } 822 } 823 824 if (!C2->isNullValue()) // avoid X udiv 0 825 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I)) 826 return FoldedDiv; 827 } 828 829 if (match(Op0, m_One())) { 830 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?"); 831 if (IsSigned) { 832 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the 833 // result is one, if Op1 is -1 then the result is minus one, otherwise 834 // it's zero. 835 Value *Inc = Builder.CreateAdd(Op1, Op0); 836 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3)); 837 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0)); 838 } else { 839 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the 840 // result is one, otherwise it's zero. 841 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty); 842 } 843 } 844 845 // See if we can fold away this div instruction. 846 if (SimplifyDemandedInstructionBits(I)) 847 return &I; 848 849 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 850 Value *X, *Z; 851 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1 852 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 853 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 854 return BinaryOperator::Create(I.getOpcode(), X, Op1); 855 856 // (X << Y) / X -> 1 << Y 857 Value *Y; 858 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y)))) 859 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y); 860 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y)))) 861 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y); 862 863 // X / (X * Y) -> 1 / Y if the multiplication does not overflow. 864 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) { 865 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap(); 866 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap(); 867 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) { 868 replaceOperand(I, 0, ConstantInt::get(Ty, 1)); 869 replaceOperand(I, 1, Y); 870 return &I; 871 } 872 } 873 874 return nullptr; 875 } 876 877 static const unsigned MaxDepth = 6; 878 879 namespace { 880 881 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1, 882 const BinaryOperator &I, 883 InstCombinerImpl &IC); 884 885 /// Used to maintain state for visitUDivOperand(). 886 struct UDivFoldAction { 887 /// Informs visitUDiv() how to fold this operand. This can be zero if this 888 /// action joins two actions together. 889 FoldUDivOperandCb FoldAction; 890 891 /// Which operand to fold. 892 Value *OperandToFold; 893 894 union { 895 /// The instruction returned when FoldAction is invoked. 896 Instruction *FoldResult; 897 898 /// Stores the LHS action index if this action joins two actions together. 899 size_t SelectLHSIdx; 900 }; 901 902 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand) 903 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {} 904 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS) 905 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {} 906 }; 907 908 } // end anonymous namespace 909 910 // X udiv 2^C -> X >> C 911 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1, 912 const BinaryOperator &I, 913 InstCombinerImpl &IC) { 914 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1)); 915 if (!C1) 916 llvm_unreachable("Failed to constant fold udiv -> logbase2"); 917 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1); 918 if (I.isExact()) 919 LShr->setIsExact(); 920 return LShr; 921 } 922 923 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 924 // X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2) 925 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I, 926 InstCombinerImpl &IC) { 927 Value *ShiftLeft; 928 if (!match(Op1, m_ZExt(m_Value(ShiftLeft)))) 929 ShiftLeft = Op1; 930 931 Constant *CI; 932 Value *N; 933 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N)))) 934 llvm_unreachable("match should never fail here!"); 935 Constant *Log2Base = getLogBase2(N->getType(), CI); 936 if (!Log2Base) 937 llvm_unreachable("getLogBase2 should never fail here!"); 938 N = IC.Builder.CreateAdd(N, Log2Base); 939 if (Op1 != ShiftLeft) 940 N = IC.Builder.CreateZExt(N, Op1->getType()); 941 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N); 942 if (I.isExact()) 943 LShr->setIsExact(); 944 return LShr; 945 } 946 947 // Recursively visits the possible right hand operands of a udiv 948 // instruction, seeing through select instructions, to determine if we can 949 // replace the udiv with something simpler. If we find that an operand is not 950 // able to simplify the udiv, we abort the entire transformation. 951 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I, 952 SmallVectorImpl<UDivFoldAction> &Actions, 953 unsigned Depth = 0) { 954 // FIXME: assert that Op1 isn't/doesn't contain undef. 955 956 // Check to see if this is an unsigned division with an exact power of 2, 957 // if so, convert to a right shift. 958 if (match(Op1, m_Power2())) { 959 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1)); 960 return Actions.size(); 961 } 962 963 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 964 if (match(Op1, m_Shl(m_Power2(), m_Value())) || 965 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) { 966 Actions.push_back(UDivFoldAction(foldUDivShl, Op1)); 967 return Actions.size(); 968 } 969 970 // The remaining tests are all recursive, so bail out if we hit the limit. 971 if (Depth++ == MaxDepth) 972 return 0; 973 974 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 975 // FIXME: missed optimization: if one of the hands of select is/contains 976 // undef, just directly pick the other one. 977 // FIXME: can both hands contain undef? 978 if (size_t LHSIdx = 979 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth)) 980 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) { 981 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1)); 982 return Actions.size(); 983 } 984 985 return 0; 986 } 987 988 /// If we have zero-extended operands of an unsigned div or rem, we may be able 989 /// to narrow the operation (sink the zext below the math). 990 static Instruction *narrowUDivURem(BinaryOperator &I, 991 InstCombiner::BuilderTy &Builder) { 992 Instruction::BinaryOps Opcode = I.getOpcode(); 993 Value *N = I.getOperand(0); 994 Value *D = I.getOperand(1); 995 Type *Ty = I.getType(); 996 Value *X, *Y; 997 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) && 998 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) { 999 // udiv (zext X), (zext Y) --> zext (udiv X, Y) 1000 // urem (zext X), (zext Y) --> zext (urem X, Y) 1001 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y); 1002 return new ZExtInst(NarrowOp, Ty); 1003 } 1004 1005 Constant *C; 1006 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) || 1007 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) { 1008 // If the constant is the same in the smaller type, use the narrow version. 1009 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType()); 1010 if (ConstantExpr::getZExt(TruncC, Ty) != C) 1011 return nullptr; 1012 1013 // udiv (zext X), C --> zext (udiv X, C') 1014 // urem (zext X), C --> zext (urem X, C') 1015 // udiv C, (zext X) --> zext (udiv C', X) 1016 // urem C, (zext X) --> zext (urem C', X) 1017 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC) 1018 : Builder.CreateBinOp(Opcode, TruncC, X); 1019 return new ZExtInst(NarrowOp, Ty); 1020 } 1021 1022 return nullptr; 1023 } 1024 1025 Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) { 1026 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1), 1027 SQ.getWithInstruction(&I))) 1028 return replaceInstUsesWith(I, V); 1029 1030 if (Instruction *X = foldVectorBinop(I)) 1031 return X; 1032 1033 // Handle the integer div common cases 1034 if (Instruction *Common = commonIDivTransforms(I)) 1035 return Common; 1036 1037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1038 Value *X; 1039 const APInt *C1, *C2; 1040 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) { 1041 // (X lshr C1) udiv C2 --> X udiv (C2 << C1) 1042 bool Overflow; 1043 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow); 1044 if (!Overflow) { 1045 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value())); 1046 BinaryOperator *BO = BinaryOperator::CreateUDiv( 1047 X, ConstantInt::get(X->getType(), C2ShlC1)); 1048 if (IsExact) 1049 BO->setIsExact(); 1050 return BO; 1051 } 1052 } 1053 1054 // Op0 / C where C is large (negative) --> zext (Op0 >= C) 1055 // TODO: Could use isKnownNegative() to handle non-constant values. 1056 Type *Ty = I.getType(); 1057 if (match(Op1, m_Negative())) { 1058 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1); 1059 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1060 } 1061 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined) 1062 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1063 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1064 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1065 } 1066 1067 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder)) 1068 return NarrowDiv; 1069 1070 // If the udiv operands are non-overflowing multiplies with a common operand, 1071 // then eliminate the common factor: 1072 // (A * B) / (A * X) --> B / X (and commuted variants) 1073 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching. 1074 // TODO: If -reassociation handled this generally, we could remove this. 1075 Value *A, *B; 1076 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) { 1077 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) || 1078 match(Op1, m_NUWMul(m_Value(X), m_Specific(A)))) 1079 return BinaryOperator::CreateUDiv(B, X); 1080 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) || 1081 match(Op1, m_NUWMul(m_Value(X), m_Specific(B)))) 1082 return BinaryOperator::CreateUDiv(A, X); 1083 } 1084 1085 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...)))) 1086 SmallVector<UDivFoldAction, 6> UDivActions; 1087 if (visitUDivOperand(Op0, Op1, I, UDivActions)) 1088 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) { 1089 FoldUDivOperandCb Action = UDivActions[i].FoldAction; 1090 Value *ActionOp1 = UDivActions[i].OperandToFold; 1091 Instruction *Inst; 1092 if (Action) 1093 Inst = Action(Op0, ActionOp1, I, *this); 1094 else { 1095 // This action joins two actions together. The RHS of this action is 1096 // simply the last action we processed, we saved the LHS action index in 1097 // the joining action. 1098 size_t SelectRHSIdx = i - 1; 1099 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult; 1100 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx; 1101 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult; 1102 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(), 1103 SelectLHS, SelectRHS); 1104 } 1105 1106 // If this is the last action to process, return it to the InstCombiner. 1107 // Otherwise, we insert it before the UDiv and record it so that we may 1108 // use it as part of a joining action (i.e., a SelectInst). 1109 if (e - i != 1) { 1110 Inst->insertBefore(&I); 1111 UDivActions[i].FoldResult = Inst; 1112 } else 1113 return Inst; 1114 } 1115 1116 return nullptr; 1117 } 1118 1119 Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) { 1120 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1), 1121 SQ.getWithInstruction(&I))) 1122 return replaceInstUsesWith(I, V); 1123 1124 if (Instruction *X = foldVectorBinop(I)) 1125 return X; 1126 1127 // Handle the integer div common cases 1128 if (Instruction *Common = commonIDivTransforms(I)) 1129 return Common; 1130 1131 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1132 Type *Ty = I.getType(); 1133 Value *X; 1134 // sdiv Op0, -1 --> -Op0 1135 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined) 1136 if (match(Op1, m_AllOnes()) || 1137 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1138 return BinaryOperator::CreateNeg(Op0); 1139 1140 // X / INT_MIN --> X == INT_MIN 1141 if (match(Op1, m_SignMask())) 1142 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty); 1143 1144 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative 1145 // sdiv exact X, -1<<C --> -(ashr exact X, C) 1146 if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) || 1147 match(Op1, m_NegatedPower2()))) { 1148 bool DivisorWasNegative = match(Op1, m_NegatedPower2()); 1149 if (DivisorWasNegative) 1150 Op1 = ConstantExpr::getNeg(cast<Constant>(Op1)); 1151 auto *AShr = BinaryOperator::CreateExactAShr( 1152 Op0, getLogBase2(Ty, cast<Constant>(Op1)), I.getName()); 1153 if (!DivisorWasNegative) 1154 return AShr; 1155 Builder.Insert(AShr); 1156 AShr->setName(I.getName() + ".neg"); 1157 return BinaryOperator::CreateNeg(AShr, I.getName()); 1158 } 1159 1160 const APInt *Op1C; 1161 if (match(Op1, m_APInt(Op1C))) { 1162 // If the dividend is sign-extended and the constant divisor is small enough 1163 // to fit in the source type, shrink the division to the narrower type: 1164 // (sext X) sdiv C --> sext (X sdiv C) 1165 Value *Op0Src; 1166 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) && 1167 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) { 1168 1169 // In the general case, we need to make sure that the dividend is not the 1170 // minimum signed value because dividing that by -1 is UB. But here, we 1171 // know that the -1 divisor case is already handled above. 1172 1173 Constant *NarrowDivisor = 1174 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType()); 1175 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor); 1176 return new SExtInst(NarrowOp, Ty); 1177 } 1178 1179 // -X / C --> X / -C (if the negation doesn't overflow). 1180 // TODO: This could be enhanced to handle arbitrary vector constants by 1181 // checking if all elements are not the min-signed-val. 1182 if (!Op1C->isMinSignedValue() && 1183 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) { 1184 Constant *NegC = ConstantInt::get(Ty, -(*Op1C)); 1185 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC); 1186 BO->setIsExact(I.isExact()); 1187 return BO; 1188 } 1189 } 1190 1191 // -X / Y --> -(X / Y) 1192 Value *Y; 1193 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1194 return BinaryOperator::CreateNSWNeg( 1195 Builder.CreateSDiv(X, Y, I.getName(), I.isExact())); 1196 1197 // abs(X) / X --> X > -1 ? 1 : -1 1198 // X / abs(X) --> X > -1 ? 1 : -1 1199 if (match(&I, m_c_BinOp( 1200 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())), 1201 m_Deferred(X)))) { 1202 Constant *NegOne = ConstantInt::getAllOnesValue(Ty); 1203 Value *Cond = Builder.CreateICmpSGT(X, NegOne); 1204 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1), NegOne); 1205 } 1206 1207 // If the sign bits of both operands are zero (i.e. we can prove they are 1208 // unsigned inputs), turn this into a udiv. 1209 APInt Mask(APInt::getSignMask(Ty->getScalarSizeInBits())); 1210 if (MaskedValueIsZero(Op0, Mask, 0, &I)) { 1211 if (MaskedValueIsZero(Op1, Mask, 0, &I)) { 1212 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 1213 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1214 BO->setIsExact(I.isExact()); 1215 return BO; 1216 } 1217 1218 if (match(Op1, m_NegatedPower2())) { 1219 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) -> 1220 // -> -(X udiv (1 << C)) -> -(X u>> C) 1221 return BinaryOperator::CreateNeg(Builder.Insert(foldUDivPow2Cst( 1222 Op0, ConstantExpr::getNeg(cast<Constant>(Op1)), I, *this))); 1223 } 1224 1225 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1226 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 1227 // Safe because the only negative value (1 << Y) can take on is 1228 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 1229 // the sign bit set. 1230 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 1231 BO->setIsExact(I.isExact()); 1232 return BO; 1233 } 1234 } 1235 1236 return nullptr; 1237 } 1238 1239 /// Remove negation and try to convert division into multiplication. 1240 static Instruction *foldFDivConstantDivisor(BinaryOperator &I) { 1241 Constant *C; 1242 if (!match(I.getOperand(1), m_Constant(C))) 1243 return nullptr; 1244 1245 // -X / C --> X / -C 1246 Value *X; 1247 if (match(I.getOperand(0), m_FNeg(m_Value(X)))) 1248 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I); 1249 1250 // If the constant divisor has an exact inverse, this is always safe. If not, 1251 // then we can still create a reciprocal if fast-math-flags allow it and the 1252 // constant is a regular number (not zero, infinite, or denormal). 1253 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP()))) 1254 return nullptr; 1255 1256 // Disallow denormal constants because we don't know what would happen 1257 // on all targets. 1258 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1259 // denorms are flushed? 1260 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C); 1261 if (!RecipC->isNormalFP()) 1262 return nullptr; 1263 1264 // X / C --> X * (1 / C) 1265 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I); 1266 } 1267 1268 /// Remove negation and try to reassociate constant math. 1269 static Instruction *foldFDivConstantDividend(BinaryOperator &I) { 1270 Constant *C; 1271 if (!match(I.getOperand(0), m_Constant(C))) 1272 return nullptr; 1273 1274 // C / -X --> -C / X 1275 Value *X; 1276 if (match(I.getOperand(1), m_FNeg(m_Value(X)))) 1277 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I); 1278 1279 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal()) 1280 return nullptr; 1281 1282 // Try to reassociate C / X expressions where X includes another constant. 1283 Constant *C2, *NewC = nullptr; 1284 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) { 1285 // C / (X * C2) --> (C / C2) / X 1286 NewC = ConstantExpr::getFDiv(C, C2); 1287 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) { 1288 // C / (X / C2) --> (C * C2) / X 1289 NewC = ConstantExpr::getFMul(C, C2); 1290 } 1291 // Disallow denormal constants because we don't know what would happen 1292 // on all targets. 1293 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that 1294 // denorms are flushed? 1295 if (!NewC || !NewC->isNormalFP()) 1296 return nullptr; 1297 1298 return BinaryOperator::CreateFDivFMF(NewC, X, &I); 1299 } 1300 1301 Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) { 1302 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1), 1303 I.getFastMathFlags(), 1304 SQ.getWithInstruction(&I))) 1305 return replaceInstUsesWith(I, V); 1306 1307 if (Instruction *X = foldVectorBinop(I)) 1308 return X; 1309 1310 if (Instruction *R = foldFDivConstantDivisor(I)) 1311 return R; 1312 1313 if (Instruction *R = foldFDivConstantDividend(I)) 1314 return R; 1315 1316 if (Instruction *R = foldFPSignBitOps(I)) 1317 return R; 1318 1319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1320 if (isa<Constant>(Op0)) 1321 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 1322 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1323 return R; 1324 1325 if (isa<Constant>(Op1)) 1326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 1327 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1328 return R; 1329 1330 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) { 1331 Value *X, *Y; 1332 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1333 (!isa<Constant>(Y) || !isa<Constant>(Op1))) { 1334 // (X / Y) / Z => X / (Y * Z) 1335 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I); 1336 return BinaryOperator::CreateFDivFMF(X, YZ, &I); 1337 } 1338 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) && 1339 (!isa<Constant>(Y) || !isa<Constant>(Op0))) { 1340 // Z / (X / Y) => (Y * Z) / X 1341 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I); 1342 return BinaryOperator::CreateFDivFMF(YZ, X, &I); 1343 } 1344 // Z / (1.0 / Y) => (Y * Z) 1345 // 1346 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The 1347 // m_OneUse check is avoided because even in the case of the multiple uses 1348 // for 1.0/Y, the number of instructions remain the same and a division is 1349 // replaced by a multiplication. 1350 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) 1351 return BinaryOperator::CreateFMulFMF(Y, Op0, &I); 1352 } 1353 1354 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) { 1355 // sin(X) / cos(X) -> tan(X) 1356 // cos(X) / sin(X) -> 1/tan(X) (cotangent) 1357 Value *X; 1358 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) && 1359 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X))); 1360 bool IsCot = 1361 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) && 1362 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X))); 1363 1364 if ((IsTan || IsCot) && 1365 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) { 1366 IRBuilder<> B(&I); 1367 IRBuilder<>::FastMathFlagGuard FMFGuard(B); 1368 B.setFastMathFlags(I.getFastMathFlags()); 1369 AttributeList Attrs = 1370 cast<CallBase>(Op0)->getCalledFunction()->getAttributes(); 1371 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf, 1372 LibFunc_tanl, B, Attrs); 1373 if (IsCot) 1374 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res); 1375 return replaceInstUsesWith(I, Res); 1376 } 1377 } 1378 1379 // X / (X * Y) --> 1.0 / Y 1380 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed. 1381 // We can ignore the possibility that X is infinity because INF/INF is NaN. 1382 Value *X, *Y; 1383 if (I.hasNoNaNs() && I.hasAllowReassoc() && 1384 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) { 1385 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0)); 1386 replaceOperand(I, 1, Y); 1387 return &I; 1388 } 1389 1390 // X / fabs(X) -> copysign(1.0, X) 1391 // fabs(X) / X -> copysign(1.0, X) 1392 if (I.hasNoNaNs() && I.hasNoInfs() && 1393 (match(&I, 1394 m_FDiv(m_Value(X), m_Intrinsic<Intrinsic::fabs>(m_Deferred(X)))) || 1395 match(&I, m_FDiv(m_Intrinsic<Intrinsic::fabs>(m_Value(X)), 1396 m_Deferred(X))))) { 1397 Value *V = Builder.CreateBinaryIntrinsic( 1398 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I); 1399 return replaceInstUsesWith(I, V); 1400 } 1401 return nullptr; 1402 } 1403 1404 /// This function implements the transforms common to both integer remainder 1405 /// instructions (urem and srem). It is called by the visitors to those integer 1406 /// remainder instructions. 1407 /// Common integer remainder transforms 1408 Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) { 1409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1410 1411 // The RHS is known non-zero. 1412 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) 1413 return replaceOperand(I, 1, V); 1414 1415 // Handle cases involving: rem X, (select Cond, Y, Z) 1416 if (simplifyDivRemOfSelectWithZeroOp(I)) 1417 return &I; 1418 1419 if (isa<Constant>(Op1)) { 1420 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1422 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1423 return R; 1424 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) { 1425 const APInt *Op1Int; 1426 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() && 1427 (I.getOpcode() == Instruction::URem || 1428 !Op1Int->isMinSignedValue())) { 1429 // foldOpIntoPhi will speculate instructions to the end of the PHI's 1430 // predecessor blocks, so do this only if we know the srem or urem 1431 // will not fault. 1432 if (Instruction *NV = foldOpIntoPhi(I, PN)) 1433 return NV; 1434 } 1435 } 1436 1437 // See if we can fold away this rem instruction. 1438 if (SimplifyDemandedInstructionBits(I)) 1439 return &I; 1440 } 1441 } 1442 1443 return nullptr; 1444 } 1445 1446 Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) { 1447 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1), 1448 SQ.getWithInstruction(&I))) 1449 return replaceInstUsesWith(I, V); 1450 1451 if (Instruction *X = foldVectorBinop(I)) 1452 return X; 1453 1454 if (Instruction *common = commonIRemTransforms(I)) 1455 return common; 1456 1457 if (Instruction *NarrowRem = narrowUDivURem(I, Builder)) 1458 return NarrowRem; 1459 1460 // X urem Y -> X and Y-1, where Y is a power of 2, 1461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1462 Type *Ty = I.getType(); 1463 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) { 1464 // This may increase instruction count, we don't enforce that Y is a 1465 // constant. 1466 Constant *N1 = Constant::getAllOnesValue(Ty); 1467 Value *Add = Builder.CreateAdd(Op1, N1); 1468 return BinaryOperator::CreateAnd(Op0, Add); 1469 } 1470 1471 // 1 urem X -> zext(X != 1) 1472 if (match(Op0, m_One())) { 1473 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1)); 1474 return CastInst::CreateZExtOrBitCast(Cmp, Ty); 1475 } 1476 1477 // X urem C -> X < C ? X : X - C, where C >= signbit. 1478 if (match(Op1, m_Negative())) { 1479 Value *Cmp = Builder.CreateICmpULT(Op0, Op1); 1480 Value *Sub = Builder.CreateSub(Op0, Op1); 1481 return SelectInst::Create(Cmp, Op0, Sub); 1482 } 1483 1484 // If the divisor is a sext of a boolean, then the divisor must be max 1485 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also 1486 // max unsigned value. In that case, the remainder is 0: 1487 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0 1488 Value *X; 1489 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 1490 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty)); 1491 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0); 1492 } 1493 1494 return nullptr; 1495 } 1496 1497 Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) { 1498 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1), 1499 SQ.getWithInstruction(&I))) 1500 return replaceInstUsesWith(I, V); 1501 1502 if (Instruction *X = foldVectorBinop(I)) 1503 return X; 1504 1505 // Handle the integer rem common cases 1506 if (Instruction *Common = commonIRemTransforms(I)) 1507 return Common; 1508 1509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1510 { 1511 const APInt *Y; 1512 // X % -Y -> X % Y 1513 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) 1514 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y)); 1515 } 1516 1517 // -X srem Y --> -(X srem Y) 1518 Value *X, *Y; 1519 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y)))) 1520 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y)); 1521 1522 // If the sign bits of both operands are zero (i.e. we can prove they are 1523 // unsigned inputs), turn this into a urem. 1524 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits())); 1525 if (MaskedValueIsZero(Op1, Mask, 0, &I) && 1526 MaskedValueIsZero(Op0, Mask, 0, &I)) { 1527 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1528 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1529 } 1530 1531 // If it's a constant vector, flip any negative values positive. 1532 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1533 Constant *C = cast<Constant>(Op1); 1534 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements(); 1535 1536 bool hasNegative = false; 1537 bool hasMissing = false; 1538 for (unsigned i = 0; i != VWidth; ++i) { 1539 Constant *Elt = C->getAggregateElement(i); 1540 if (!Elt) { 1541 hasMissing = true; 1542 break; 1543 } 1544 1545 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1546 if (RHS->isNegative()) 1547 hasNegative = true; 1548 } 1549 1550 if (hasNegative && !hasMissing) { 1551 SmallVector<Constant *, 16> Elts(VWidth); 1552 for (unsigned i = 0; i != VWidth; ++i) { 1553 Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1555 if (RHS->isNegative()) 1556 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1557 } 1558 } 1559 1560 Constant *NewRHSV = ConstantVector::get(Elts); 1561 if (NewRHSV != C) // Don't loop on -MININT 1562 return replaceOperand(I, 1, NewRHSV); 1563 } 1564 } 1565 1566 return nullptr; 1567 } 1568 1569 Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) { 1570 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1), 1571 I.getFastMathFlags(), 1572 SQ.getWithInstruction(&I))) 1573 return replaceInstUsesWith(I, V); 1574 1575 if (Instruction *X = foldVectorBinop(I)) 1576 return X; 1577 1578 return nullptr; 1579 } 1580