1 //===- InstCombineShifts.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 visitShl, visitLShr, and visitAShr functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/Analysis/ConstantFolding.h" 15 #include "llvm/Analysis/InstructionSimplify.h" 16 #include "llvm/IR/IntrinsicInst.h" 17 #include "llvm/IR/PatternMatch.h" 18 using namespace llvm; 19 using namespace PatternMatch; 20 21 #define DEBUG_TYPE "instcombine" 22 23 // Given pattern: 24 // (x shiftopcode Q) shiftopcode K 25 // we should rewrite it as 26 // x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x) 27 // This is valid for any shift, but they must be identical. 28 static Instruction * 29 reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, 30 const SimplifyQuery &SQ, 31 InstCombiner::BuilderTy &Builder) { 32 // Look for a shift of some instruction, ignore zext of shift amount if any. 33 Instruction *Sh0Op0; 34 Value *ShAmt0; 35 if (!match(Sh0, 36 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0))))) 37 return nullptr; 38 39 // If there is a truncation between the two shifts, we must make note of it 40 // and look through it. The truncation imposes additional constraints on the 41 // transform. 42 Instruction *Sh1; 43 Value *Trunc = nullptr; 44 match(Sh0Op0, 45 m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)), 46 m_Instruction(Sh1))); 47 48 // Inner shift: (x shiftopcode ShAmt1) 49 // Like with other shift, ignore zext of shift amount if any. 50 Value *X, *ShAmt1; 51 if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1))))) 52 return nullptr; 53 54 // We have two shift amounts from two different shifts. The types of those 55 // shift amounts may not match. If that's the case let's bailout now.. 56 if (ShAmt0->getType() != ShAmt1->getType()) 57 return nullptr; 58 59 // The shift opcodes must be identical. 60 Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode(); 61 if (ShiftOpcode != Sh1->getOpcode()) 62 return nullptr; 63 64 // If we saw truncation, we'll need to produce extra instruction, 65 // and for that one of the operands of the shift must be one-use. 66 if (Trunc && !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value()))) 67 return nullptr; 68 69 // Can we fold (ShAmt0+ShAmt1) ? 70 auto *NewShAmt = dyn_cast_or_null<Constant>( 71 SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false, 72 SQ.getWithInstruction(Sh0))); 73 if (!NewShAmt) 74 return nullptr; // Did not simplify. 75 unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits(); 76 unsigned XBitWidth = X->getType()->getScalarSizeInBits(); 77 // Is the new shift amount smaller than the bit width of inner/new shift? 78 if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT, 79 APInt(NewShAmtBitWidth, XBitWidth)))) 80 return nullptr; // FIXME: could perform constant-folding. 81 82 // If there was a truncation, and we have a right-shift, we can only fold if 83 // we are left with the original sign bit. 84 // FIXME: zero shift amount is also legal here, but we can't *easily* check 85 // more than one predicate so it's not really worth it. 86 if (Trunc && ShiftOpcode != Instruction::BinaryOps::Shl && 87 !match(NewShAmt, 88 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 89 APInt(NewShAmtBitWidth, XBitWidth - 1)))) 90 return nullptr; 91 92 // All good, we can do this fold. 93 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType()); 94 95 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt); 96 97 // The flags can only be propagated if there wasn't a trunc. 98 if (!Trunc) { 99 // If the pattern did not involve trunc, and both of the original shifts 100 // had the same flag set, preserve the flag. 101 if (ShiftOpcode == Instruction::BinaryOps::Shl) { 102 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() && 103 Sh1->hasNoUnsignedWrap()); 104 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() && 105 Sh1->hasNoSignedWrap()); 106 } else { 107 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact()); 108 } 109 } 110 111 Instruction *Ret = NewShift; 112 if (Trunc) { 113 Builder.Insert(NewShift); 114 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType()); 115 } 116 117 return Ret; 118 } 119 120 // Try to replace `undef` constants in C with Replacement. 121 static Constant *replaceUndefsWith(Constant *C, Constant *Replacement) { 122 if (C && match(C, m_Undef())) 123 return Replacement; 124 125 if (auto *CV = dyn_cast<ConstantVector>(C)) { 126 llvm::SmallVector<Constant *, 32> NewOps(CV->getNumOperands()); 127 for (unsigned i = 0, NumElts = NewOps.size(); i != NumElts; ++i) { 128 Constant *EltC = CV->getOperand(i); 129 NewOps[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC; 130 } 131 return ConstantVector::get(NewOps); 132 } 133 134 // Don't know how to deal with this constant. 135 return C; 136 } 137 138 // If we have some pattern that leaves only some low bits set, and then performs 139 // left-shift of those bits, if none of the bits that are left after the final 140 // shift are modified by the mask, we can omit the mask. 141 // 142 // There are many variants to this pattern: 143 // a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt 144 // b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt 145 // c) (x & (-1 >> MaskShAmt)) << ShiftShAmt 146 // d) (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt 147 // e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt 148 // f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt 149 // All these patterns can be simplified to just: 150 // x << ShiftShAmt 151 // iff: 152 // a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x) 153 // c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt) 154 static Instruction * 155 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, 156 const SimplifyQuery &Q, 157 InstCombiner::BuilderTy &Builder) { 158 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl && 159 "The input must be 'shl'!"); 160 161 Value *Masked, *ShiftShAmt; 162 match(OuterShift, m_Shift(m_Value(Masked), m_Value(ShiftShAmt))); 163 164 Type *NarrowestTy = OuterShift->getType(); 165 Type *WidestTy = Masked->getType(); 166 // The mask must be computed in a type twice as wide to ensure 167 // that no bits are lost if the sum-of-shifts is wider than the base type. 168 Type *ExtendedTy = WidestTy->getExtendedType(); 169 170 Value *MaskShAmt; 171 172 // ((1 << MaskShAmt) - 1) 173 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes()); 174 // (~(-1 << maskNbits)) 175 auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes()); 176 // (-1 >> MaskShAmt) 177 auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt)); 178 // ((-1 << MaskShAmt) >> MaskShAmt) 179 auto MaskD = 180 m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt)); 181 182 Value *X; 183 Constant *NewMask; 184 185 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) { 186 // Can we simplify (MaskShAmt+ShiftShAmt) ? 187 auto *SumOfShAmts = dyn_cast_or_null<Constant>(SimplifyAddInst( 188 MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q)); 189 if (!SumOfShAmts) 190 return nullptr; // Did not simplify. 191 // In this pattern SumOfShAmts correlates with the number of low bits 192 // that shall remain in the root value (OuterShift). 193 194 // An extend of an undef value becomes zero because the high bits are never 195 // completely unknown. Replace the the `undef` shift amounts with final 196 // shift bitwidth to ensure that the value remains undef when creating the 197 // subsequent shift op. 198 SumOfShAmts = replaceUndefsWith( 199 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(), 200 ExtendedTy->getScalarSizeInBits())); 201 auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy); 202 // And compute the mask as usual: ~(-1 << (SumOfShAmts)) 203 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy); 204 auto *ExtendedInvertedMask = 205 ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts); 206 NewMask = ConstantExpr::getNot(ExtendedInvertedMask); 207 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) || 208 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)), 209 m_Deferred(MaskShAmt)))) { 210 // Can we simplify (ShiftShAmt-MaskShAmt) ? 211 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(SimplifySubInst( 212 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q)); 213 if (!ShAmtsDiff) 214 return nullptr; // Did not simplify. 215 // In this pattern ShAmtsDiff correlates with the number of high bits that 216 // shall be unset in the root value (OuterShift). 217 218 // An extend of an undef value becomes zero because the high bits are never 219 // completely unknown. Replace the the `undef` shift amounts with negated 220 // bitwidth of innermost shift to ensure that the value remains undef when 221 // creating the subsequent shift op. 222 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits(); 223 ShAmtsDiff = replaceUndefsWith( 224 ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(), 225 -WidestTyBitWidth)); 226 auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt( 227 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(), 228 WidestTyBitWidth, 229 /*isSigned=*/false), 230 ShAmtsDiff), 231 ExtendedTy); 232 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear)) 233 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy); 234 NewMask = 235 ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear); 236 } else 237 return nullptr; // Don't know anything about this pattern. 238 239 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy); 240 241 // Does this mask has any unset bits? If not then we can just not apply it. 242 bool NeedMask = !match(NewMask, m_AllOnes()); 243 244 // If we need to apply a mask, there are several more restrictions we have. 245 if (NeedMask) { 246 // The old masking instruction must go away. 247 if (!Masked->hasOneUse()) 248 return nullptr; 249 // The original "masking" instruction must not have been`ashr`. 250 if (match(Masked, m_AShr(m_Value(), m_Value()))) 251 return nullptr; 252 } 253 254 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits. 255 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X, 256 OuterShift->getOperand(1)); 257 258 if (!NeedMask) 259 return NewShift; 260 261 Builder.Insert(NewShift); 262 return BinaryOperator::Create(Instruction::And, NewShift, NewMask); 263 } 264 265 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) { 266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 267 assert(Op0->getType() == Op1->getType()); 268 269 // If the shift amount is a one-use `sext`, we can demote it to `zext`. 270 Value *Y; 271 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) { 272 Value *NewExt = Builder.CreateZExt(Y, I.getType(), Op1->getName()); 273 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt); 274 } 275 276 // See if we can fold away this shift. 277 if (SimplifyDemandedInstructionBits(I)) 278 return &I; 279 280 // Try to fold constant and into select arguments. 281 if (isa<Constant>(Op0)) 282 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 283 if (Instruction *R = FoldOpIntoSelect(I, SI)) 284 return R; 285 286 if (Constant *CUI = dyn_cast<Constant>(Op1)) 287 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I)) 288 return Res; 289 290 if (Instruction *NewShift = 291 reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ, Builder)) 292 return NewShift; 293 294 // (C1 shift (A add C2)) -> (C1 shift C2) shift A) 295 // iff A and C2 are both positive. 296 Value *A; 297 Constant *C; 298 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C)))) 299 if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) && 300 isKnownNonNegative(C, DL, 0, &AC, &I, &DT)) 301 return BinaryOperator::Create( 302 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A); 303 304 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2. 305 // Because shifts by negative values (which could occur if A were negative) 306 // are undefined. 307 const APInt *B; 308 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) { 309 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't 310 // demand the sign bit (and many others) here?? 311 Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1), 312 Op1->getName()); 313 I.setOperand(1, Rem); 314 return &I; 315 } 316 317 return nullptr; 318 } 319 320 /// Return true if we can simplify two logical (either left or right) shifts 321 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2. 322 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl, 323 Instruction *InnerShift, InstCombiner &IC, 324 Instruction *CxtI) { 325 assert(InnerShift->isLogicalShift() && "Unexpected instruction type"); 326 327 // We need constant scalar or constant splat shifts. 328 const APInt *InnerShiftConst; 329 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst))) 330 return false; 331 332 // Two logical shifts in the same direction: 333 // shl (shl X, C1), C2 --> shl X, C1 + C2 334 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2 335 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl; 336 if (IsInnerShl == IsOuterShl) 337 return true; 338 339 // Equal shift amounts in opposite directions become bitwise 'and': 340 // lshr (shl X, C), C --> and X, C' 341 // shl (lshr X, C), C --> and X, C' 342 if (*InnerShiftConst == OuterShAmt) 343 return true; 344 345 // If the 2nd shift is bigger than the 1st, we can fold: 346 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3 347 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3 348 // but it isn't profitable unless we know the and'd out bits are already zero. 349 // Also, check that the inner shift is valid (less than the type width) or 350 // we'll crash trying to produce the bit mask for the 'and'. 351 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits(); 352 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) { 353 unsigned InnerShAmt = InnerShiftConst->getZExtValue(); 354 unsigned MaskShift = 355 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt; 356 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift; 357 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI)) 358 return true; 359 } 360 361 return false; 362 } 363 364 /// See if we can compute the specified value, but shifted logically to the left 365 /// or right by some number of bits. This should return true if the expression 366 /// can be computed for the same cost as the current expression tree. This is 367 /// used to eliminate extraneous shifting from things like: 368 /// %C = shl i128 %A, 64 369 /// %D = shl i128 %B, 96 370 /// %E = or i128 %C, %D 371 /// %F = lshr i128 %E, 64 372 /// where the client will ask if E can be computed shifted right by 64-bits. If 373 /// this succeeds, getShiftedValue() will be called to produce the value. 374 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift, 375 InstCombiner &IC, Instruction *CxtI) { 376 // We can always evaluate constants shifted. 377 if (isa<Constant>(V)) 378 return true; 379 380 Instruction *I = dyn_cast<Instruction>(V); 381 if (!I) return false; 382 383 // If this is the opposite shift, we can directly reuse the input of the shift 384 // if the needed bits are already zero in the input. This allows us to reuse 385 // the value which means that we don't care if the shift has multiple uses. 386 // TODO: Handle opposite shift by exact value. 387 ConstantInt *CI = nullptr; 388 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) || 389 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) { 390 if (CI->getValue() == NumBits) { 391 // TODO: Check that the input bits are already zero with MaskedValueIsZero 392 #if 0 393 // If this is a truncate of a logical shr, we can truncate it to a smaller 394 // lshr iff we know that the bits we would otherwise be shifting in are 395 // already zeros. 396 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 397 uint32_t BitWidth = Ty->getScalarSizeInBits(); 398 if (MaskedValueIsZero(I->getOperand(0), 399 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) && 400 CI->getLimitedValue(BitWidth) < BitWidth) { 401 return CanEvaluateTruncated(I->getOperand(0), Ty); 402 } 403 #endif 404 405 } 406 } 407 408 // We can't mutate something that has multiple uses: doing so would 409 // require duplicating the instruction in general, which isn't profitable. 410 if (!I->hasOneUse()) return false; 411 412 switch (I->getOpcode()) { 413 default: return false; 414 case Instruction::And: 415 case Instruction::Or: 416 case Instruction::Xor: 417 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted. 418 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) && 419 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I); 420 421 case Instruction::Shl: 422 case Instruction::LShr: 423 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI); 424 425 case Instruction::Select: { 426 SelectInst *SI = cast<SelectInst>(I); 427 Value *TrueVal = SI->getTrueValue(); 428 Value *FalseVal = SI->getFalseValue(); 429 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) && 430 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI); 431 } 432 case Instruction::PHI: { 433 // We can change a phi if we can change all operands. Note that we never 434 // get into trouble with cyclic PHIs here because we only consider 435 // instructions with a single use. 436 PHINode *PN = cast<PHINode>(I); 437 for (Value *IncValue : PN->incoming_values()) 438 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN)) 439 return false; 440 return true; 441 } 442 } 443 } 444 445 /// Fold OuterShift (InnerShift X, C1), C2. 446 /// See canEvaluateShiftedShift() for the constraints on these instructions. 447 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt, 448 bool IsOuterShl, 449 InstCombiner::BuilderTy &Builder) { 450 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl; 451 Type *ShType = InnerShift->getType(); 452 unsigned TypeWidth = ShType->getScalarSizeInBits(); 453 454 // We only accept shifts-by-a-constant in canEvaluateShifted(). 455 const APInt *C1; 456 match(InnerShift->getOperand(1), m_APInt(C1)); 457 unsigned InnerShAmt = C1->getZExtValue(); 458 459 // Change the shift amount and clear the appropriate IR flags. 460 auto NewInnerShift = [&](unsigned ShAmt) { 461 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt)); 462 if (IsInnerShl) { 463 InnerShift->setHasNoUnsignedWrap(false); 464 InnerShift->setHasNoSignedWrap(false); 465 } else { 466 InnerShift->setIsExact(false); 467 } 468 return InnerShift; 469 }; 470 471 // Two logical shifts in the same direction: 472 // shl (shl X, C1), C2 --> shl X, C1 + C2 473 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2 474 if (IsInnerShl == IsOuterShl) { 475 // If this is an oversized composite shift, then unsigned shifts get 0. 476 if (InnerShAmt + OuterShAmt >= TypeWidth) 477 return Constant::getNullValue(ShType); 478 479 return NewInnerShift(InnerShAmt + OuterShAmt); 480 } 481 482 // Equal shift amounts in opposite directions become bitwise 'and': 483 // lshr (shl X, C), C --> and X, C' 484 // shl (lshr X, C), C --> and X, C' 485 if (InnerShAmt == OuterShAmt) { 486 APInt Mask = IsInnerShl 487 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt) 488 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt); 489 Value *And = Builder.CreateAnd(InnerShift->getOperand(0), 490 ConstantInt::get(ShType, Mask)); 491 if (auto *AndI = dyn_cast<Instruction>(And)) { 492 AndI->moveBefore(InnerShift); 493 AndI->takeName(InnerShift); 494 } 495 return And; 496 } 497 498 assert(InnerShAmt > OuterShAmt && 499 "Unexpected opposite direction logical shift pair"); 500 501 // In general, we would need an 'and' for this transform, but 502 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used. 503 // lshr (shl X, C1), C2 --> shl X, C1 - C2 504 // shl (lshr X, C1), C2 --> lshr X, C1 - C2 505 return NewInnerShift(InnerShAmt - OuterShAmt); 506 } 507 508 /// When canEvaluateShifted() returns true for an expression, this function 509 /// inserts the new computation that produces the shifted value. 510 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift, 511 InstCombiner &IC, const DataLayout &DL) { 512 // We can always evaluate constants shifted. 513 if (Constant *C = dyn_cast<Constant>(V)) { 514 if (isLeftShift) 515 V = IC.Builder.CreateShl(C, NumBits); 516 else 517 V = IC.Builder.CreateLShr(C, NumBits); 518 // If we got a constantexpr back, try to simplify it with TD info. 519 if (auto *C = dyn_cast<Constant>(V)) 520 if (auto *FoldedC = 521 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo())) 522 V = FoldedC; 523 return V; 524 } 525 526 Instruction *I = cast<Instruction>(V); 527 IC.Worklist.Add(I); 528 529 switch (I->getOpcode()) { 530 default: llvm_unreachable("Inconsistency with CanEvaluateShifted"); 531 case Instruction::And: 532 case Instruction::Or: 533 case Instruction::Xor: 534 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted. 535 I->setOperand( 536 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL)); 537 I->setOperand( 538 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL)); 539 return I; 540 541 case Instruction::Shl: 542 case Instruction::LShr: 543 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift, 544 IC.Builder); 545 546 case Instruction::Select: 547 I->setOperand( 548 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL)); 549 I->setOperand( 550 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL)); 551 return I; 552 case Instruction::PHI: { 553 // We can change a phi if we can change all operands. Note that we never 554 // get into trouble with cyclic PHIs here because we only consider 555 // instructions with a single use. 556 PHINode *PN = cast<PHINode>(I); 557 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 558 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits, 559 isLeftShift, IC, DL)); 560 return PN; 561 } 562 } 563 } 564 565 // If this is a bitwise operator or add with a constant RHS we might be able 566 // to pull it through a shift. 567 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift, 568 BinaryOperator *BO) { 569 switch (BO->getOpcode()) { 570 default: 571 return false; // Do not perform transform! 572 case Instruction::Add: 573 return Shift.getOpcode() == Instruction::Shl; 574 case Instruction::Or: 575 case Instruction::Xor: 576 case Instruction::And: 577 return true; 578 } 579 } 580 581 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1, 582 BinaryOperator &I) { 583 bool isLeftShift = I.getOpcode() == Instruction::Shl; 584 585 const APInt *Op1C; 586 if (!match(Op1, m_APInt(Op1C))) 587 return nullptr; 588 589 // See if we can propagate this shift into the input, this covers the trivial 590 // cast of lshr(shl(x,c1),c2) as well as other more complex cases. 591 if (I.getOpcode() != Instruction::AShr && 592 canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) { 593 LLVM_DEBUG( 594 dbgs() << "ICE: GetShiftedValue propagating shift through expression" 595 " to eliminate shift:\n IN: " 596 << *Op0 << "\n SH: " << I << "\n"); 597 598 return replaceInstUsesWith( 599 I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL)); 600 } 601 602 // See if we can simplify any instructions used by the instruction whose sole 603 // purpose is to compute bits we don't care about. 604 unsigned TypeBits = Op0->getType()->getScalarSizeInBits(); 605 606 assert(!Op1C->uge(TypeBits) && 607 "Shift over the type width should have been removed already"); 608 609 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I)) 610 return FoldedShift; 611 612 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2)) 613 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) { 614 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0)); 615 // If 'shift2' is an ashr, we would have to get the sign bit into a funny 616 // place. Don't try to do this transformation in this case. Also, we 617 // require that the input operand is a shift-by-constant so that we have 618 // confidence that the shifts will get folded together. We could do this 619 // xform in more cases, but it is unlikely to be profitable. 620 if (TrOp && I.isLogicalShift() && TrOp->isShift() && 621 isa<ConstantInt>(TrOp->getOperand(1))) { 622 // Okay, we'll do this xform. Make the shift of shift. 623 Constant *ShAmt = 624 ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType()); 625 // (shift2 (shift1 & 0x00FF), c2) 626 Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName()); 627 628 // For logical shifts, the truncation has the effect of making the high 629 // part of the register be zeros. Emulate this by inserting an AND to 630 // clear the top bits as needed. This 'and' will usually be zapped by 631 // other xforms later if dead. 632 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits(); 633 unsigned DstSize = TI->getType()->getScalarSizeInBits(); 634 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize)); 635 636 // The mask we constructed says what the trunc would do if occurring 637 // between the shifts. We want to know the effect *after* the second 638 // shift. We know that it is a logical shift by a constant, so adjust the 639 // mask as appropriate. 640 if (I.getOpcode() == Instruction::Shl) 641 MaskV <<= Op1C->getZExtValue(); 642 else { 643 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift"); 644 MaskV.lshrInPlace(Op1C->getZExtValue()); 645 } 646 647 // shift1 & 0x00FF 648 Value *And = Builder.CreateAnd(NSh, 649 ConstantInt::get(I.getContext(), MaskV), 650 TI->getName()); 651 652 // Return the value truncated to the interesting size. 653 return new TruncInst(And, I.getType()); 654 } 655 } 656 657 if (Op0->hasOneUse()) { 658 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) { 659 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) 660 Value *V1, *V2; 661 ConstantInt *CC; 662 switch (Op0BO->getOpcode()) { 663 default: break; 664 case Instruction::Add: 665 case Instruction::And: 666 case Instruction::Or: 667 case Instruction::Xor: { 668 // These operators commute. 669 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C) 670 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() && 671 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), 672 m_Specific(Op1)))) { 673 Value *YS = // (Y << C) 674 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName()); 675 // (X + (Y << C)) 676 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1, 677 Op0BO->getOperand(1)->getName()); 678 unsigned Op1Val = Op1C->getLimitedValue(TypeBits); 679 680 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val); 681 Constant *Mask = ConstantInt::get(I.getContext(), Bits); 682 if (VectorType *VT = dyn_cast<VectorType>(X->getType())) 683 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask); 684 return BinaryOperator::CreateAnd(X, Mask); 685 } 686 687 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C)) 688 Value *Op0BOOp1 = Op0BO->getOperand(1); 689 if (isLeftShift && Op0BOOp1->hasOneUse() && 690 match(Op0BOOp1, 691 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))), 692 m_ConstantInt(CC)))) { 693 Value *YS = // (Y << C) 694 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName()); 695 // X & (CC << C) 696 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1), 697 V1->getName()+".mask"); 698 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM); 699 } 700 LLVM_FALLTHROUGH; 701 } 702 703 case Instruction::Sub: { 704 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) 705 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && 706 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), 707 m_Specific(Op1)))) { 708 Value *YS = // (Y << C) 709 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName()); 710 // (X + (Y << C)) 711 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS, 712 Op0BO->getOperand(0)->getName()); 713 unsigned Op1Val = Op1C->getLimitedValue(TypeBits); 714 715 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val); 716 Constant *Mask = ConstantInt::get(I.getContext(), Bits); 717 if (VectorType *VT = dyn_cast<VectorType>(X->getType())) 718 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask); 719 return BinaryOperator::CreateAnd(X, Mask); 720 } 721 722 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C) 723 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && 724 match(Op0BO->getOperand(0), 725 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))), 726 m_ConstantInt(CC))) && V2 == Op1) { 727 Value *YS = // (Y << C) 728 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName()); 729 // X & (CC << C) 730 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1), 731 V1->getName()+".mask"); 732 733 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS); 734 } 735 736 break; 737 } 738 } 739 740 741 // If the operand is a bitwise operator with a constant RHS, and the 742 // shift is the only use, we can pull it out of the shift. 743 const APInt *Op0C; 744 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) { 745 if (canShiftBinOpWithConstantRHS(I, Op0BO)) { 746 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 747 cast<Constant>(Op0BO->getOperand(1)), Op1); 748 749 Value *NewShift = 750 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1); 751 NewShift->takeName(Op0BO); 752 753 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, 754 NewRHS); 755 } 756 } 757 758 // If the operand is a subtract with a constant LHS, and the shift 759 // is the only use, we can pull it out of the shift. 760 // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2)) 761 if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub && 762 match(Op0BO->getOperand(0), m_APInt(Op0C))) { 763 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 764 cast<Constant>(Op0BO->getOperand(0)), Op1); 765 766 Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1); 767 NewShift->takeName(Op0BO); 768 769 return BinaryOperator::CreateSub(NewRHS, NewShift); 770 } 771 } 772 773 // If we have a select that conditionally executes some binary operator, 774 // see if we can pull it the select and operator through the shift. 775 // 776 // For example, turning: 777 // shl (select C, (add X, C1), X), C2 778 // Into: 779 // Y = shl X, C2 780 // select C, (add Y, C1 << C2), Y 781 Value *Cond; 782 BinaryOperator *TBO; 783 Value *FalseVal; 784 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)), 785 m_Value(FalseVal)))) { 786 const APInt *C; 787 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal && 788 match(TBO->getOperand(1), m_APInt(C)) && 789 canShiftBinOpWithConstantRHS(I, TBO)) { 790 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 791 cast<Constant>(TBO->getOperand(1)), Op1); 792 793 Value *NewShift = 794 Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1); 795 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, 796 NewRHS); 797 return SelectInst::Create(Cond, NewOp, NewShift); 798 } 799 } 800 801 BinaryOperator *FBO; 802 Value *TrueVal; 803 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal), 804 m_OneUse(m_BinOp(FBO))))) { 805 const APInt *C; 806 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal && 807 match(FBO->getOperand(1), m_APInt(C)) && 808 canShiftBinOpWithConstantRHS(I, FBO)) { 809 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 810 cast<Constant>(FBO->getOperand(1)), Op1); 811 812 Value *NewShift = 813 Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1); 814 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, 815 NewRHS); 816 return SelectInst::Create(Cond, NewShift, NewOp); 817 } 818 } 819 } 820 821 return nullptr; 822 } 823 824 Instruction *InstCombiner::visitShl(BinaryOperator &I) { 825 const SimplifyQuery Q = SQ.getWithInstruction(&I); 826 827 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1), 828 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q)) 829 return replaceInstUsesWith(I, V); 830 831 if (Instruction *X = foldVectorBinop(I)) 832 return X; 833 834 if (Instruction *V = commonShiftTransforms(I)) 835 return V; 836 837 if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder)) 838 return V; 839 840 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 841 Type *Ty = I.getType(); 842 unsigned BitWidth = Ty->getScalarSizeInBits(); 843 844 const APInt *ShAmtAPInt; 845 if (match(Op1, m_APInt(ShAmtAPInt))) { 846 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 847 848 // shl (zext X), ShAmt --> zext (shl X, ShAmt) 849 // This is only valid if X would have zeros shifted out. 850 Value *X; 851 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) { 852 unsigned SrcWidth = X->getType()->getScalarSizeInBits(); 853 if (ShAmt < SrcWidth && 854 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I)) 855 return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty); 856 } 857 858 // (X >> C) << C --> X & (-1 << C) 859 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) { 860 APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)); 861 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask)); 862 } 863 864 // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine) 865 // needs a few fixes for the rotate pattern recognition first. 866 const APInt *ShOp1; 867 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) { 868 unsigned ShrAmt = ShOp1->getZExtValue(); 869 if (ShrAmt < ShAmt) { 870 // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1) 871 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt); 872 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff); 873 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap()); 874 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap()); 875 return NewShl; 876 } 877 if (ShrAmt > ShAmt) { 878 // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2) 879 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt); 880 auto *NewShr = BinaryOperator::Create( 881 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff); 882 NewShr->setIsExact(true); 883 return NewShr; 884 } 885 } 886 887 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) { 888 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 889 // Oversized shifts are simplified to zero in InstSimplify. 890 if (AmtSum < BitWidth) 891 // (X << C1) << C2 --> X << (C1 + C2) 892 return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum)); 893 } 894 895 // If the shifted-out value is known-zero, then this is a NUW shift. 896 if (!I.hasNoUnsignedWrap() && 897 MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) { 898 I.setHasNoUnsignedWrap(); 899 return &I; 900 } 901 902 // If the shifted-out value is all signbits, then this is a NSW shift. 903 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) { 904 I.setHasNoSignedWrap(); 905 return &I; 906 } 907 } 908 909 // Transform (x >> y) << y to x & (-1 << y) 910 // Valid for any type of right-shift. 911 Value *X; 912 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) { 913 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty); 914 Value *Mask = Builder.CreateShl(AllOnes, Op1); 915 return BinaryOperator::CreateAnd(Mask, X); 916 } 917 918 Constant *C1; 919 if (match(Op1, m_Constant(C1))) { 920 Constant *C2; 921 Value *X; 922 // (C2 << X) << C1 --> (C2 << C1) << X 923 if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X))))) 924 return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X); 925 926 // (X * C2) << C1 --> X * (C2 << C1) 927 if (match(Op0, m_Mul(m_Value(X), m_Constant(C2)))) 928 return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1)); 929 930 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0) 931 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 932 auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1); 933 return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty)); 934 } 935 } 936 937 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1 938 if (match(Op0, m_One()) && 939 match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X)))) 940 return BinaryOperator::CreateLShr( 941 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X); 942 943 return nullptr; 944 } 945 946 Instruction *InstCombiner::visitLShr(BinaryOperator &I) { 947 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(), 948 SQ.getWithInstruction(&I))) 949 return replaceInstUsesWith(I, V); 950 951 if (Instruction *X = foldVectorBinop(I)) 952 return X; 953 954 if (Instruction *R = commonShiftTransforms(I)) 955 return R; 956 957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 958 Type *Ty = I.getType(); 959 const APInt *ShAmtAPInt; 960 if (match(Op1, m_APInt(ShAmtAPInt))) { 961 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 962 unsigned BitWidth = Ty->getScalarSizeInBits(); 963 auto *II = dyn_cast<IntrinsicInst>(Op0); 964 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt && 965 (II->getIntrinsicID() == Intrinsic::ctlz || 966 II->getIntrinsicID() == Intrinsic::cttz || 967 II->getIntrinsicID() == Intrinsic::ctpop)) { 968 // ctlz.i32(x)>>5 --> zext(x == 0) 969 // cttz.i32(x)>>5 --> zext(x == 0) 970 // ctpop.i32(x)>>5 --> zext(x == -1) 971 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop; 972 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0); 973 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS); 974 return new ZExtInst(Cmp, Ty); 975 } 976 977 Value *X; 978 const APInt *ShOp1; 979 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) { 980 if (ShOp1->ult(ShAmt)) { 981 unsigned ShlAmt = ShOp1->getZExtValue(); 982 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt); 983 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) { 984 // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1) 985 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff); 986 NewLShr->setIsExact(I.isExact()); 987 return NewLShr; 988 } 989 // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2) 990 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact()); 991 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 992 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask)); 993 } 994 if (ShOp1->ugt(ShAmt)) { 995 unsigned ShlAmt = ShOp1->getZExtValue(); 996 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt); 997 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) { 998 // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2) 999 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff); 1000 NewShl->setHasNoUnsignedWrap(true); 1001 return NewShl; 1002 } 1003 // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2) 1004 Value *NewShl = Builder.CreateShl(X, ShiftDiff); 1005 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 1006 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask)); 1007 } 1008 assert(*ShOp1 == ShAmt); 1009 // (X << C) >>u C --> X & (-1 >>u C) 1010 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 1011 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask)); 1012 } 1013 1014 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && 1015 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) { 1016 assert(ShAmt < X->getType()->getScalarSizeInBits() && 1017 "Big shift not simplified to zero?"); 1018 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN 1019 Value *NewLShr = Builder.CreateLShr(X, ShAmt); 1020 return new ZExtInst(NewLShr, Ty); 1021 } 1022 1023 if (match(Op0, m_SExt(m_Value(X))) && 1024 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) { 1025 // Are we moving the sign bit to the low bit and widening with high zeros? 1026 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits(); 1027 if (ShAmt == BitWidth - 1) { 1028 // lshr (sext i1 X to iN), N-1 --> zext X to iN 1029 if (SrcTyBitWidth == 1) 1030 return new ZExtInst(X, Ty); 1031 1032 // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN 1033 if (Op0->hasOneUse()) { 1034 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1); 1035 return new ZExtInst(NewLShr, Ty); 1036 } 1037 } 1038 1039 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN 1040 if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) { 1041 // The new shift amount can't be more than the narrow source type. 1042 unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1); 1043 Value *AShr = Builder.CreateAShr(X, NewShAmt); 1044 return new ZExtInst(AShr, Ty); 1045 } 1046 } 1047 1048 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) { 1049 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 1050 // Oversized shifts are simplified to zero in InstSimplify. 1051 if (AmtSum < BitWidth) 1052 // (X >>u C1) >>u C2 --> X >>u (C1 + C2) 1053 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum)); 1054 } 1055 1056 // If the shifted-out value is known-zero, then this is an exact shift. 1057 if (!I.isExact() && 1058 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) { 1059 I.setIsExact(); 1060 return &I; 1061 } 1062 } 1063 1064 // Transform (x << y) >> y to x & (-1 >> y) 1065 Value *X; 1066 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) { 1067 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty); 1068 Value *Mask = Builder.CreateLShr(AllOnes, Op1); 1069 return BinaryOperator::CreateAnd(Mask, X); 1070 } 1071 1072 return nullptr; 1073 } 1074 1075 Instruction * 1076 InstCombiner::foldVariableSignZeroExtensionOfVariableHighBitExtract( 1077 BinaryOperator &OldAShr) { 1078 assert(OldAShr.getOpcode() == Instruction::AShr && 1079 "Must be called with arithmetic right-shift instruction only."); 1080 1081 // Check that constant C is a splat of the element-wise bitwidth of V. 1082 auto BitWidthSplat = [](Constant *C, Value *V) { 1083 return match( 1084 C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 1085 APInt(C->getType()->getScalarSizeInBits(), 1086 V->getType()->getScalarSizeInBits()))); 1087 }; 1088 1089 // It should look like variable-length sign-extension on the outside: 1090 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits) 1091 Value *NBits; 1092 Instruction *MaybeTrunc; 1093 Constant *C1, *C2; 1094 if (!match(&OldAShr, 1095 m_AShr(m_Shl(m_Instruction(MaybeTrunc), 1096 m_ZExtOrSelf(m_Sub(m_Constant(C1), 1097 m_ZExtOrSelf(m_Value(NBits))))), 1098 m_ZExtOrSelf(m_Sub(m_Constant(C2), 1099 m_ZExtOrSelf(m_Deferred(NBits)))))) || 1100 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr)) 1101 return nullptr; 1102 1103 // There may or may not be a truncation after outer two shifts. 1104 Instruction *HighBitExtract; 1105 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract))); 1106 bool HadTrunc = MaybeTrunc != HighBitExtract; 1107 1108 // And finally, the innermost part of the pattern must be a right-shift. 1109 Value *X, *NumLowBitsToSkip; 1110 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip)))) 1111 return nullptr; 1112 1113 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth. 1114 Constant *C0; 1115 if (!match(NumLowBitsToSkip, 1116 m_ZExtOrSelf( 1117 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) || 1118 !BitWidthSplat(C0, HighBitExtract)) 1119 return nullptr; 1120 1121 // Since the NBits is identical for all shifts, if the outermost and 1122 // innermost shifts are identical, then outermost shifts are redundant. 1123 // If we had truncation, do keep it though. 1124 if (HighBitExtract->getOpcode() == OldAShr.getOpcode()) 1125 return replaceInstUsesWith(OldAShr, MaybeTrunc); 1126 1127 // Else, if there was a truncation, then we need to ensure that one 1128 // instruction will go away. 1129 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value()))) 1130 return nullptr; 1131 1132 // Finally, bypass two innermost shifts, and perform the outermost shift on 1133 // the operands of the innermost shift. 1134 Instruction *NewAShr = 1135 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip); 1136 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness. 1137 if (!HadTrunc) 1138 return NewAShr; 1139 1140 Builder.Insert(NewAShr); 1141 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType()); 1142 } 1143 1144 Instruction *InstCombiner::visitAShr(BinaryOperator &I) { 1145 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(), 1146 SQ.getWithInstruction(&I))) 1147 return replaceInstUsesWith(I, V); 1148 1149 if (Instruction *X = foldVectorBinop(I)) 1150 return X; 1151 1152 if (Instruction *R = commonShiftTransforms(I)) 1153 return R; 1154 1155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1156 Type *Ty = I.getType(); 1157 unsigned BitWidth = Ty->getScalarSizeInBits(); 1158 const APInt *ShAmtAPInt; 1159 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) { 1160 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 1161 1162 // If the shift amount equals the difference in width of the destination 1163 // and source scalar types: 1164 // ashr (shl (zext X), C), C --> sext X 1165 Value *X; 1166 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) && 1167 ShAmt == BitWidth - X->getType()->getScalarSizeInBits()) 1168 return new SExtInst(X, Ty); 1169 1170 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However, 1171 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits. 1172 const APInt *ShOp1; 1173 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) && 1174 ShOp1->ult(BitWidth)) { 1175 unsigned ShlAmt = ShOp1->getZExtValue(); 1176 if (ShlAmt < ShAmt) { 1177 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1) 1178 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt); 1179 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff); 1180 NewAShr->setIsExact(I.isExact()); 1181 return NewAShr; 1182 } 1183 if (ShlAmt > ShAmt) { 1184 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2) 1185 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt); 1186 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff); 1187 NewShl->setHasNoSignedWrap(true); 1188 return NewShl; 1189 } 1190 } 1191 1192 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) && 1193 ShOp1->ult(BitWidth)) { 1194 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 1195 // Oversized arithmetic shifts replicate the sign bit. 1196 AmtSum = std::min(AmtSum, BitWidth - 1); 1197 // (X >>s C1) >>s C2 --> X >>s (C1 + C2) 1198 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum)); 1199 } 1200 1201 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) && 1202 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) { 1203 // ashr (sext X), C --> sext (ashr X, C') 1204 Type *SrcTy = X->getType(); 1205 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1); 1206 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt)); 1207 return new SExtInst(NewSh, Ty); 1208 } 1209 1210 // If the shifted-out value is known-zero, then this is an exact shift. 1211 if (!I.isExact() && 1212 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) { 1213 I.setIsExact(); 1214 return &I; 1215 } 1216 } 1217 1218 if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I)) 1219 return R; 1220 1221 // See if we can turn a signed shr into an unsigned shr. 1222 if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I)) 1223 return BinaryOperator::CreateLShr(Op0, Op1); 1224 1225 return nullptr; 1226 } 1227