blob: 6cf64c261724c00744dcdf55121675fa7b02de80 [file] [log] [blame]
Chris Lattnerdc67e132010-01-05 07:44:46 +00001//===- InstCombineShifts.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitShl, visitLShr, and visitAShr functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands7f60dc12011-01-14 00:37:45 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc67e132010-01-05 07:44:46 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattnerdc67e132010-01-05 07:44:46 +000024Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
Chris Lattnerdc67e132010-01-05 07:44:46 +000025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patelcf082032017-01-13 18:08:25 +000026 assert(Op0->getType() == Op1->getType());
Chris Lattnerdc67e132010-01-05 07:44:46 +000027
Chris Lattnerdc67e132010-01-05 07:44:46 +000028 // See if we can fold away this shift.
29 if (SimplifyDemandedInstructionBits(I))
30 return &I;
31
32 // Try to fold constant and into select arguments.
33 if (isa<Constant>(Op0))
34 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
35 if (Instruction *R = FoldOpIntoSelect(I, SI))
36 return R;
37
Matt Arsenaultfed3dc82014-04-14 21:50:37 +000038 if (Constant *CUI = dyn_cast<Constant>(Op1))
Chris Lattnerdc67e132010-01-05 07:44:46 +000039 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
40 return Res;
Benjamin Kramerb5afa652010-11-23 18:52:42 +000041
Simon Pilgrim6dd8fab2016-11-01 15:40:30 +000042 // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
43 // iff A and C2 are both positive.
44 Value *A;
45 Constant *C;
46 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
47 if (isKnownNonNegative(A, DL) && isKnownNonNegative(C, DL))
48 return BinaryOperator::Create(
49 I.getOpcode(), Builder->CreateBinOp(I.getOpcode(), Op0, C), A);
50
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000051 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
Chris Lattner6b657ae2011-02-10 05:36:31 +000052 // Because shifts by negative values (which could occur if A were negative)
53 // are undefined.
Simon Pilgrim6dd8fab2016-11-01 15:40:30 +000054 const APInt *B;
Chris Lattner6b657ae2011-02-10 05:36:31 +000055 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
56 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
57 // demand the sign bit (and many others) here??
58 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
59 Op1->getName());
60 I.setOperand(1, Rem);
61 return &I;
62 }
Jakub Staszak538e3862012-12-09 15:37:46 +000063
Craig Topperf40110f2014-04-25 05:29:35 +000064 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +000065}
66
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000067/// Return true if we can simplify two logical (either left or right) shifts
Sanjay Patel65cce202017-01-16 20:05:26 +000068/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
69static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
70 Instruction *InnerShift, InstCombiner &IC,
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000071 Instruction *CxtI) {
Sanjay Patel65cce202017-01-16 20:05:26 +000072 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
Sanjay Patelb91bcd72016-04-11 17:35:57 +000073
Sanjay Patelab8b32d2017-01-16 19:35:45 +000074 // We need constant scalar or constant splat shifts.
Sanjay Patel65cce202017-01-16 20:05:26 +000075 const APInt *InnerShiftConst;
76 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000077 return false;
78
Sanjay Patel65cce202017-01-16 20:05:26 +000079 // Two logical shifts in the same direction:
80 // shl (shl X, C1), C2 --> shl X, C1 + C2
81 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
82 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
83 if (IsInnerShl == IsOuterShl)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000084 return true;
85
Sanjay Patel65cce202017-01-16 20:05:26 +000086 // Equal shift amounts in opposite directions become bitwise 'and':
87 // lshr (shl X, C), C --> and X, C'
88 // shl (lshr X, C), C --> and X, C'
89 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
90 if (InnerShAmt == OuterShAmt)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000091 return true;
92
Sanjay Patelbd8b7792016-04-11 16:11:07 +000093 // If the 2nd shift is bigger than the 1st, we can fold:
Sanjay Patel65cce202017-01-16 20:05:26 +000094 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
95 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
Sanjay Patelbd8b7792016-04-11 16:11:07 +000096 // but it isn't profitable unless we know the and'd out bits are already zero.
Sanjay Patel65cce202017-01-16 20:05:26 +000097 // Also, check that the inner shift is valid (less than the type width) or
98 // we'll crash trying to produce the bit mask for the 'and'.
99 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
100 if (InnerShAmt > OuterShAmt && InnerShAmt < TypeWidth) {
101 unsigned MaskShift =
102 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
103 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
104 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
Sanjay Patel6eaff5c2016-04-11 15:43:41 +0000105 return true;
106 }
107
108 return false;
109}
110
Sanjay Patel20aaf582017-01-15 17:55:35 +0000111/// See if we can compute the specified value, but shifted logically to the left
112/// or right by some number of bits. This should return true if the expression
113/// can be computed for the same cost as the current expression tree. This is
114/// used to eliminate extraneous shifting from things like:
Chris Lattner18d7fc82010-08-27 22:24:38 +0000115/// %C = shl i128 %A, 64
116/// %D = shl i128 %B, 96
117/// %E = or i128 %C, %D
118/// %F = lshr i128 %E, 64
Sanjay Patel20aaf582017-01-15 17:55:35 +0000119/// where the client will ask if E can be computed shifted right by 64-bits. If
120/// this succeeds, getShiftedValue() will be called to produce the value.
121static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
Hal Finkel60db0582014-09-07 18:57:58 +0000122 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000123 // We can always evaluate constants shifted.
124 if (isa<Constant>(V))
125 return true;
Jakub Staszak538e3862012-12-09 15:37:46 +0000126
Chris Lattner18d7fc82010-08-27 22:24:38 +0000127 Instruction *I = dyn_cast<Instruction>(V);
128 if (!I) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000129
Chris Lattner18d7fc82010-08-27 22:24:38 +0000130 // If this is the opposite shift, we can directly reuse the input of the shift
131 // if the needed bits are already zero in the input. This allows us to reuse
132 // the value which means that we don't care if the shift has multiple uses.
133 // TODO: Handle opposite shift by exact value.
Craig Topperf40110f2014-04-25 05:29:35 +0000134 ConstantInt *CI = nullptr;
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000135 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
136 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000137 if (CI->getZExtValue() == NumBits) {
138 // TODO: Check that the input bits are already zero with MaskedValueIsZero
139#if 0
140 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000141 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner18d7fc82010-08-27 22:24:38 +0000142 // already zeros.
143 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
144 uint32_t BitWidth = Ty->getScalarSizeInBits();
145 if (MaskedValueIsZero(I->getOperand(0),
146 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
147 CI->getLimitedValue(BitWidth) < BitWidth) {
148 return CanEvaluateTruncated(I->getOperand(0), Ty);
149 }
150#endif
Jakub Staszak538e3862012-12-09 15:37:46 +0000151
Chris Lattner18d7fc82010-08-27 22:24:38 +0000152 }
153 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000154
Chris Lattner18d7fc82010-08-27 22:24:38 +0000155 // We can't mutate something that has multiple uses: doing so would
156 // require duplicating the instruction in general, which isn't profitable.
157 if (!I->hasOneUse()) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000158
Chris Lattner18d7fc82010-08-27 22:24:38 +0000159 switch (I->getOpcode()) {
160 default: return false;
161 case Instruction::And:
162 case Instruction::Or:
163 case Instruction::Xor:
164 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Sanjay Patel20aaf582017-01-15 17:55:35 +0000165 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
166 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
Jakub Staszak538e3862012-12-09 15:37:46 +0000167
Sanjay Patel6eaff5c2016-04-11 15:43:41 +0000168 case Instruction::Shl:
Sanjay Patel37129072016-04-11 17:11:55 +0000169 case Instruction::LShr:
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000170 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000171
Chris Lattner18d7fc82010-08-27 22:24:38 +0000172 case Instruction::Select: {
173 SelectInst *SI = cast<SelectInst>(I);
Sanjay Patel690955f2016-01-31 16:34:11 +0000174 Value *TrueVal = SI->getTrueValue();
175 Value *FalseVal = SI->getFalseValue();
Sanjay Patel20aaf582017-01-15 17:55:35 +0000176 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
177 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000178 }
179 case Instruction::PHI: {
180 // We can change a phi if we can change all operands. Note that we never
181 // get into trouble with cyclic PHIs here because we only consider
182 // instructions with a single use.
183 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +0000184 for (Value *IncValue : PN->incoming_values())
Sanjay Patel20aaf582017-01-15 17:55:35 +0000185 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
Chris Lattner18d7fc82010-08-27 22:24:38 +0000186 return false;
187 return true;
188 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000189 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000190}
191
Sanjay Patel646734a2017-01-16 17:27:50 +0000192/// Fold OuterShift (InnerShift X, C1), C2.
193/// See canEvaluateShiftedShift() for the constraints on these instructions.
194static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
195 bool IsOuterShl,
196 InstCombiner::BuilderTy &Builder) {
197 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
198 Type *ShType = InnerShift->getType();
199 unsigned TypeWidth = ShType->getScalarSizeInBits();
200
201 // We only accept shifts-by-a-constant in canEvaluateShifted().
Sanjay Patelab8b32d2017-01-16 19:35:45 +0000202 const APInt *C1;
203 match(InnerShift->getOperand(1), m_APInt(C1));
Sanjay Patel646734a2017-01-16 17:27:50 +0000204 unsigned InnerShAmt = C1->getZExtValue();
205
206 // Change the shift amount and clear the appropriate IR flags.
207 auto NewInnerShift = [&](unsigned ShAmt) {
208 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
209 if (IsInnerShl) {
210 InnerShift->setHasNoUnsignedWrap(false);
211 InnerShift->setHasNoSignedWrap(false);
212 } else {
213 InnerShift->setIsExact(false);
214 }
215 return InnerShift;
216 };
217
218 // Two logical shifts in the same direction:
219 // shl (shl X, C1), C2 --> shl X, C1 + C2
220 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
221 if (IsInnerShl == IsOuterShl) {
222 // If this is an oversized composite shift, then unsigned shifts get 0.
223 if (InnerShAmt + OuterShAmt >= TypeWidth)
224 return Constant::getNullValue(ShType);
225
226 return NewInnerShift(InnerShAmt + OuterShAmt);
227 }
228
229 // Equal shift amounts in opposite directions become bitwise 'and':
230 // lshr (shl X, C), C --> and X, C'
231 // shl (lshr X, C), C --> and X, C'
232 if (InnerShAmt == OuterShAmt) {
233 APInt Mask = IsInnerShl
234 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
235 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
236 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
237 ConstantInt::get(ShType, Mask));
238 if (auto *AndI = dyn_cast<Instruction>(And)) {
239 AndI->moveBefore(InnerShift);
240 AndI->takeName(InnerShift);
241 }
242 return And;
243 }
244
245 assert(InnerShAmt > OuterShAmt &&
246 "Unexpected opposite direction logical shift pair");
247
248 // In general, we would need an 'and' for this transform, but
249 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
250 // lshr (shl X, C1), C2 --> shl X, C1 - C2
251 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
252 return NewInnerShift(InnerShAmt - OuterShAmt);
253}
254
Sanjay Patel20aaf582017-01-15 17:55:35 +0000255/// When canEvaluateShifted() returns true for an expression, this function
256/// inserts the new computation that produces the shifted value.
257static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000258 InstCombiner &IC, const DataLayout &DL) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000259 // We can always evaluate constants shifted.
260 if (Constant *C = dyn_cast<Constant>(V)) {
261 if (isLeftShift)
262 V = IC.Builder->CreateShl(C, NumBits);
263 else
264 V = IC.Builder->CreateLShr(C, NumBits);
265 // If we got a constantexpr back, try to simplify it with TD info.
David Majnemerd536f232016-07-29 03:27:26 +0000266 if (auto *C = dyn_cast<Constant>(V))
267 if (auto *FoldedC =
Justin Bogner99798402016-08-05 01:06:44 +0000268 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
David Majnemerd536f232016-07-29 03:27:26 +0000269 V = FoldedC;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000270 return V;
271 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000272
Chris Lattner18d7fc82010-08-27 22:24:38 +0000273 Instruction *I = cast<Instruction>(V);
274 IC.Worklist.Add(I);
275
276 switch (I->getOpcode()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000277 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
Chris Lattner18d7fc82010-08-27 22:24:38 +0000278 case Instruction::And:
279 case Instruction::Or:
280 case Instruction::Xor:
281 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000282 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000283 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000284 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000285 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000286 return I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000287
Sanjay Patel646734a2017-01-16 17:27:50 +0000288 case Instruction::Shl:
289 case Instruction::LShr:
290 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
291 *(IC.Builder));
Jakub Staszak538e3862012-12-09 15:37:46 +0000292
Chris Lattner18d7fc82010-08-27 22:24:38 +0000293 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000295 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000297 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000298 return I;
299 case Instruction::PHI: {
300 // We can change a phi if we can change all operands. Note that we never
301 // get into trouble with cyclic PHIs here because we only consider
302 // instructions with a single use.
303 PHINode *PN = cast<PHINode>(I);
304 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Sanjay Patel20aaf582017-01-15 17:55:35 +0000305 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000307 return PN;
308 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000309 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000310}
311
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000312/// Try to fold (X << C1) << C2, where the shifts are some combination of
313/// shl/ashr/lshr.
314static Instruction *
Sanjay Patelda5682a2017-01-16 21:24:41 +0000315foldShiftByConstOfShiftByConst(BinaryOperator &I, const APInt *COp1,
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000316 InstCombiner::BuilderTy *Builder) {
317 Value *Op0 = I.getOperand(0);
Sanjay Patel478a83c2017-01-21 17:59:59 +0000318 unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000319
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000320 // Find out if this is a shift of a shift by a constant.
321 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
Sanjay Patel478a83c2017-01-21 17:59:59 +0000322 if (!ShiftOp || !ShiftOp->isShift())
Sanjay Patel5424bd22017-01-17 16:59:09 +0000323 return nullptr;
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000324
Sanjay Patel478a83c2017-01-21 17:59:59 +0000325 const APInt *ShAmt1;
326 if (!match(ShiftOp->getOperand(1), m_APInt(ShAmt1)))
327 return nullptr;
328
329 // Check for (X << c1) << c2 and (X >> c1) >> c2
330 if (I.getOpcode() == ShiftOp->getOpcode()) {
331 unsigned AmtSum = (*ShAmt1 + *COp1).getZExtValue();
332 // If this is an oversized composite shift, then unsigned shifts become
333 // zero (handled in InstSimplify) and ashr saturates.
334 if (AmtSum >= TypeBits) {
335 if (I.getOpcode() != Instruction::AShr)
336 return nullptr;
337 AmtSum = TypeBits - 1; // Saturate to 31 for i32 ashr.
338 }
339
340 return BinaryOperator::Create(I.getOpcode(), ShiftOp->getOperand(0),
341 ConstantInt::get(I.getType(), AmtSum));
342 }
343
Sanjay Patel5424bd22017-01-17 16:59:09 +0000344 // This is a constant shift of a constant shift. Be careful about hiding
345 // shl instructions behind bit masks. They are used to represent multiplies
346 // by a constant, and it is important that simple arithmetic expressions
347 // are still recognizable by scalar evolution.
348 //
349 // The transforms applied to shl are very similar to the transforms applied
350 // to mul by constant. We can be more aggressive about optimizing right
351 // shifts.
352 //
353 // Combinations of right and left shifts will still be optimized in
354 // DAGCombine where scalar evolution no longer applies.
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000355
Sanjay Patelb0d96d32017-01-26 20:52:27 +0000356 Value *X = ShiftOp->getOperand(0);
357 unsigned ShiftAmt1 = ShAmt1->getLimitedValue();
358 unsigned ShiftAmt2 = COp1->getLimitedValue();
359 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
360 if (ShiftAmt1 == 0)
361 return nullptr; // Will be simplified in the future.
362
Sanjay Patel50753f02017-01-26 22:08:10 +0000363 if (ShiftAmt1 == ShiftAmt2)
364 return nullptr;
Sanjay Patelb0d96d32017-01-26 20:52:27 +0000365
Sanjay Patel478a83c2017-01-21 17:59:59 +0000366 // FIXME: Everything under here should be extended to work with vector types.
367
368 auto *ShiftAmt1C = dyn_cast<ConstantInt>(ShiftOp->getOperand(1));
369 if (!ShiftAmt1C)
370 return nullptr;
371
Sanjay Patel5424bd22017-01-17 16:59:09 +0000372 IntegerType *Ty = cast<IntegerType>(I.getType());
Sanjay Patelb0d96d32017-01-26 20:52:27 +0000373 if (ShiftAmt1 < ShiftAmt2) {
Sanjay Patel5424bd22017-01-17 16:59:09 +0000374 uint32_t ShiftDiff = ShiftAmt2 - ShiftAmt1;
375
Sanjay Patel5424bd22017-01-17 16:59:09 +0000376 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
377 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
378 if (I.getOpcode() == Instruction::AShr &&
379 ShiftOp->getOpcode() == Instruction::Shl) {
380 if (ShiftOp->hasNoSignedWrap()) {
381 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
382 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
383 BinaryOperator *NewAShr =
384 BinaryOperator::Create(Instruction::AShr, X, ShiftDiffCst);
385 NewAShr->setIsExact(I.isExact());
386 return NewAShr;
387 }
388 }
389 } else {
390 assert(ShiftAmt2 < ShiftAmt1);
391 uint32_t ShiftDiff = ShiftAmt1 - ShiftAmt2;
392
393 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
394 // The inexact version is deferred to DAGCombine so we don't hide shl
395 // behind a bit mask.
396 if (I.getOpcode() == Instruction::Shl &&
397 ShiftOp->getOpcode() != Instruction::Shl && ShiftOp->isExact()) {
398 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
399 BinaryOperator *NewShr =
400 BinaryOperator::Create(ShiftOp->getOpcode(), X, ShiftDiffCst);
401 NewShr->setIsExact(true);
402 return NewShr;
403 }
404
405 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
406 if (I.getOpcode() == Instruction::LShr &&
407 ShiftOp->getOpcode() == Instruction::Shl) {
408 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
409 if (ShiftOp->hasNoUnsignedWrap()) {
410 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
411 BinaryOperator *NewShl =
412 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
413 NewShl->setHasNoUnsignedWrap(true);
414 return NewShl;
415 }
416 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
417
418 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
419 return BinaryOperator::CreateAnd(Shift,
420 ConstantInt::get(I.getContext(), Mask));
421 }
422
423 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
424 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
425 if (I.getOpcode() == Instruction::AShr &&
426 ShiftOp->getOpcode() == Instruction::Shl) {
427 if (ShiftOp->hasNoSignedWrap()) {
428 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000429 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
430 BinaryOperator *NewShl =
431 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
Sanjay Patel5424bd22017-01-17 16:59:09 +0000432 NewShl->setHasNoSignedWrap(true);
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000433 return NewShl;
434 }
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000435 }
436 }
437
438 return nullptr;
439}
Chris Lattner18d7fc82010-08-27 22:24:38 +0000440
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000441Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattnerdc67e132010-01-05 07:44:46 +0000442 BinaryOperator &I) {
443 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Jakub Staszak538e3862012-12-09 15:37:46 +0000444
Sanjay Patelda5682a2017-01-16 21:24:41 +0000445 const APInt *Op1C;
446 if (!match(Op1, m_APInt(Op1C)))
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000447 return nullptr;
Jakub Staszak538e3862012-12-09 15:37:46 +0000448
Chris Lattner18d7fc82010-08-27 22:24:38 +0000449 // See if we can propagate this shift into the input, this covers the trivial
450 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
451 if (I.getOpcode() != Instruction::AShr &&
Sanjay Patelda5682a2017-01-16 21:24:41 +0000452 canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
Chris Lattnerdd660102010-08-28 01:20:38 +0000453 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
454 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Jakub Staszak538e3862012-12-09 15:37:46 +0000455
Sanjay Patel4b198802016-02-01 22:23:39 +0000456 return replaceInstUsesWith(
Sanjay Patelda5682a2017-01-16 21:24:41 +0000457 I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000458 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000459
Jakub Staszak538e3862012-12-09 15:37:46 +0000460 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattnerdc67e132010-01-05 07:44:46 +0000461 // purpose is to compute bits we don't care about.
Sanjay Patelda5682a2017-01-16 21:24:41 +0000462 unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
Jakub Staszak538e3862012-12-09 15:37:46 +0000463
Sanjay Patelda5682a2017-01-16 21:24:41 +0000464 assert(!Op1C->uge(TypeBits) &&
Matt Arsenault6b4bed42014-04-23 16:48:40 +0000465 "Shift over the type width should have been removed already");
Jakub Staszak538e3862012-12-09 15:37:46 +0000466
Chris Lattnerdc67e132010-01-05 07:44:46 +0000467 // ((X*C1) << C2) == (X * (C1 << C2))
468 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
469 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
470 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
471 return BinaryOperator::CreateMul(BO->getOperand(0),
Sanjay Patel690955f2016-01-31 16:34:11 +0000472 ConstantExpr::getShl(BOOp, Op1));
Jakub Staszak538e3862012-12-09 15:37:46 +0000473
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000474 if (Instruction *FoldedShift = foldOpWithConstantIntoOperand(I))
475 return FoldedShift;
Jakub Staszak538e3862012-12-09 15:37:46 +0000476
Chris Lattnerdc67e132010-01-05 07:44:46 +0000477 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
478 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
479 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
480 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
481 // place. Don't try to do this transformation in this case. Also, we
482 // require that the input operand is a shift-by-constant so that we have
483 // confidence that the shifts will get folded together. We could do this
484 // xform in more cases, but it is unlikely to be profitable.
Jakub Staszak538e3862012-12-09 15:37:46 +0000485 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
Chris Lattnerdc67e132010-01-05 07:44:46 +0000486 isa<ConstantInt>(TrOp->getOperand(1))) {
487 // Okay, we'll do this xform. Make the shift of shift.
Sanjay Patelda5682a2017-01-16 21:24:41 +0000488 Constant *ShAmt =
489 ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000490 // (shift2 (shift1 & 0x00FF), c2)
491 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
492
493 // For logical shifts, the truncation has the effect of making the high
494 // part of the register be zeros. Emulate this by inserting an AND to
495 // clear the top bits as needed. This 'and' will usually be zapped by
496 // other xforms later if dead.
497 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
498 unsigned DstSize = TI->getType()->getScalarSizeInBits();
499 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
Jakub Staszak538e3862012-12-09 15:37:46 +0000500
Chris Lattnerdc67e132010-01-05 07:44:46 +0000501 // The mask we constructed says what the trunc would do if occurring
502 // between the shifts. We want to know the effect *after* the second
503 // shift. We know that it is a logical shift by a constant, so adjust the
504 // mask as appropriate.
505 if (I.getOpcode() == Instruction::Shl)
Sanjay Patelda5682a2017-01-16 21:24:41 +0000506 MaskV <<= Op1C->getZExtValue();
Chris Lattnerdc67e132010-01-05 07:44:46 +0000507 else {
508 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
Sanjay Patelda5682a2017-01-16 21:24:41 +0000509 MaskV = MaskV.lshr(Op1C->getZExtValue());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000510 }
511
512 // shift1 & 0x00FF
513 Value *And = Builder->CreateAnd(NSh,
514 ConstantInt::get(I.getContext(), MaskV),
515 TI->getName());
516
517 // Return the value truncated to the interesting size.
518 return new TruncInst(And, I.getType());
519 }
520 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000521
Chris Lattnerdc67e132010-01-05 07:44:46 +0000522 if (Op0->hasOneUse()) {
523 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
524 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
525 Value *V1, *V2;
526 ConstantInt *CC;
527 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000528 default: break;
529 case Instruction::Add:
530 case Instruction::And:
531 case Instruction::Or:
532 case Instruction::Xor: {
533 // These operators commute.
534 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
535 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
536 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
537 m_Specific(Op1)))) {
538 Value *YS = // (Y << C)
539 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
540 // (X + (Y << C))
541 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
542 Op0BO->getOperand(1)->getName());
Sanjay Patelda5682a2017-01-16 21:24:41 +0000543 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000544
545 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
546 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
547 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
548 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
549 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000550 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000551
Chris Lattner2b459fe2010-01-10 06:59:55 +0000552 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
553 Value *Op0BOOp1 = Op0BO->getOperand(1);
554 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Jakub Staszak538e3862012-12-09 15:37:46 +0000555 match(Op0BOOp1,
Jakub Staszak84321852012-12-09 16:06:44 +0000556 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
557 m_ConstantInt(CC)))) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000558 Value *YS = // (Y << C)
559 Builder->CreateShl(Op0BO->getOperand(0), Op1,
560 Op0BO->getName());
561 // X & (CC << C)
562 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
563 V1->getName()+".mask");
564 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000565 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000566 LLVM_FALLTHROUGH;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000567 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000568
Chris Lattner2b459fe2010-01-10 06:59:55 +0000569 case Instruction::Sub: {
570 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
571 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
572 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
573 m_Specific(Op1)))) {
574 Value *YS = // (Y << C)
575 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
576 // (X + (Y << C))
577 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
578 Op0BO->getOperand(0)->getName());
Sanjay Patelda5682a2017-01-16 21:24:41 +0000579 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000580
581 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
582 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
583 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
584 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
585 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattner2b459fe2010-01-10 06:59:55 +0000586 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000587
Chris Lattner2b459fe2010-01-10 06:59:55 +0000588 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
589 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
590 match(Op0BO->getOperand(0),
Jakub Staszak84321852012-12-09 16:06:44 +0000591 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
592 m_ConstantInt(CC))) && V2 == Op1) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000593 Value *YS = // (Y << C)
594 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
595 // X & (CC << C)
596 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
597 V1->getName()+".mask");
Jakub Staszak538e3862012-12-09 15:37:46 +0000598
Chris Lattner2b459fe2010-01-10 06:59:55 +0000599 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
600 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000601
Chris Lattner2b459fe2010-01-10 06:59:55 +0000602 break;
603 }
604 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000605
606
Sanjay Patelfc3d8f02014-07-22 04:57:06 +0000607 // If the operand is a bitwise operator with a constant RHS, and the
Chris Lattnerdc67e132010-01-05 07:44:46 +0000608 // shift is the only use, we can pull it out of the shift.
609 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
610 bool isValid = true; // Valid only for And, Or, Xor
611 bool highBitSet = false; // Transform if high bit of constant set?
Jakub Staszak538e3862012-12-09 15:37:46 +0000612
Chris Lattnerdc67e132010-01-05 07:44:46 +0000613 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000614 default: isValid = false; break; // Do not perform transform!
615 case Instruction::Add:
616 isValid = isLeftShift;
617 break;
618 case Instruction::Or:
619 case Instruction::Xor:
620 highBitSet = false;
621 break;
622 case Instruction::And:
623 highBitSet = true;
624 break;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000625 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000626
Chris Lattnerdc67e132010-01-05 07:44:46 +0000627 // If this is a signed shift right, and the high bit is modified
628 // by the logical operation, do not perform the transformation.
629 // The highBitSet boolean indicates the value of the high bit of
630 // the constant which would cause it to be modified for this
631 // operation.
632 //
633 if (isValid && I.getOpcode() == Instruction::AShr)
634 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Jakub Staszak538e3862012-12-09 15:37:46 +0000635
Chris Lattnerdc67e132010-01-05 07:44:46 +0000636 if (isValid) {
637 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000638
Chris Lattnerdc67e132010-01-05 07:44:46 +0000639 Value *NewShift =
640 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
641 NewShift->takeName(Op0BO);
Jakub Staszak538e3862012-12-09 15:37:46 +0000642
Chris Lattnerdc67e132010-01-05 07:44:46 +0000643 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
644 NewRHS);
645 }
646 }
647 }
648 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000649
Sanjay Patelda5682a2017-01-16 21:24:41 +0000650 if (Instruction *Folded = foldShiftByConstOfShiftByConst(I, Op1C, Builder))
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000651 return Folded;
Jakub Staszak538e3862012-12-09 15:37:46 +0000652
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000654}
655
656Instruction *InstCombiner::visitShl(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000657 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000658 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000659
Sanjay Patelcf082032017-01-13 18:08:25 +0000660 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
661 if (Value *V = SimplifyShlInst(Op0, Op1, I.hasNoSignedWrap(),
662 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000663 return replaceInstUsesWith(I, V);
Jakub Staszak538e3862012-12-09 15:37:46 +0000664
Chris Lattner6b657ae2011-02-10 05:36:31 +0000665 if (Instruction *V = commonShiftTransforms(I))
666 return V;
Jakub Staszak538e3862012-12-09 15:37:46 +0000667
Sanjay Patelb22f6c52017-01-13 18:39:09 +0000668 const APInt *ShAmtAPInt;
669 if (match(Op1, m_APInt(ShAmtAPInt))) {
670 unsigned ShAmt = ShAmtAPInt->getZExtValue();
Sanjay Patel50753f02017-01-26 22:08:10 +0000671 unsigned BitWidth = I.getType()->getScalarSizeInBits();
Sanjay Patel062adaa2017-01-29 17:11:18 +0000672 Type *Ty = I.getType();
Jakub Staszak538e3862012-12-09 15:37:46 +0000673
Sanjay Patelacd24c72017-01-13 18:52:10 +0000674 // shl (zext X), ShAmt --> zext (shl X, ShAmt)
675 // This is only valid if X would have zeros shifted out.
676 Value *X;
677 if (match(Op0, m_ZExt(m_Value(X)))) {
678 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
679 if (ShAmt < SrcWidth &&
680 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
Sanjay Patel062adaa2017-01-29 17:11:18 +0000681 return new ZExtInst(Builder->CreateShl(X, ShAmt), Ty);
David Majnemercb892e92017-01-04 02:21:34 +0000682 }
683
Sanjay Patel50753f02017-01-26 22:08:10 +0000684 // (X >>u C) << C --> X & (-1 << C)
685 if (match(Op0, m_LShr(m_Value(X), m_Specific(Op1)))) {
686 APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
Sanjay Patel062adaa2017-01-29 17:11:18 +0000687 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
688 }
689
690 const APInt *ShrAmt;
691 if (match(Op0, m_CombineOr(m_Exact(m_LShr(m_Value(X), m_APInt(ShrAmt))),
692 m_Exact(m_AShr(m_Value(X), m_APInt(ShrAmt))))) &&
693 ShrAmt->ult(*ShAmtAPInt)) {
694 // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
695 // The inexact version is deferred to DAGCombine, so we don't hide shl
696 // behind a bit mask.
697 Constant *ShiftDiffCst = ConstantInt::get(Ty, *ShAmtAPInt - *ShrAmt);
698 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
699 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
700 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
701 return NewShl;
Sanjay Patel50753f02017-01-26 22:08:10 +0000702 }
703
Chris Lattner6b657ae2011-02-10 05:36:31 +0000704 // If the shifted-out value is known-zero, then this is a NUW shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000705 if (!I.hasNoUnsignedWrap() &&
Sanjay Patel50753f02017-01-26 22:08:10 +0000706 MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
Sanjay Patel690955f2016-01-31 16:34:11 +0000707 I.setHasNoUnsignedWrap();
708 return &I;
709 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000710
Sanjay Patelcf082032017-01-13 18:08:25 +0000711 // If the shifted-out value is all signbits, then this is a NSW shift.
712 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000713 I.setHasNoSignedWrap();
714 return &I;
715 }
716 }
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000717
Benjamin Kramerf0e3f042011-04-29 08:41:23 +0000718 // (C1 << A) << C2 -> (C1 << C2) << A
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000719 Constant *C1, *C2;
720 Value *A;
Sanjay Patelcf082032017-01-13 18:08:25 +0000721 if (match(Op0, m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
722 match(Op1, m_Constant(C2)))
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000723 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
724
Craig Topperf40110f2014-04-25 05:29:35 +0000725 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000726}
727
728Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000729 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000730 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000731
Sanjay Patelcf082032017-01-13 18:08:25 +0000732 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
733 if (Value *V = SimplifyLShrInst(Op0, Op1, I.isExact(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000734 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000735
Chris Lattner249da5c2010-01-23 18:49:30 +0000736 if (Instruction *R = commonShiftTransforms(I))
737 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000738
Sanjay Patel1196d7c2017-01-30 16:11:40 +0000739 Type *Ty = I.getType();
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000740 const APInt *ShAmtAPInt;
741 if (match(Op1, m_APInt(ShAmtAPInt))) {
742 unsigned ShAmt = ShAmtAPInt->getZExtValue();
Sanjay Patel1196d7c2017-01-30 16:11:40 +0000743 unsigned BitWidth = Ty->getScalarSizeInBits();
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000744 auto *II = dyn_cast<IntrinsicInst>(Op0);
745 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
746 (II->getIntrinsicID() == Intrinsic::ctlz ||
747 II->getIntrinsicID() == Intrinsic::cttz ||
748 II->getIntrinsicID() == Intrinsic::ctpop)) {
Chris Lattner249da5c2010-01-23 18:49:30 +0000749 // ctlz.i32(x)>>5 --> zext(x == 0)
750 // cttz.i32(x)>>5 --> zext(x == 0)
751 // ctpop.i32(x)>>5 --> zext(x == -1)
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000752 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
Sanjay Patel1196d7c2017-01-30 16:11:40 +0000753 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000754 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
Sanjay Patel1196d7c2017-01-30 16:11:40 +0000755 return new ZExtInst(Cmp, Ty);
Chris Lattner249da5c2010-01-23 18:49:30 +0000756 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000757
Sanjay Patel50753f02017-01-26 22:08:10 +0000758 Value *X;
Sanjay Patel1196d7c2017-01-30 16:11:40 +0000759 const APInt *ShlAmtAPInt;
760 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShlAmtAPInt)))) {
761 unsigned ShlAmt = ShlAmtAPInt->getZExtValue();
762 if (ShlAmt == ShAmt) {
763 // (X << C) >>u C --> X & (-1 >>u C)
764 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
765 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
766 }
767 if (ShlAmt < ShAmt) {
768 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
769 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
770 // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
771 BinaryOperator *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
772 NewLShr->setIsExact(I.isExact());
773 return NewLShr;
774 }
775 // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2)
776 Value *NewLShr = Builder->CreateLShr(X, ShiftDiff);
777 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
778 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
779 }
Sanjay Patel50753f02017-01-26 22:08:10 +0000780 }
781
Chris Lattner6b657ae2011-02-10 05:36:31 +0000782 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000783 if (!I.isExact() &&
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000784 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000785 I.setIsExact();
786 return &I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000787 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000788 }
Craig Topperf40110f2014-04-25 05:29:35 +0000789 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000790}
791
792Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000793 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000794 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000795
Sanjay Patelcf082032017-01-13 18:08:25 +0000796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
797 if (Value *V = SimplifyAShrInst(Op0, Op1, I.isExact(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000798 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000799
Chris Lattnerdc67e132010-01-05 07:44:46 +0000800 if (Instruction *R = commonShiftTransforms(I))
801 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000802
Sanjay Patelca3124f2017-01-14 23:13:50 +0000803 unsigned BitWidth = I.getType()->getScalarSizeInBits();
Sanjay Patel5f8451a2017-01-15 16:38:19 +0000804 const APInt *ShAmtAPInt;
805 if (match(Op1, m_APInt(ShAmtAPInt))) {
806 unsigned ShAmt = ShAmtAPInt->getZExtValue();
Jakub Staszak538e3862012-12-09 15:37:46 +0000807
Sanjay Patelca3124f2017-01-14 23:13:50 +0000808 // If the shift amount equals the difference in width of the destination
Sanjay Patel5f8451a2017-01-15 16:38:19 +0000809 // and source scalar types:
Sanjay Patelca3124f2017-01-14 23:13:50 +0000810 // ashr (shl (zext X), C), C --> sext X
Chris Lattnera1e223e2010-01-08 19:04:21 +0000811 Value *X;
Sanjay Patelca3124f2017-01-14 23:13:50 +0000812 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
813 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
814 return new SExtInst(X, I.getType());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000815
816 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000817 if (!I.isExact() &&
Sanjay Patelca3124f2017-01-14 23:13:50 +0000818 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000819 I.setIsExact();
820 return &I;
821 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000822 }
823
Chris Lattnerdc67e132010-01-05 07:44:46 +0000824 // See if we can turn a signed shr into an unsigned shr.
Sanjay Patelca3124f2017-01-14 23:13:50 +0000825 if (MaskedValueIsZero(Op0, APInt::getSignBit(BitWidth), 0, &I))
Chris Lattnera1e223e2010-01-08 19:04:21 +0000826 return BinaryOperator::CreateLShr(Op0, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000827
Craig Topperf40110f2014-04-25 05:29:35 +0000828 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000829}