InstCombineShifts.cpp 54 KB

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