blob: 341692fa3f4703df25303f5e10409077c952dbbf [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) {
25 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
26 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
27
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
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000042 // 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 +000043 // Because shifts by negative values (which could occur if A were negative)
44 // are undefined.
45 Value *A; const APInt *B;
46 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
47 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
48 // demand the sign bit (and many others) here??
49 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
50 Op1->getName());
51 I.setOperand(1, Rem);
52 return &I;
53 }
Jakub Staszak538e3862012-12-09 15:37:46 +000054
Craig Topperf40110f2014-04-25 05:29:35 +000055 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +000056}
57
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000058/// Return true if we can simplify two logical (either left or right) shifts
59/// that have constant shift amounts.
Sanjay Patelbd8b7792016-04-11 16:11:07 +000060static bool canEvaluateShiftedShift(unsigned FirstShiftAmt,
61 bool IsFirstShiftLeft,
62 Instruction *SecondShift, InstCombiner &IC,
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000063 Instruction *CxtI) {
Sanjay Patel3a48e982016-04-11 17:27:44 +000064 assert(SecondShift->isLogicalShift() && "Unexpected instruction type");
Sanjay Patelb91bcd72016-04-11 17:35:57 +000065
Sanjay Patelbd8b7792016-04-11 16:11:07 +000066 // We need constant shifts.
67 auto *SecondShiftConst = dyn_cast<ConstantInt>(SecondShift->getOperand(1));
68 if (!SecondShiftConst)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000069 return false;
70
Sanjay Patelbd8b7792016-04-11 16:11:07 +000071 unsigned SecondShiftAmt = SecondShiftConst->getZExtValue();
Sanjay Patel37129072016-04-11 17:11:55 +000072 bool IsSecondShiftLeft = SecondShift->getOpcode() == Instruction::Shl;
Sanjay Patelbd8b7792016-04-11 16:11:07 +000073
Sanjay Patel37129072016-04-11 17:11:55 +000074 // We can always fold shl(c1) + shl(c2) -> shl(c1+c2).
75 // We can always fold lshr(c1) + lshr(c2) -> lshr(c1+c2).
76 if (IsFirstShiftLeft == IsSecondShiftLeft)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000077 return true;
78
Sanjay Patel37129072016-04-11 17:11:55 +000079 // We can always fold lshr(c) + shl(c) -> and(c2).
80 // We can always fold shl(c) + lshr(c) -> and(c2).
81 if (FirstShiftAmt == SecondShiftAmt)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000082 return true;
83
Sanjay Patelbd8b7792016-04-11 16:11:07 +000084 unsigned TypeWidth = SecondShift->getType()->getScalarSizeInBits();
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000085
Sanjay Patelbd8b7792016-04-11 16:11:07 +000086 // If the 2nd shift is bigger than the 1st, we can fold:
Sanjay Patel37129072016-04-11 17:11:55 +000087 // lshr(c1) + shl(c2) -> shl(c3) + and(c4) or
88 // shl(c1) + lshr(c2) -> lshr(c3) + and(c4),
Sanjay Patelbd8b7792016-04-11 16:11:07 +000089 // but it isn't profitable unless we know the and'd out bits are already zero.
Sanjay Patel816ec882016-04-11 16:50:32 +000090 // Also check that the 2nd shift is valid (less than the type width) or we'll
91 // crash trying to produce the bit mask for the 'and'.
92 if (SecondShiftAmt > FirstShiftAmt && SecondShiftAmt < TypeWidth) {
Sanjay Patel37129072016-04-11 17:11:55 +000093 unsigned MaskShift = IsSecondShiftLeft ? TypeWidth - SecondShiftAmt
94 : SecondShiftAmt - FirstShiftAmt;
Sanjay Patelbd8b7792016-04-11 16:11:07 +000095 APInt Mask = APInt::getLowBitsSet(TypeWidth, FirstShiftAmt) << MaskShift;
96 if (IC.MaskedValueIsZero(SecondShift->getOperand(0), Mask, 0, CxtI))
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000097 return true;
98 }
99
100 return false;
101}
102
Sanjay Patele6e84172015-11-02 22:34:55 +0000103/// See if we can compute the specified value, but shifted
Chris Lattner18d7fc82010-08-27 22:24:38 +0000104/// logically to the left or right by some number of bits. This should return
105/// true if the expression can be computed for the same cost as the current
106/// expression tree. This is used to eliminate extraneous shifting from things
107/// like:
108/// %C = shl i128 %A, 64
109/// %D = shl i128 %B, 96
110/// %E = or i128 %C, %D
111/// %F = lshr i128 %E, 64
112/// where the client will ask if E can be computed shifted right by 64-bits. If
113/// this succeeds, the GetShiftedValue function will be called to produce the
114/// value.
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000115static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
Hal Finkel60db0582014-09-07 18:57:58 +0000116 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000117 // We can always evaluate constants shifted.
118 if (isa<Constant>(V))
119 return true;
Jakub Staszak538e3862012-12-09 15:37:46 +0000120
Chris Lattner18d7fc82010-08-27 22:24:38 +0000121 Instruction *I = dyn_cast<Instruction>(V);
122 if (!I) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000123
Chris Lattner18d7fc82010-08-27 22:24:38 +0000124 // If this is the opposite shift, we can directly reuse the input of the shift
125 // if the needed bits are already zero in the input. This allows us to reuse
126 // the value which means that we don't care if the shift has multiple uses.
127 // TODO: Handle opposite shift by exact value.
Craig Topperf40110f2014-04-25 05:29:35 +0000128 ConstantInt *CI = nullptr;
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000129 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
130 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000131 if (CI->getZExtValue() == NumBits) {
132 // TODO: Check that the input bits are already zero with MaskedValueIsZero
133#if 0
134 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000135 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner18d7fc82010-08-27 22:24:38 +0000136 // already zeros.
137 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
138 uint32_t BitWidth = Ty->getScalarSizeInBits();
139 if (MaskedValueIsZero(I->getOperand(0),
140 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
141 CI->getLimitedValue(BitWidth) < BitWidth) {
142 return CanEvaluateTruncated(I->getOperand(0), Ty);
143 }
144#endif
Jakub Staszak538e3862012-12-09 15:37:46 +0000145
Chris Lattner18d7fc82010-08-27 22:24:38 +0000146 }
147 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000148
Chris Lattner18d7fc82010-08-27 22:24:38 +0000149 // We can't mutate something that has multiple uses: doing so would
150 // require duplicating the instruction in general, which isn't profitable.
151 if (!I->hasOneUse()) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000152
Chris Lattner18d7fc82010-08-27 22:24:38 +0000153 switch (I->getOpcode()) {
154 default: return false;
155 case Instruction::And:
156 case Instruction::Or:
157 case Instruction::Xor:
158 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000159 return CanEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
160 CanEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
Jakub Staszak538e3862012-12-09 15:37:46 +0000161
Sanjay Patel6eaff5c2016-04-11 15:43:41 +0000162 case Instruction::Shl:
Sanjay Patel37129072016-04-11 17:11:55 +0000163 case Instruction::LShr:
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000164 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000165
Chris Lattner18d7fc82010-08-27 22:24:38 +0000166 case Instruction::Select: {
167 SelectInst *SI = cast<SelectInst>(I);
Sanjay Patel690955f2016-01-31 16:34:11 +0000168 Value *TrueVal = SI->getTrueValue();
169 Value *FalseVal = SI->getFalseValue();
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000170 return CanEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
171 CanEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000172 }
173 case Instruction::PHI: {
174 // We can change a phi if we can change all operands. Note that we never
175 // get into trouble with cyclic PHIs here because we only consider
176 // instructions with a single use.
177 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +0000178 for (Value *IncValue : PN->incoming_values())
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000179 if (!CanEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
Chris Lattner18d7fc82010-08-27 22:24:38 +0000180 return false;
181 return true;
182 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000183 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000184}
185
Sanjay Patele6e84172015-11-02 22:34:55 +0000186/// When CanEvaluateShifted returned true for an expression,
Chris Lattner18d7fc82010-08-27 22:24:38 +0000187/// this value inserts the new computation that produces the shifted value.
188static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000189 InstCombiner &IC, const DataLayout &DL) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000190 // We can always evaluate constants shifted.
191 if (Constant *C = dyn_cast<Constant>(V)) {
192 if (isLeftShift)
193 V = IC.Builder->CreateShl(C, NumBits);
194 else
195 V = IC.Builder->CreateLShr(C, NumBits);
196 // If we got a constantexpr back, try to simplify it with TD info.
David Majnemerd536f232016-07-29 03:27:26 +0000197 if (auto *C = dyn_cast<Constant>(V))
198 if (auto *FoldedC =
Justin Bogner99798402016-08-05 01:06:44 +0000199 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
David Majnemerd536f232016-07-29 03:27:26 +0000200 V = FoldedC;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000201 return V;
202 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000203
Chris Lattner18d7fc82010-08-27 22:24:38 +0000204 Instruction *I = cast<Instruction>(V);
205 IC.Worklist.Add(I);
206
207 switch (I->getOpcode()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000208 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
Chris Lattner18d7fc82010-08-27 22:24:38 +0000209 case Instruction::And:
210 case Instruction::Or:
211 case Instruction::Xor:
212 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000213 I->setOperand(
214 0, GetShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
215 I->setOperand(
216 1, GetShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000217 return I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000218
Chris Lattner18d7fc82010-08-27 22:24:38 +0000219 case Instruction::Shl: {
Eli Friedman530341d2011-07-29 00:18:19 +0000220 BinaryOperator *BO = cast<BinaryOperator>(I);
221 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000222
223 // We only accept shifts-by-a-constant in CanEvaluateShifted.
Eli Friedman530341d2011-07-29 00:18:19 +0000224 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
225
Chris Lattner18d7fc82010-08-27 22:24:38 +0000226 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
227 if (isLeftShift) {
228 // If this is oversized composite shift, then unsigned shifts get 0.
229 unsigned NewShAmt = NumBits+CI->getZExtValue();
230 if (NewShAmt >= TypeWidth)
231 return Constant::getNullValue(I->getType());
232
Eli Friedman530341d2011-07-29 00:18:19 +0000233 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
234 BO->setHasNoUnsignedWrap(false);
235 BO->setHasNoSignedWrap(false);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000236 return I;
237 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000238
Chris Lattner18d7fc82010-08-27 22:24:38 +0000239 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
240 // zeros.
Chris Lattner6c1395f2010-08-27 22:53:44 +0000241 if (CI->getValue() == NumBits) {
242 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
Eli Friedman530341d2011-07-29 00:18:19 +0000243 V = IC.Builder->CreateAnd(BO->getOperand(0),
244 ConstantInt::get(BO->getContext(), Mask));
Chris Lattner6c1395f2010-08-27 22:53:44 +0000245 if (Instruction *VI = dyn_cast<Instruction>(V)) {
Eli Friedman530341d2011-07-29 00:18:19 +0000246 VI->moveBefore(BO);
247 VI->takeName(BO);
Chris Lattner6c1395f2010-08-27 22:53:44 +0000248 }
249 return V;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000250 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000251
Chris Lattner6c1395f2010-08-27 22:53:44 +0000252 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
253 // the and won't be needed.
254 assert(CI->getZExtValue() > NumBits);
Eli Friedman530341d2011-07-29 00:18:19 +0000255 BO->setOperand(1, ConstantInt::get(BO->getType(),
256 CI->getZExtValue() - NumBits));
257 BO->setHasNoUnsignedWrap(false);
258 BO->setHasNoSignedWrap(false);
259 return BO;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000260 }
Sanjay Patelb91bcd72016-04-11 17:35:57 +0000261 // FIXME: This is almost identical to the SHL case. Refactor both cases into
262 // a helper function.
Chris Lattner18d7fc82010-08-27 22:24:38 +0000263 case Instruction::LShr: {
Eli Friedman530341d2011-07-29 00:18:19 +0000264 BinaryOperator *BO = cast<BinaryOperator>(I);
265 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000266 // We only accept shifts-by-a-constant in CanEvaluateShifted.
Eli Friedman530341d2011-07-29 00:18:19 +0000267 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
Jakub Staszak538e3862012-12-09 15:37:46 +0000268
Chris Lattner18d7fc82010-08-27 22:24:38 +0000269 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
270 if (!isLeftShift) {
271 // If this is oversized composite shift, then unsigned shifts get 0.
272 unsigned NewShAmt = NumBits+CI->getZExtValue();
273 if (NewShAmt >= TypeWidth)
Eli Friedman530341d2011-07-29 00:18:19 +0000274 return Constant::getNullValue(BO->getType());
Jakub Staszak538e3862012-12-09 15:37:46 +0000275
Eli Friedman530341d2011-07-29 00:18:19 +0000276 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
277 BO->setIsExact(false);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000278 return I;
279 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000280
Chris Lattner18d7fc82010-08-27 22:24:38 +0000281 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
282 // zeros.
Chris Lattner6c1395f2010-08-27 22:53:44 +0000283 if (CI->getValue() == NumBits) {
284 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
285 V = IC.Builder->CreateAnd(I->getOperand(0),
Eli Friedman530341d2011-07-29 00:18:19 +0000286 ConstantInt::get(BO->getContext(), Mask));
Chris Lattner6c1395f2010-08-27 22:53:44 +0000287 if (Instruction *VI = dyn_cast<Instruction>(V)) {
288 VI->moveBefore(I);
289 VI->takeName(I);
290 }
291 return V;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000292 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000293
Chris Lattner6c1395f2010-08-27 22:53:44 +0000294 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
295 // the and won't be needed.
296 assert(CI->getZExtValue() > NumBits);
Eli Friedman530341d2011-07-29 00:18:19 +0000297 BO->setOperand(1, ConstantInt::get(BO->getType(),
298 CI->getZExtValue() - NumBits));
299 BO->setIsExact(false);
300 return BO;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000301 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000302
Chris Lattner18d7fc82010-08-27 22:24:38 +0000303 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304 I->setOperand(
305 1, GetShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
306 I->setOperand(
307 2, GetShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000308 return I;
309 case Instruction::PHI: {
310 // We can change a phi if we can change all operands. Note that we never
311 // get into trouble with cyclic PHIs here because we only consider
312 // instructions with a single use.
313 PHINode *PN = cast<PHINode>(I);
314 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i), NumBits,
316 isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000317 return PN;
318 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000319 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000320}
321
322
323
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000324Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattnerdc67e132010-01-05 07:44:46 +0000325 BinaryOperator &I) {
326 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Jakub Staszak538e3862012-12-09 15:37:46 +0000327
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000328 ConstantInt *COp1 = nullptr;
329 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
330 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
331 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
332 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
333 else
334 COp1 = dyn_cast<ConstantInt>(Op1);
335
336 if (!COp1)
337 return nullptr;
Jakub Staszak538e3862012-12-09 15:37:46 +0000338
Chris Lattner18d7fc82010-08-27 22:24:38 +0000339 // See if we can propagate this shift into the input, this covers the trivial
340 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
341 if (I.getOpcode() != Instruction::AShr &&
Hal Finkel60db0582014-09-07 18:57:58 +0000342 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this, &I)) {
Chris Lattnerdd660102010-08-28 01:20:38 +0000343 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
344 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Jakub Staszak538e3862012-12-09 15:37:46 +0000345
Sanjay Patel4b198802016-02-01 22:23:39 +0000346 return replaceInstUsesWith(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 I, GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000348 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000349
Jakub Staszak538e3862012-12-09 15:37:46 +0000350 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattnerdc67e132010-01-05 07:44:46 +0000351 // purpose is to compute bits we don't care about.
352 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Jakub Staszak538e3862012-12-09 15:37:46 +0000353
Matt Arsenault6b4bed42014-04-23 16:48:40 +0000354 assert(!COp1->uge(TypeBits) &&
355 "Shift over the type width should have been removed already");
Jakub Staszak538e3862012-12-09 15:37:46 +0000356
Chris Lattnerdc67e132010-01-05 07:44:46 +0000357 // ((X*C1) << C2) == (X * (C1 << C2))
358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
359 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
360 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
361 return BinaryOperator::CreateMul(BO->getOperand(0),
Sanjay Patel690955f2016-01-31 16:34:11 +0000362 ConstantExpr::getShl(BOOp, Op1));
Jakub Staszak538e3862012-12-09 15:37:46 +0000363
Chris Lattnerdc67e132010-01-05 07:44:46 +0000364 // Try to fold constant and into select arguments.
365 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
366 if (Instruction *R = FoldOpIntoSelect(I, SI))
367 return R;
368 if (isa<PHINode>(Op0))
369 if (Instruction *NV = FoldOpIntoPhi(I))
370 return NV;
Jakub Staszak538e3862012-12-09 15:37:46 +0000371
Chris Lattnerdc67e132010-01-05 07:44:46 +0000372 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
373 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
374 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
375 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
376 // place. Don't try to do this transformation in this case. Also, we
377 // require that the input operand is a shift-by-constant so that we have
378 // confidence that the shifts will get folded together. We could do this
379 // xform in more cases, but it is unlikely to be profitable.
Jakub Staszak538e3862012-12-09 15:37:46 +0000380 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
Chris Lattnerdc67e132010-01-05 07:44:46 +0000381 isa<ConstantInt>(TrOp->getOperand(1))) {
382 // Okay, we'll do this xform. Make the shift of shift.
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000383 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000384 // (shift2 (shift1 & 0x00FF), c2)
385 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
386
387 // For logical shifts, the truncation has the effect of making the high
388 // part of the register be zeros. Emulate this by inserting an AND to
389 // clear the top bits as needed. This 'and' will usually be zapped by
390 // other xforms later if dead.
391 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
392 unsigned DstSize = TI->getType()->getScalarSizeInBits();
393 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
Jakub Staszak538e3862012-12-09 15:37:46 +0000394
Chris Lattnerdc67e132010-01-05 07:44:46 +0000395 // The mask we constructed says what the trunc would do if occurring
396 // between the shifts. We want to know the effect *after* the second
397 // shift. We know that it is a logical shift by a constant, so adjust the
398 // mask as appropriate.
399 if (I.getOpcode() == Instruction::Shl)
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000400 MaskV <<= COp1->getZExtValue();
Chris Lattnerdc67e132010-01-05 07:44:46 +0000401 else {
402 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000403 MaskV = MaskV.lshr(COp1->getZExtValue());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000404 }
405
406 // shift1 & 0x00FF
407 Value *And = Builder->CreateAnd(NSh,
408 ConstantInt::get(I.getContext(), MaskV),
409 TI->getName());
410
411 // Return the value truncated to the interesting size.
412 return new TruncInst(And, I.getType());
413 }
414 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000415
Chris Lattnerdc67e132010-01-05 07:44:46 +0000416 if (Op0->hasOneUse()) {
417 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
418 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
419 Value *V1, *V2;
420 ConstantInt *CC;
421 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000422 default: break;
423 case Instruction::Add:
424 case Instruction::And:
425 case Instruction::Or:
426 case Instruction::Xor: {
427 // These operators commute.
428 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
429 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
430 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
431 m_Specific(Op1)))) {
432 Value *YS = // (Y << C)
433 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
434 // (X + (Y << C))
435 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
436 Op0BO->getOperand(1)->getName());
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000437 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
438
439 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
440 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
441 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
442 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
443 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000444 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000445
Chris Lattner2b459fe2010-01-10 06:59:55 +0000446 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
447 Value *Op0BOOp1 = Op0BO->getOperand(1);
448 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Jakub Staszak538e3862012-12-09 15:37:46 +0000449 match(Op0BOOp1,
Jakub Staszak84321852012-12-09 16:06:44 +0000450 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
451 m_ConstantInt(CC)))) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000452 Value *YS = // (Y << C)
453 Builder->CreateShl(Op0BO->getOperand(0), Op1,
454 Op0BO->getName());
455 // X & (CC << C)
456 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
457 V1->getName()+".mask");
458 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000459 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000460 LLVM_FALLTHROUGH;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000461 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000462
Chris Lattner2b459fe2010-01-10 06:59:55 +0000463 case Instruction::Sub: {
464 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
465 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
466 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
467 m_Specific(Op1)))) {
468 Value *YS = // (Y << C)
469 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
470 // (X + (Y << C))
471 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
472 Op0BO->getOperand(0)->getName());
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000473 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
474
475 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
476 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
477 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
478 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
479 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattner2b459fe2010-01-10 06:59:55 +0000480 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000481
Chris Lattner2b459fe2010-01-10 06:59:55 +0000482 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
483 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
484 match(Op0BO->getOperand(0),
Jakub Staszak84321852012-12-09 16:06:44 +0000485 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
486 m_ConstantInt(CC))) && V2 == Op1) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000487 Value *YS = // (Y << C)
488 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
489 // X & (CC << C)
490 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
491 V1->getName()+".mask");
Jakub Staszak538e3862012-12-09 15:37:46 +0000492
Chris Lattner2b459fe2010-01-10 06:59:55 +0000493 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
494 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000495
Chris Lattner2b459fe2010-01-10 06:59:55 +0000496 break;
497 }
498 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000499
500
Sanjay Patelfc3d8f02014-07-22 04:57:06 +0000501 // If the operand is a bitwise operator with a constant RHS, and the
Chris Lattnerdc67e132010-01-05 07:44:46 +0000502 // shift is the only use, we can pull it out of the shift.
503 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
504 bool isValid = true; // Valid only for And, Or, Xor
505 bool highBitSet = false; // Transform if high bit of constant set?
Jakub Staszak538e3862012-12-09 15:37:46 +0000506
Chris Lattnerdc67e132010-01-05 07:44:46 +0000507 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000508 default: isValid = false; break; // Do not perform transform!
509 case Instruction::Add:
510 isValid = isLeftShift;
511 break;
512 case Instruction::Or:
513 case Instruction::Xor:
514 highBitSet = false;
515 break;
516 case Instruction::And:
517 highBitSet = true;
518 break;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000519 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000520
Chris Lattnerdc67e132010-01-05 07:44:46 +0000521 // If this is a signed shift right, and the high bit is modified
522 // by the logical operation, do not perform the transformation.
523 // The highBitSet boolean indicates the value of the high bit of
524 // the constant which would cause it to be modified for this
525 // operation.
526 //
527 if (isValid && I.getOpcode() == Instruction::AShr)
528 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Jakub Staszak538e3862012-12-09 15:37:46 +0000529
Chris Lattnerdc67e132010-01-05 07:44:46 +0000530 if (isValid) {
531 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000532
Chris Lattnerdc67e132010-01-05 07:44:46 +0000533 Value *NewShift =
534 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
535 NewShift->takeName(Op0BO);
Jakub Staszak538e3862012-12-09 15:37:46 +0000536
Chris Lattnerdc67e132010-01-05 07:44:46 +0000537 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
538 NewRHS);
539 }
540 }
541 }
542 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000543
Chris Lattnerdc67e132010-01-05 07:44:46 +0000544 // Find out if this is a shift of a shift by a constant.
545 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
546 if (ShiftOp && !ShiftOp->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +0000547 ShiftOp = nullptr;
Jakub Staszak538e3862012-12-09 15:37:46 +0000548
Chris Lattnerdc67e132010-01-05 07:44:46 +0000549 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000550
551 // This is a constant shift of a constant shift. Be careful about hiding
552 // shl instructions behind bit masks. They are used to represent multiplies
553 // by a constant, and it is important that simple arithmetic expressions
554 // are still recognizable by scalar evolution.
555 //
556 // The transforms applied to shl are very similar to the transforms applied
557 // to mul by constant. We can be more aggressive about optimizing right
558 // shifts.
559 //
560 // Combinations of right and left shifts will still be optimized in
561 // DAGCombine where scalar evolution no longer applies.
562
Chris Lattnerdc67e132010-01-05 07:44:46 +0000563 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
564 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000565 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000566 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
Craig Topperf40110f2014-04-25 05:29:35 +0000567 if (ShiftAmt1 == 0) return nullptr; // Will be simplified in the future.
Chris Lattnerdc67e132010-01-05 07:44:46 +0000568 Value *X = ShiftOp->getOperand(0);
Jakub Staszak538e3862012-12-09 15:37:46 +0000569
Chris Lattner229907c2011-07-18 04:54:35 +0000570 IntegerType *Ty = cast<IntegerType>(I.getType());
Jakub Staszak538e3862012-12-09 15:37:46 +0000571
Chris Lattnerdc67e132010-01-05 07:44:46 +0000572 // Check for (X << c1) << c2 and (X >> c1) >> c2
573 if (I.getOpcode() == ShiftOp->getOpcode()) {
Nick Lewyckyb59008c2011-12-31 21:30:22 +0000574 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerdc67e132010-01-05 07:44:46 +0000575 // If this is oversized composite shift, then unsigned shifts get 0, ashr
576 // saturates.
577 if (AmtSum >= TypeBits) {
578 if (I.getOpcode() != Instruction::AShr)
Sanjay Patel4b198802016-02-01 22:23:39 +0000579 return replaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdc67e132010-01-05 07:44:46 +0000580 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
581 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000582
Chris Lattnerdc67e132010-01-05 07:44:46 +0000583 return BinaryOperator::Create(I.getOpcode(), X,
584 ConstantInt::get(Ty, AmtSum));
585 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000586
Chris Lattnerdc67e132010-01-05 07:44:46 +0000587 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerdc67e132010-01-05 07:44:46 +0000588 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
Chris Lattner25a198e2010-08-27 21:04:34 +0000589 if (I.getOpcode() == Instruction::LShr &&
590 ShiftOp->getOpcode() == Instruction::Shl) {
Chris Lattnerdc67e132010-01-05 07:44:46 +0000591 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
592 return BinaryOperator::CreateAnd(X,
593 ConstantInt::get(I.getContext(), Mask));
594 }
Chris Lattnerdc67e132010-01-05 07:44:46 +0000595 } else if (ShiftAmt1 < ShiftAmt2) {
596 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000597
598 // (X >>?,exact C1) << C2 --> X << (C2-C1)
599 // The inexact version is deferred to DAGCombine so we don't hide shl
600 // behind a bit mask.
Chris Lattner25a198e2010-08-27 21:04:34 +0000601 if (I.getOpcode() == Instruction::Shl &&
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000602 ShiftOp->getOpcode() != Instruction::Shl &&
603 ShiftOp->isExact()) {
Chris Lattnerdc67e132010-01-05 07:44:46 +0000604 assert(ShiftOp->getOpcode() == Instruction::LShr ||
605 ShiftOp->getOpcode() == Instruction::AShr);
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000606 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000607 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
608 X, ShiftDiffCst);
609 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
610 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
611 return NewShl;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000612 }
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000613
Chris Lattnerdc67e132010-01-05 07:44:46 +0000614 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner25a198e2010-08-27 21:04:34 +0000615 if (I.getOpcode() == Instruction::LShr &&
616 ShiftOp->getOpcode() == Instruction::Shl) {
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000617 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
618 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
619 if (ShiftOp->hasNoUnsignedWrap()) {
620 BinaryOperator *NewLShr = BinaryOperator::Create(Instruction::LShr,
621 X, ShiftDiffCst);
622 NewLShr->setIsExact(I.isExact());
623 return NewLShr;
624 }
625 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
Jakub Staszak538e3862012-12-09 15:37:46 +0000626
Chris Lattnerdc67e132010-01-05 07:44:46 +0000627 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
628 return BinaryOperator::CreateAnd(Shift,
629 ConstantInt::get(I.getContext(),Mask));
630 }
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000631
632 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
633 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
634 if (I.getOpcode() == Instruction::AShr &&
635 ShiftOp->getOpcode() == Instruction::Shl) {
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000636 if (ShiftOp->hasNoSignedWrap()) {
637 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
638 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
639 BinaryOperator *NewAShr = BinaryOperator::Create(Instruction::AShr,
640 X, ShiftDiffCst);
641 NewAShr->setIsExact(I.isExact());
642 return NewAShr;
643 }
644 }
Chris Lattnerdc67e132010-01-05 07:44:46 +0000645 } else {
646 assert(ShiftAmt2 < ShiftAmt1);
647 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
648
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000649 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
650 // The inexact version is deferred to DAGCombine so we don't hide shl
651 // behind a bit mask.
Chris Lattner25a198e2010-08-27 21:04:34 +0000652 if (I.getOpcode() == Instruction::Shl &&
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000653 ShiftOp->getOpcode() != Instruction::Shl &&
654 ShiftOp->isExact()) {
Nick Lewyckyb59008c2011-12-31 21:30:22 +0000655 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000656 BinaryOperator *NewShr = BinaryOperator::Create(ShiftOp->getOpcode(),
657 X, ShiftDiffCst);
658 NewShr->setIsExact(true);
659 return NewShr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000660 }
Jakob Stoklund Olesen43bcb972012-04-23 17:39:52 +0000661
Chris Lattnerdc67e132010-01-05 07:44:46 +0000662 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner25a198e2010-08-27 21:04:34 +0000663 if (I.getOpcode() == Instruction::LShr &&
664 ShiftOp->getOpcode() == Instruction::Shl) {
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000665 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
666 if (ShiftOp->hasNoUnsignedWrap()) {
667 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
668 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
669 X, ShiftDiffCst);
670 NewShl->setHasNoUnsignedWrap(true);
671 return NewShl;
672 }
673 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
Jakub Staszak538e3862012-12-09 15:37:46 +0000674
Chris Lattnerdc67e132010-01-05 07:44:46 +0000675 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
676 return BinaryOperator::CreateAnd(Shift,
677 ConstantInt::get(I.getContext(),Mask));
678 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000679
Nick Lewycky0c48afa2012-01-04 09:28:29 +0000680 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
681 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
682 if (I.getOpcode() == Instruction::AShr &&
683 ShiftOp->getOpcode() == Instruction::Shl) {
684 if (ShiftOp->hasNoSignedWrap()) {
685 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
686 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
687 BinaryOperator *NewShl = BinaryOperator::Create(Instruction::Shl,
688 X, ShiftDiffCst);
689 NewShl->setHasNoSignedWrap(true);
690 return NewShl;
691 }
692 }
Chris Lattnerdc67e132010-01-05 07:44:46 +0000693 }
694 }
Craig Topperf40110f2014-04-25 05:29:35 +0000695 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000696}
697
698Instruction *InstCombiner::visitShl(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000699 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000700 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000701
Chandler Carruth66b31302015-01-04 12:03:27 +0000702 if (Value *V =
703 SimplifyShlInst(I.getOperand(0), I.getOperand(1), I.hasNoSignedWrap(),
Justin Bogner99798402016-08-05 01:06:44 +0000704 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000705 return replaceInstUsesWith(I, V);
Jakub Staszak538e3862012-12-09 15:37:46 +0000706
Chris Lattner6b657ae2011-02-10 05:36:31 +0000707 if (Instruction *V = commonShiftTransforms(I))
708 return V;
Jakub Staszak538e3862012-12-09 15:37:46 +0000709
Chris Lattner6b657ae2011-02-10 05:36:31 +0000710 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
711 unsigned ShAmt = Op1C->getZExtValue();
Jakub Staszak538e3862012-12-09 15:37:46 +0000712
Chris Lattner6b657ae2011-02-10 05:36:31 +0000713 // If the shifted-out value is known-zero, then this is a NUW shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000714 if (!I.hasNoUnsignedWrap() &&
Chris Lattner6b657ae2011-02-10 05:36:31 +0000715 MaskedValueIsZero(I.getOperand(0),
Sanjay Patel690955f2016-01-31 16:34:11 +0000716 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt), 0,
717 &I)) {
718 I.setHasNoUnsignedWrap();
719 return &I;
720 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000721
Chris Lattner6b657ae2011-02-10 05:36:31 +0000722 // If the shifted out value is all signbits, this is a NSW shift.
723 if (!I.hasNoSignedWrap() &&
Hal Finkel60db0582014-09-07 18:57:58 +0000724 ComputeNumSignBits(I.getOperand(0), 0, &I) > ShAmt) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000725 I.setHasNoSignedWrap();
726 return &I;
727 }
728 }
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000729
Benjamin Kramerf0e3f042011-04-29 08:41:23 +0000730 // (C1 << A) << C2 -> (C1 << C2) << A
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000731 Constant *C1, *C2;
732 Value *A;
733 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
734 match(I.getOperand(1), m_Constant(C2)))
735 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
736
Craig Topperf40110f2014-04-25 05:29:35 +0000737 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000738}
739
740Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000741 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000742 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000743
Chandler Carruth66b31302015-01-04 12:03:27 +0000744 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
Justin Bogner99798402016-08-05 01:06:44 +0000745 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000746 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000747
Chris Lattner249da5c2010-01-23 18:49:30 +0000748 if (Instruction *R = commonShiftTransforms(I))
749 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000750
Chris Lattner249da5c2010-01-23 18:49:30 +0000751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000752
Chris Lattner6b657ae2011-02-10 05:36:31 +0000753 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
754 unsigned ShAmt = Op1C->getZExtValue();
755
Chris Lattner249da5c2010-01-23 18:49:30 +0000756 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
Chris Lattnere112ff62010-01-23 23:31:46 +0000757 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
Chris Lattner249da5c2010-01-23 18:49:30 +0000758 // ctlz.i32(x)>>5 --> zext(x == 0)
759 // cttz.i32(x)>>5 --> zext(x == 0)
760 // ctpop.i32(x)>>5 --> zext(x == -1)
761 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
762 II->getIntrinsicID() == Intrinsic::cttz ||
763 II->getIntrinsicID() == Intrinsic::ctpop) &&
Chris Lattner6b657ae2011-02-10 05:36:31 +0000764 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
Chris Lattner249da5c2010-01-23 18:49:30 +0000765 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
Chris Lattnere112ff62010-01-23 23:31:46 +0000766 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
Gabor Greif4a39b842010-06-24 00:44:01 +0000767 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
Chris Lattner249da5c2010-01-23 18:49:30 +0000768 return new ZExtInst(Cmp, II->getType());
769 }
770 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000771
Chris Lattner6b657ae2011-02-10 05:36:31 +0000772 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000773 if (!I.isExact() &&
Hal Finkel60db0582014-09-07 18:57:58 +0000774 MaskedValueIsZero(Op0, APInt::getLowBitsSet(Op1C->getBitWidth(), ShAmt),
775 0, &I)){
Chris Lattner6b657ae2011-02-10 05:36:31 +0000776 I.setIsExact();
777 return &I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000778 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000779 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000780
Craig Topperf40110f2014-04-25 05:29:35 +0000781 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000782}
783
784Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000785 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000786 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000787
Chandler Carruth66b31302015-01-04 12:03:27 +0000788 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
Justin Bogner99798402016-08-05 01:06:44 +0000789 DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000790 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000791
Chris Lattnerdc67e132010-01-05 07:44:46 +0000792 if (Instruction *R = commonShiftTransforms(I))
793 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000794
Chris Lattnera1e223e2010-01-08 19:04:21 +0000795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000796
Chris Lattnera1e223e2010-01-08 19:04:21 +0000797 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000798 unsigned ShAmt = Op1C->getZExtValue();
Jakub Staszak538e3862012-12-09 15:37:46 +0000799
Chris Lattnera1e223e2010-01-08 19:04:21 +0000800 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
Chris Lattner43f2fa62010-01-18 22:19:16 +0000801 // have a sign-extend idiom.
Chris Lattnera1e223e2010-01-08 19:04:21 +0000802 Value *X;
Chris Lattner43f2fa62010-01-18 22:19:16 +0000803 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
Chris Lattner43f2fa62010-01-18 22:19:16 +0000804 // If the input is an extension from the shifted amount value, e.g.
805 // %x = zext i8 %A to i32
806 // %y = shl i32 %x, 24
807 // %z = ashr %y, 24
808 // then turn this into "z = sext i8 A to i32".
809 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
810 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
811 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
812 if (Op1C->getZExtValue() == DestBits-SrcBits)
813 return new SExtInst(ZI->getOperand(0), ZI->getType());
814 }
815 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000816
817 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000818 if (!I.isExact() &&
Sanjay Patel690955f2016-01-31 16:34:11 +0000819 MaskedValueIsZero(Op0, APInt::getLowBitsSet(Op1C->getBitWidth(), ShAmt),
820 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000821 I.setIsExact();
822 return &I;
823 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000824 }
825
Chris Lattnerdc67e132010-01-05 07:44:46 +0000826 // See if we can turn a signed shr into an unsigned shr.
827 if (MaskedValueIsZero(Op0,
Hal Finkel60db0582014-09-07 18:57:58 +0000828 APInt::getSignBit(I.getType()->getScalarSizeInBits()),
829 0, &I))
Chris Lattnera1e223e2010-01-08 19:04:21 +0000830 return BinaryOperator::CreateLShr(Op0, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000831
Craig Topperf40110f2014-04-25 05:29:35 +0000832 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000833}