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