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