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