InstCombineMulDivRem.cpp revision da2ed458b4e7066fc414c403173b882ccc2c8833
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 "InstCombine.h" 16#include "llvm/Analysis/InstructionSimplify.h" 17#include "llvm/IR/IntrinsicInst.h" 18#include "llvm/Support/PatternMatch.h" 19using namespace llvm; 20using namespace PatternMatch; 21 22 23/// simplifyValueKnownNonZero - The specific integer value is used in a context 24/// where it is known to be non-zero. If this allows us to simplify the 25/// computation, do so and return the new operand, otherwise return null. 26static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) { 27 // If V has multiple uses, then we would have to do more analysis to determine 28 // if this is safe. For example, the use could be in dynamically unreached 29 // code. 30 if (!V->hasOneUse()) return 0; 31 32 bool MadeChange = false; 33 34 // ((1 << A) >>u B) --> (1 << (A-B)) 35 // Because V cannot be zero, we know that B is less than A. 36 Value *A = 0, *B = 0, *PowerOf2 = 0; 37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))), 38 m_Value(B))) && 39 // The "1" can be any value known to be a power of 2. 40 isKnownToBeAPowerOfTwo(PowerOf2)) { 41 A = IC.Builder->CreateSub(A, B); 42 return IC.Builder->CreateShl(PowerOf2, A); 43 } 44 45 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it 46 // inexact. Similarly for <<. 47 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V)) 48 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) { 49 // We know that this is an exact/nuw shift and that the input is a 50 // non-zero context as well. 51 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) { 52 I->setOperand(0, V2); 53 MadeChange = true; 54 } 55 56 if (I->getOpcode() == Instruction::LShr && !I->isExact()) { 57 I->setIsExact(); 58 MadeChange = true; 59 } 60 61 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) { 62 I->setHasNoUnsignedWrap(); 63 MadeChange = true; 64 } 65 } 66 67 // TODO: Lots more we could do here: 68 // If V is a phi node, we can call this on each of its operands. 69 // "select cond, X, 0" can simplify to "X". 70 71 return MadeChange ? V : 0; 72} 73 74 75/// MultiplyOverflows - True if the multiply can not be expressed in an int 76/// this size. 77static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) { 78 uint32_t W = C1->getBitWidth(); 79 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue(); 80 if (sign) { 81 LHSExt = LHSExt.sext(W * 2); 82 RHSExt = RHSExt.sext(W * 2); 83 } else { 84 LHSExt = LHSExt.zext(W * 2); 85 RHSExt = RHSExt.zext(W * 2); 86 } 87 88 APInt MulExt = LHSExt * RHSExt; 89 90 if (!sign) 91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W)); 92 93 APInt Min = APInt::getSignedMinValue(W).sext(W * 2); 94 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2); 95 return MulExt.slt(Min) || MulExt.sgt(Max); 96} 97 98Instruction *InstCombiner::visitMul(BinaryOperator &I) { 99 bool Changed = SimplifyAssociativeOrCommutative(I); 100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 101 102 if (Value *V = SimplifyMulInst(Op0, Op1, TD)) 103 return ReplaceInstUsesWith(I, V); 104 105 if (Value *V = SimplifyUsingDistributiveLaws(I)) 106 return ReplaceInstUsesWith(I, V); 107 108 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X 109 return BinaryOperator::CreateNeg(Op0, I.getName()); 110 111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 112 113 // ((X << C1)*C2) == (X * (C2 << C1)) 114 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0)) 115 if (SI->getOpcode() == Instruction::Shl) 116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1))) 117 return BinaryOperator::CreateMul(SI->getOperand(0), 118 ConstantExpr::getShl(CI, ShOp)); 119 120 const APInt &Val = CI->getValue(); 121 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C 122 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2()); 123 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst); 124 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap(); 125 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap(); 126 return Shl; 127 } 128 129 // Canonicalize (X+C1)*CI -> X*CI+C1*CI. 130 { Value *X; ConstantInt *C1; 131 if (Op0->hasOneUse() && 132 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) { 133 Value *Add = Builder->CreateMul(X, CI); 134 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI)); 135 } 136 } 137 138 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n 139 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n 140 // The "* (2**n)" thus becomes a potential shifting opportunity. 141 { 142 const APInt & Val = CI->getValue(); 143 const APInt &PosVal = Val.abs(); 144 if (Val.isNegative() && PosVal.isPowerOf2()) { 145 Value *X = 0, *Y = 0; 146 if (Op0->hasOneUse()) { 147 ConstantInt *C1; 148 Value *Sub = 0; 149 if (match(Op0, m_Sub(m_Value(Y), m_Value(X)))) 150 Sub = Builder->CreateSub(X, Y, "suba"); 151 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1)))) 152 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc"); 153 if (Sub) 154 return 155 BinaryOperator::CreateMul(Sub, 156 ConstantInt::get(Y->getType(), PosVal)); 157 } 158 } 159 } 160 } 161 162 // Simplify mul instructions with a constant RHS. 163 if (isa<Constant>(Op1)) { 164 // Try to fold constant mul into select arguments. 165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 166 if (Instruction *R = FoldOpIntoSelect(I, SI)) 167 return R; 168 169 if (isa<PHINode>(Op0)) 170 if (Instruction *NV = FoldOpIntoPhi(I)) 171 return NV; 172 } 173 174 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y 175 if (Value *Op1v = dyn_castNegVal(Op1)) 176 return BinaryOperator::CreateMul(Op0v, Op1v); 177 178 // (X / Y) * Y = X - (X % Y) 179 // (X / Y) * -Y = (X % Y) - X 180 { 181 Value *Op1C = Op1; 182 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0); 183 if (!BO || 184 (BO->getOpcode() != Instruction::UDiv && 185 BO->getOpcode() != Instruction::SDiv)) { 186 Op1C = Op0; 187 BO = dyn_cast<BinaryOperator>(Op1); 188 } 189 Value *Neg = dyn_castNegVal(Op1C); 190 if (BO && BO->hasOneUse() && 191 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) && 192 (BO->getOpcode() == Instruction::UDiv || 193 BO->getOpcode() == Instruction::SDiv)) { 194 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1); 195 196 // If the division is exact, X % Y is zero, so we end up with X or -X. 197 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO)) 198 if (SDiv->isExact()) { 199 if (Op1BO == Op1C) 200 return ReplaceInstUsesWith(I, Op0BO); 201 return BinaryOperator::CreateNeg(Op0BO); 202 } 203 204 Value *Rem; 205 if (BO->getOpcode() == Instruction::UDiv) 206 Rem = Builder->CreateURem(Op0BO, Op1BO); 207 else 208 Rem = Builder->CreateSRem(Op0BO, Op1BO); 209 Rem->takeName(BO); 210 211 if (Op1BO == Op1C) 212 return BinaryOperator::CreateSub(Op0BO, Rem); 213 return BinaryOperator::CreateSub(Rem, Op0BO); 214 } 215 } 216 217 /// i1 mul -> i1 and. 218 if (I.getType()->isIntegerTy(1)) 219 return BinaryOperator::CreateAnd(Op0, Op1); 220 221 // X*(1 << Y) --> X << Y 222 // (1 << Y)*X --> X << Y 223 { 224 Value *Y; 225 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) 226 return BinaryOperator::CreateShl(Op1, Y); 227 if (match(Op1, m_Shl(m_One(), m_Value(Y)))) 228 return BinaryOperator::CreateShl(Op0, Y); 229 } 230 231 // If one of the operands of the multiply is a cast from a boolean value, then 232 // we know the bool is either zero or one, so this is a 'masking' multiply. 233 // X * Y (where Y is 0 or 1) -> X & (0-Y) 234 if (!I.getType()->isVectorTy()) { 235 // -2 is "-1 << 1" so it is all bits set except the low one. 236 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true); 237 238 Value *BoolCast = 0, *OtherOp = 0; 239 if (MaskedValueIsZero(Op0, Negative2)) 240 BoolCast = Op0, OtherOp = Op1; 241 else if (MaskedValueIsZero(Op1, Negative2)) 242 BoolCast = Op1, OtherOp = Op0; 243 244 if (BoolCast) { 245 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()), 246 BoolCast); 247 return BinaryOperator::CreateAnd(V, OtherOp); 248 } 249 } 250 251 return Changed ? &I : 0; 252} 253 254// 255// Detect pattern: 256// 257// log2(Y*0.5) 258// 259// And check for corresponding fast math flags 260// 261 262static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) { 263 264 if (!Op->hasOneUse()) 265 return; 266 267 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op); 268 if (!II) 269 return; 270 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra()) 271 return; 272 Log2 = II; 273 274 Value *OpLog2Of = II->getArgOperand(0); 275 if (!OpLog2Of->hasOneUse()) 276 return; 277 278 Instruction *I = dyn_cast<Instruction>(OpLog2Of); 279 if (!I) 280 return; 281 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra()) 282 return; 283 284 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0)); 285 if (CFP && CFP->isExactlyValue(0.5)) { 286 Y = I->getOperand(1); 287 return; 288 } 289 CFP = dyn_cast<ConstantFP>(I->getOperand(1)); 290 if (CFP && CFP->isExactlyValue(0.5)) 291 Y = I->getOperand(0); 292} 293 294/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns 295/// true iff the given value is FMul or FDiv with one and only one operand 296/// being a normal constant (i.e. not Zero/NaN/Infinity). 297static bool isFMulOrFDivWithConstant(Value *V) { 298 Instruction *I = dyn_cast<Instruction>(V); 299 if (!I || (I->getOpcode() != Instruction::FMul && 300 I->getOpcode() != Instruction::FDiv)) 301 return false; 302 303 ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0)); 304 ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1)); 305 306 if (C0 && C1) 307 return false; 308 309 return (C0 && C0->getValueAPF().isNormal()) || 310 (C1 && C1->getValueAPF().isNormal()); 311} 312 313static bool isNormalFp(const ConstantFP *C) { 314 const APFloat &Flt = C->getValueAPF(); 315 return Flt.isNormal() && !Flt.isDenormal(); 316} 317 318/// foldFMulConst() is a helper routine of InstCombiner::visitFMul(). 319/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand 320/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true). 321/// This function is to simplify "FMulOrDiv * C" and returns the 322/// resulting expression. Note that this function could return NULL in 323/// case the constants cannot be folded into a normal floating-point. 324/// 325Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C, 326 Instruction *InsertBefore) { 327 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid"); 328 329 Value *Opnd0 = FMulOrDiv->getOperand(0); 330 Value *Opnd1 = FMulOrDiv->getOperand(1); 331 332 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0); 333 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1); 334 335 BinaryOperator *R = 0; 336 337 // (X * C0) * C => X * (C0*C) 338 if (FMulOrDiv->getOpcode() == Instruction::FMul) { 339 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C); 340 if (isNormalFp(cast<ConstantFP>(F))) 341 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F); 342 } else { 343 if (C0) { 344 // (C0 / X) * C => (C0 * C) / X 345 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C)); 346 if (isNormalFp(F)) 347 R = BinaryOperator::CreateFDiv(F, Opnd1); 348 } else { 349 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal 350 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1)); 351 if (isNormalFp(F)) { 352 R = BinaryOperator::CreateFMul(Opnd0, F); 353 } else { 354 // (X / C1) * C => X / (C1/C) 355 Constant *F = ConstantExpr::getFDiv(C1, C); 356 if (isNormalFp(cast<ConstantFP>(F))) 357 R = BinaryOperator::CreateFDiv(Opnd0, F); 358 } 359 } 360 } 361 362 if (R) { 363 R->setHasUnsafeAlgebra(true); 364 InsertNewInstWith(R, *InsertBefore); 365 } 366 367 return R; 368} 369 370Instruction *InstCombiner::visitFMul(BinaryOperator &I) { 371 bool Changed = SimplifyAssociativeOrCommutative(I); 372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 373 374 if (isa<Constant>(Op0)) 375 std::swap(Op0, Op1); 376 377 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD)) 378 return ReplaceInstUsesWith(I, V); 379 380 bool AllowReassociate = I.hasUnsafeAlgebra(); 381 382 // Simplify mul instructions with a constant RHS. 383 if (isa<Constant>(Op1)) { 384 // Try to fold constant mul into select arguments. 385 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 386 if (Instruction *R = FoldOpIntoSelect(I, SI)) 387 return R; 388 389 if (isa<PHINode>(Op0)) 390 if (Instruction *NV = FoldOpIntoPhi(I)) 391 return NV; 392 393 ConstantFP *C = dyn_cast<ConstantFP>(Op1); 394 if (C && AllowReassociate && C->getValueAPF().isNormal()) { 395 // Let MDC denote an expression in one of these forms: 396 // X * C, C/X, X/C, where C is a constant. 397 // 398 // Try to simplify "MDC * Constant" 399 if (isFMulOrFDivWithConstant(Op0)) { 400 Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I); 401 if (V) 402 return ReplaceInstUsesWith(I, V); 403 } 404 405 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C) 406 Instruction *FAddSub = dyn_cast<Instruction>(Op0); 407 if (FAddSub && 408 (FAddSub->getOpcode() == Instruction::FAdd || 409 FAddSub->getOpcode() == Instruction::FSub)) { 410 Value *Opnd0 = FAddSub->getOperand(0); 411 Value *Opnd1 = FAddSub->getOperand(1); 412 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0); 413 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1); 414 bool Swap = false; 415 if (C0) { 416 std::swap(C0, C1); 417 std::swap(Opnd0, Opnd1); 418 Swap = true; 419 } 420 421 if (C1 && C1->getValueAPF().isNormal() && 422 isFMulOrFDivWithConstant(Opnd0)) { 423 Value *M1 = ConstantExpr::getFMul(C1, C); 424 Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ? 425 foldFMulConst(cast<Instruction>(Opnd0), C, &I) : 426 0; 427 if (M0 && M1) { 428 if (Swap && FAddSub->getOpcode() == Instruction::FSub) 429 std::swap(M0, M1); 430 431 Value *R = (FAddSub->getOpcode() == Instruction::FAdd) ? 432 BinaryOperator::CreateFAdd(M0, M1) : 433 BinaryOperator::CreateFSub(M0, M1); 434 Instruction *RI = cast<Instruction>(R); 435 RI->copyFastMathFlags(&I); 436 return RI; 437 } 438 } 439 } 440 } 441 } 442 443 444 // Under unsafe algebra do: 445 // X * log2(0.5*Y) = X*log2(Y) - X 446 if (I.hasUnsafeAlgebra()) { 447 Value *OpX = NULL; 448 Value *OpY = NULL; 449 IntrinsicInst *Log2; 450 detectLog2OfHalf(Op0, OpY, Log2); 451 if (OpY) { 452 OpX = Op1; 453 } else { 454 detectLog2OfHalf(Op1, OpY, Log2); 455 if (OpY) { 456 OpX = Op0; 457 } 458 } 459 // if pattern detected emit alternate sequence 460 if (OpX && OpY) { 461 Log2->setArgOperand(0, OpY); 462 Value *FMulVal = Builder->CreateFMul(OpX, Log2); 463 Instruction *FMul = cast<Instruction>(FMulVal); 464 FMul->copyFastMathFlags(Log2); 465 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX); 466 FSub->copyFastMathFlags(Log2); 467 return FSub; 468 } 469 } 470 471 // Handle symmetric situation in a 2-iteration loop 472 Value *Opnd0 = Op0; 473 Value *Opnd1 = Op1; 474 for (int i = 0; i < 2; i++) { 475 bool IgnoreZeroSign = I.hasNoSignedZeros(); 476 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) { 477 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign); 478 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign); 479 480 // -X * -Y => X*Y 481 if (N1) 482 return BinaryOperator::CreateFMul(N0, N1); 483 484 if (Opnd0->hasOneUse()) { 485 // -X * Y => -(X*Y) (Promote negation as high as possible) 486 Value *T = Builder->CreateFMul(N0, Opnd1); 487 cast<Instruction>(T)->setDebugLoc(I.getDebugLoc()); 488 Instruction *Neg = BinaryOperator::CreateFNeg(T); 489 if (I.getFastMathFlags().any()) { 490 cast<Instruction>(T)->copyFastMathFlags(&I); 491 Neg->copyFastMathFlags(&I); 492 } 493 return Neg; 494 } 495 } 496 497 // (X*Y) * X => (X*X) * Y where Y != X 498 // The purpose is two-fold: 499 // 1) to form a power expression (of X). 500 // 2) potentially shorten the critical path: After transformation, the 501 // latency of the instruction Y is amortized by the expression of X*X, 502 // and therefore Y is in a "less critical" position compared to what it 503 // was before the transformation. 504 // 505 if (AllowReassociate) { 506 Value *Opnd0_0, *Opnd0_1; 507 if (Opnd0->hasOneUse() && 508 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) { 509 Value *Y = 0; 510 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1) 511 Y = Opnd0_1; 512 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1) 513 Y = Opnd0_0; 514 515 if (Y) { 516 Instruction *T = cast<Instruction>(Builder->CreateFMul(Opnd1, Opnd1)); 517 T->copyFastMathFlags(&I); 518 T->setDebugLoc(I.getDebugLoc()); 519 520 Instruction *R = BinaryOperator::CreateFMul(T, Y); 521 R->copyFastMathFlags(&I); 522 return R; 523 } 524 } 525 } 526 527 // B * (uitofp i1 C) -> select C, B, 0 528 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 529 Value *LHS = Op0, *RHS = Op1; 530 Value *B, *C; 531 if (!match(RHS, m_UIToFp(m_Value(C)))) 532 std::swap(LHS, RHS); 533 534 if (match(RHS, m_UIToFp(m_Value(C))) && C->getType()->isIntegerTy(1)) { 535 B = LHS; 536 Value *Zero = ConstantFP::getNegativeZero(B->getType()); 537 return SelectInst::Create(C, B, Zero); 538 } 539 } 540 541 // A * (1 - uitofp i1 C) -> select C, 0, A 542 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) { 543 Value *LHS = Op0, *RHS = Op1; 544 Value *A, *C; 545 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFp(m_Value(C))))) 546 std::swap(LHS, RHS); 547 548 if (match(RHS, m_FSub(m_FPOne(), m_UIToFp(m_Value(C)))) && 549 C->getType()->isIntegerTy(1)) { 550 A = LHS; 551 Value *Zero = ConstantFP::getNegativeZero(A->getType()); 552 return SelectInst::Create(C, Zero, A); 553 } 554 } 555 556 if (!isa<Constant>(Op1)) 557 std::swap(Opnd0, Opnd1); 558 else 559 break; 560 } 561 562 return Changed ? &I : 0; 563} 564 565/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select 566/// instruction. 567bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) { 568 SelectInst *SI = cast<SelectInst>(I.getOperand(1)); 569 570 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y 571 int NonNullOperand = -1; 572 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1))) 573 if (ST->isNullValue()) 574 NonNullOperand = 2; 575 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y 576 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2))) 577 if (ST->isNullValue()) 578 NonNullOperand = 1; 579 580 if (NonNullOperand == -1) 581 return false; 582 583 Value *SelectCond = SI->getOperand(0); 584 585 // Change the div/rem to use 'Y' instead of the select. 586 I.setOperand(1, SI->getOperand(NonNullOperand)); 587 588 // Okay, we know we replace the operand of the div/rem with 'Y' with no 589 // problem. However, the select, or the condition of the select may have 590 // multiple uses. Based on our knowledge that the operand must be non-zero, 591 // propagate the known value for the select into other uses of it, and 592 // propagate a known value of the condition into its other users. 593 594 // If the select and condition only have a single use, don't bother with this, 595 // early exit. 596 if (SI->use_empty() && SelectCond->hasOneUse()) 597 return true; 598 599 // Scan the current block backward, looking for other uses of SI. 600 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin(); 601 602 while (BBI != BBFront) { 603 --BBI; 604 // If we found a call to a function, we can't assume it will return, so 605 // information from below it cannot be propagated above it. 606 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI)) 607 break; 608 609 // Replace uses of the select or its condition with the known values. 610 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); 611 I != E; ++I) { 612 if (*I == SI) { 613 *I = SI->getOperand(NonNullOperand); 614 Worklist.Add(BBI); 615 } else if (*I == SelectCond) { 616 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) : 617 ConstantInt::getFalse(BBI->getContext()); 618 Worklist.Add(BBI); 619 } 620 } 621 622 // If we past the instruction, quit looking for it. 623 if (&*BBI == SI) 624 SI = 0; 625 if (&*BBI == SelectCond) 626 SelectCond = 0; 627 628 // If we ran out of things to eliminate, break out of the loop. 629 if (SelectCond == 0 && SI == 0) 630 break; 631 632 } 633 return true; 634} 635 636 637/// This function implements the transforms common to both integer division 638/// instructions (udiv and sdiv). It is called by the visitors to those integer 639/// division instructions. 640/// @brief Common integer divide transforms 641Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) { 642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 643 644 // The RHS is known non-zero. 645 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 646 I.setOperand(1, V); 647 return &I; 648 } 649 650 // Handle cases involving: [su]div X, (select Cond, Y, Z) 651 // This does not apply for fdiv. 652 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 653 return &I; 654 655 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 656 // (X / C1) / C2 -> X / (C1*C2) 657 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) 658 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode()) 659 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) { 660 if (MultiplyOverflows(RHS, LHSRHS, 661 I.getOpcode()==Instruction::SDiv)) 662 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); 663 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0), 664 ConstantExpr::getMul(RHS, LHSRHS)); 665 } 666 667 if (!RHS->isZero()) { // avoid X udiv 0 668 if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) 669 if (Instruction *R = FoldOpIntoSelect(I, SI)) 670 return R; 671 if (isa<PHINode>(Op0)) 672 if (Instruction *NV = FoldOpIntoPhi(I)) 673 return NV; 674 } 675 } 676 677 // See if we can fold away this div instruction. 678 if (SimplifyDemandedInstructionBits(I)) 679 return &I; 680 681 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y 682 Value *X = 0, *Z = 0; 683 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1 684 bool isSigned = I.getOpcode() == Instruction::SDiv; 685 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) || 686 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1))))) 687 return BinaryOperator::Create(I.getOpcode(), X, Op1); 688 } 689 690 return 0; 691} 692 693/// dyn_castZExtVal - Checks if V is a zext or constant that can 694/// be truncated to Ty without losing bits. 695static Value *dyn_castZExtVal(Value *V, Type *Ty) { 696 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) { 697 if (Z->getSrcTy() == Ty) 698 return Z->getOperand(0); 699 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) { 700 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth()) 701 return ConstantExpr::getTrunc(C, Ty); 702 } 703 return 0; 704} 705 706Instruction *InstCombiner::visitUDiv(BinaryOperator &I) { 707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 708 709 if (Value *V = SimplifyUDivInst(Op0, Op1, TD)) 710 return ReplaceInstUsesWith(I, V); 711 712 // Handle the integer div common cases 713 if (Instruction *Common = commonIDivTransforms(I)) 714 return Common; 715 716 { 717 // X udiv 2^C -> X >> C 718 // Check to see if this is an unsigned division with an exact power of 2, 719 // if so, convert to a right shift. 720 const APInt *C; 721 if (match(Op1, m_Power2(C))) { 722 BinaryOperator *LShr = 723 BinaryOperator::CreateLShr(Op0, 724 ConstantInt::get(Op0->getType(), 725 C->logBase2())); 726 if (I.isExact()) LShr->setIsExact(); 727 return LShr; 728 } 729 } 730 731 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) { 732 // X udiv C, where C >= signbit 733 if (C->getValue().isNegative()) { 734 Value *IC = Builder->CreateICmpULT(Op0, C); 735 return SelectInst::Create(IC, Constant::getNullValue(I.getType()), 736 ConstantInt::get(I.getType(), 1)); 737 } 738 } 739 740 // (x lshr C1) udiv C2 --> x udiv (C2 << C1) 741 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) { 742 Value *X; 743 ConstantInt *C1; 744 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) { 745 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1)); 746 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC)); 747 } 748 } 749 750 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) 751 { const APInt *CI; Value *N; 752 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) || 753 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) { 754 if (*CI != 1) 755 N = Builder->CreateAdd(N, 756 ConstantInt::get(N->getType(), CI->logBase2())); 757 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1)) 758 N = Builder->CreateZExt(N, Z->getDestTy()); 759 if (I.isExact()) 760 return BinaryOperator::CreateExactLShr(Op0, N); 761 return BinaryOperator::CreateLShr(Op0, N); 762 } 763 } 764 765 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2) 766 // where C1&C2 are powers of two. 767 { Value *Cond; const APInt *C1, *C2; 768 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) { 769 // Construct the "on true" case of the select 770 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t", 771 I.isExact()); 772 773 // Construct the "on false" case of the select 774 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f", 775 I.isExact()); 776 777 // construct the select instruction and return it. 778 return SelectInst::Create(Cond, TSI, FSI); 779 } 780 } 781 782 // (zext A) udiv (zext B) --> zext (A udiv B) 783 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 784 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 785 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", 786 I.isExact()), 787 I.getType()); 788 789 return 0; 790} 791 792Instruction *InstCombiner::visitSDiv(BinaryOperator &I) { 793 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 794 795 if (Value *V = SimplifySDivInst(Op0, Op1, TD)) 796 return ReplaceInstUsesWith(I, V); 797 798 // Handle the integer div common cases 799 if (Instruction *Common = commonIDivTransforms(I)) 800 return Common; 801 802 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { 803 // sdiv X, -1 == -X 804 if (RHS->isAllOnesValue()) 805 return BinaryOperator::CreateNeg(Op0); 806 807 // sdiv X, C --> ashr exact X, log2(C) 808 if (I.isExact() && RHS->getValue().isNonNegative() && 809 RHS->getValue().isPowerOf2()) { 810 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(), 811 RHS->getValue().exactLogBase2()); 812 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName()); 813 } 814 815 // -X/C --> X/-C provided the negation doesn't overflow. 816 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0)) 817 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap()) 818 return BinaryOperator::CreateSDiv(Sub->getOperand(1), 819 ConstantExpr::getNeg(RHS)); 820 } 821 822 // If the sign bits of both operands are zero (i.e. we can prove they are 823 // unsigned inputs), turn this into a udiv. 824 if (I.getType()->isIntegerTy()) { 825 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 826 if (MaskedValueIsZero(Op0, Mask)) { 827 if (MaskedValueIsZero(Op1, Mask)) { 828 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set 829 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 830 } 831 832 if (match(Op1, m_Shl(m_Power2(), m_Value()))) { 833 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y) 834 // Safe because the only negative value (1 << Y) can take on is 835 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have 836 // the sign bit set. 837 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); 838 } 839 } 840 } 841 842 return 0; 843} 844 845/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special 846/// FP value and: 847/// 1) 1/C is exact, or 848/// 2) reciprocal is allowed. 849/// If the conversion was successful, the simplified expression "X * 1/C" is 850/// returned; otherwise, NULL is returned. 851/// 852static Instruction *CvtFDivConstToReciprocal(Value *Dividend, 853 ConstantFP *Divisor, 854 bool AllowReciprocal) { 855 const APFloat &FpVal = Divisor->getValueAPF(); 856 APFloat Reciprocal(FpVal.getSemantics()); 857 bool Cvt = FpVal.getExactInverse(&Reciprocal); 858 859 if (!Cvt && AllowReciprocal && FpVal.isNormal()) { 860 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f); 861 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven); 862 Cvt = !Reciprocal.isDenormal(); 863 } 864 865 if (!Cvt) 866 return 0; 867 868 ConstantFP *R; 869 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal); 870 return BinaryOperator::CreateFMul(Dividend, R); 871} 872 873Instruction *InstCombiner::visitFDiv(BinaryOperator &I) { 874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 875 876 if (Value *V = SimplifyFDivInst(Op0, Op1, TD)) 877 return ReplaceInstUsesWith(I, V); 878 879 bool AllowReassociate = I.hasUnsafeAlgebra(); 880 bool AllowReciprocal = I.hasAllowReciprocal(); 881 882 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) { 883 if (AllowReassociate) { 884 ConstantFP *C1 = 0; 885 ConstantFP *C2 = Op1C; 886 Value *X; 887 Instruction *Res = 0; 888 889 if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) { 890 // (X*C1)/C2 => X * (C1/C2) 891 // 892 Constant *C = ConstantExpr::getFDiv(C1, C2); 893 const APFloat &F = cast<ConstantFP>(C)->getValueAPF(); 894 if (F.isNormal() && !F.isDenormal()) 895 Res = BinaryOperator::CreateFMul(X, C); 896 } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) { 897 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed] 898 // 899 Constant *C = ConstantExpr::getFMul(C1, C2); 900 const APFloat &F = cast<ConstantFP>(C)->getValueAPF(); 901 if (F.isNormal() && !F.isDenormal()) { 902 Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C), 903 AllowReciprocal); 904 if (!Res) 905 Res = BinaryOperator::CreateFDiv(X, C); 906 } 907 } 908 909 if (Res) { 910 Res->setFastMathFlags(I.getFastMathFlags()); 911 return Res; 912 } 913 } 914 915 // X / C => X * 1/C 916 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) 917 return T; 918 919 return 0; 920 } 921 922 if (AllowReassociate && isa<ConstantFP>(Op0)) { 923 ConstantFP *C1 = cast<ConstantFP>(Op0), *C2; 924 Constant *Fold = 0; 925 Value *X; 926 bool CreateDiv = true; 927 928 // C1 / (X*C2) => (C1/C2) / X 929 if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2)))) 930 Fold = ConstantExpr::getFDiv(C1, C2); 931 else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) { 932 // C1 / (X/C2) => (C1*C2) / X 933 Fold = ConstantExpr::getFMul(C1, C2); 934 } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) { 935 // C1 / (C2/X) => (C1/C2) * X 936 Fold = ConstantExpr::getFDiv(C1, C2); 937 CreateDiv = false; 938 } 939 940 if (Fold) { 941 const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF(); 942 if (FoldC.isNormal() && !FoldC.isDenormal()) { 943 Instruction *R = CreateDiv ? 944 BinaryOperator::CreateFDiv(Fold, X) : 945 BinaryOperator::CreateFMul(X, Fold); 946 R->setFastMathFlags(I.getFastMathFlags()); 947 return R; 948 } 949 } 950 return 0; 951 } 952 953 if (AllowReassociate) { 954 Value *X, *Y; 955 Value *NewInst = 0; 956 Instruction *SimpR = 0; 957 958 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) { 959 // (X/Y) / Z => X / (Y*Z) 960 // 961 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) { 962 NewInst = Builder->CreateFMul(Y, Op1); 963 SimpR = BinaryOperator::CreateFDiv(X, NewInst); 964 } 965 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) { 966 // Z / (X/Y) => Z*Y / X 967 // 968 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) { 969 NewInst = Builder->CreateFMul(Op0, Y); 970 SimpR = BinaryOperator::CreateFDiv(NewInst, X); 971 } 972 } 973 974 if (NewInst) { 975 if (Instruction *T = dyn_cast<Instruction>(NewInst)) 976 T->setDebugLoc(I.getDebugLoc()); 977 SimpR->setFastMathFlags(I.getFastMathFlags()); 978 return SimpR; 979 } 980 } 981 982 return 0; 983} 984 985/// This function implements the transforms common to both integer remainder 986/// instructions (urem and srem). It is called by the visitors to those integer 987/// remainder instructions. 988/// @brief Common integer remainder transforms 989Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) { 990 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 991 992 // The RHS is known non-zero. 993 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) { 994 I.setOperand(1, V); 995 return &I; 996 } 997 998 // Handle cases involving: rem X, (select Cond, Y, Z) 999 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1000 return &I; 1001 1002 if (isa<ConstantInt>(Op1)) { 1003 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { 1004 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { 1005 if (Instruction *R = FoldOpIntoSelect(I, SI)) 1006 return R; 1007 } else if (isa<PHINode>(Op0I)) { 1008 if (Instruction *NV = FoldOpIntoPhi(I)) 1009 return NV; 1010 } 1011 1012 // See if we can fold away this rem instruction. 1013 if (SimplifyDemandedInstructionBits(I)) 1014 return &I; 1015 } 1016 } 1017 1018 return 0; 1019} 1020 1021Instruction *InstCombiner::visitURem(BinaryOperator &I) { 1022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1023 1024 if (Value *V = SimplifyURemInst(Op0, Op1, TD)) 1025 return ReplaceInstUsesWith(I, V); 1026 1027 if (Instruction *common = commonIRemTransforms(I)) 1028 return common; 1029 1030 // (zext A) urem (zext B) --> zext (A urem B) 1031 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0)) 1032 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy())) 1033 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1), 1034 I.getType()); 1035 1036 // X urem Y -> X and Y-1, where Y is a power of 2, 1037 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) { 1038 Constant *N1 = Constant::getAllOnesValue(I.getType()); 1039 Value *Add = Builder->CreateAdd(Op1, N1); 1040 return BinaryOperator::CreateAnd(Op0, Add); 1041 } 1042 1043 return 0; 1044} 1045 1046Instruction *InstCombiner::visitSRem(BinaryOperator &I) { 1047 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1048 1049 if (Value *V = SimplifySRemInst(Op0, Op1, TD)) 1050 return ReplaceInstUsesWith(I, V); 1051 1052 // Handle the integer rem common cases 1053 if (Instruction *Common = commonIRemTransforms(I)) 1054 return Common; 1055 1056 if (Value *RHSNeg = dyn_castNegVal(Op1)) 1057 if (!isa<Constant>(RHSNeg) || 1058 (isa<ConstantInt>(RHSNeg) && 1059 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) { 1060 // X % -Y -> X % Y 1061 Worklist.AddValue(I.getOperand(1)); 1062 I.setOperand(1, RHSNeg); 1063 return &I; 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 urem. 1068 if (I.getType()->isIntegerTy()) { 1069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); 1070 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { 1071 // X srem Y -> X urem Y, iff X and Y don't have sign bit set 1072 return BinaryOperator::CreateURem(Op0, Op1, I.getName()); 1073 } 1074 } 1075 1076 // If it's a constant vector, flip any negative values positive. 1077 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) { 1078 Constant *C = cast<Constant>(Op1); 1079 unsigned VWidth = C->getType()->getVectorNumElements(); 1080 1081 bool hasNegative = false; 1082 bool hasMissing = false; 1083 for (unsigned i = 0; i != VWidth; ++i) { 1084 Constant *Elt = C->getAggregateElement(i); 1085 if (Elt == 0) { 1086 hasMissing = true; 1087 break; 1088 } 1089 1090 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt)) 1091 if (RHS->isNegative()) 1092 hasNegative = true; 1093 } 1094 1095 if (hasNegative && !hasMissing) { 1096 SmallVector<Constant *, 16> Elts(VWidth); 1097 for (unsigned i = 0; i != VWidth; ++i) { 1098 Elts[i] = C->getAggregateElement(i); // Handle undef, etc. 1099 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) { 1100 if (RHS->isNegative()) 1101 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); 1102 } 1103 } 1104 1105 Constant *NewRHSV = ConstantVector::get(Elts); 1106 if (NewRHSV != C) { // Don't loop on -MININT 1107 Worklist.AddValue(I.getOperand(1)); 1108 I.setOperand(1, NewRHSV); 1109 return &I; 1110 } 1111 } 1112 } 1113 1114 return 0; 1115} 1116 1117Instruction *InstCombiner::visitFRem(BinaryOperator &I) { 1118 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1119 1120 if (Value *V = SimplifyFRemInst(Op0, Op1, TD)) 1121 return ReplaceInstUsesWith(I, V); 1122 1123 // Handle cases involving: rem X, (select Cond, Y, Z) 1124 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) 1125 return &I; 1126 1127 return 0; 1128} 1129