blob: cb165844bdce831138ade76e9280fbc6996f81a0 [file] [log] [blame]
Chris Lattnerec97a902010-01-05 05:36:20 +00001//===- InstCombineVectorOps.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 instcombine for ExtractElement, InsertElement and
11// ShuffleVector.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000016#include "llvm/IR/PatternMatch.h"
Chris Lattnerec97a902010-01-05 05:36:20 +000017using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000018using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000019
Chandler Carruth964daaa2014-04-22 02:55:47 +000020#define DEBUG_TYPE "instcombine"
21
Chris Lattnerec97a902010-01-05 05:36:20 +000022/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
Chris Lattnera0d01ff2012-01-24 14:31:22 +000023/// is to leave as a vector operation. isConstant indicates whether we're
24/// extracting one known element. If false we're extracting a variable index.
Chris Lattnerec97a902010-01-05 05:36:20 +000025static bool CheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000026 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000027 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000028
29 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000030 if (Constant *Op0 = C->getAggregateElement(0U)) {
31 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
32 ++i)
33 if (C->getAggregateElement(i) != Op0)
34 return false;
35 return true;
36 }
Chris Lattnerec97a902010-01-05 05:36:20 +000037 }
38 Instruction *I = dyn_cast<Instruction>(V);
39 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000040
Chris Lattnerec97a902010-01-05 05:36:20 +000041 // Insert element gets simplified to the inserted element or is deleted if
42 // this is constant idx extract element and its a constant idx insertelt.
43 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
44 isa<ConstantInt>(I->getOperand(2)))
45 return true;
46 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
47 return true;
48 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
49 if (BO->hasOneUse() &&
50 (CheapToScalarize(BO->getOperand(0), isConstant) ||
51 CheapToScalarize(BO->getOperand(1), isConstant)))
52 return true;
53 if (CmpInst *CI = dyn_cast<CmpInst>(I))
54 if (CI->hasOneUse() &&
55 (CheapToScalarize(CI->getOperand(0), isConstant) ||
56 CheapToScalarize(CI->getOperand(1), isConstant)))
57 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000058
Chris Lattnerec97a902010-01-05 05:36:20 +000059 return false;
60}
61
Chris Lattnerec97a902010-01-05 05:36:20 +000062/// FindScalarElement - Given a vector and an element number, see if the scalar
63/// value is already around as a register, for example if it were inserted then
64/// extracted from the vector.
65static Value *FindScalarElement(Value *V, unsigned EltNo) {
Duncan Sands19d0b472010-02-16 11:11:14 +000066 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
Chris Lattner8326bd82012-01-26 00:42:34 +000067 VectorType *VTy = cast<VectorType>(V->getType());
68 unsigned Width = VTy->getNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +000069 if (EltNo >= Width) // Out of range access.
Chris Lattner8326bd82012-01-26 00:42:34 +000070 return UndefValue::get(VTy->getElementType());
Bob Wilson8ecf98b2010-10-29 22:20:43 +000071
Chris Lattner8326bd82012-01-26 00:42:34 +000072 if (Constant *C = dyn_cast<Constant>(V))
73 return C->getAggregateElement(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000074
Chris Lattner841af4f2010-01-05 05:42:08 +000075 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000076 // If this is an insert to a variable element, we don't know what it is.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000077 if (!isa<ConstantInt>(III->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +000078 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +000079 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +000080
Chris Lattnerec97a902010-01-05 05:36:20 +000081 // If this is an insert to the element we are looking for, return the
82 // inserted value.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000083 if (EltNo == IIElt)
Chris Lattnerec97a902010-01-05 05:36:20 +000084 return III->getOperand(1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000085
Chris Lattnerec97a902010-01-05 05:36:20 +000086 // Otherwise, the insertelement doesn't modify the value, recurse on its
87 // vector input.
88 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner841af4f2010-01-05 05:42:08 +000089 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000090
Chris Lattner841af4f2010-01-05 05:42:08 +000091 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner8326bd82012-01-26 00:42:34 +000092 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
Eli Friedman303c81c2011-10-21 19:11:34 +000093 int InEl = SVI->getMaskValue(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000094 if (InEl < 0)
Chris Lattner8326bd82012-01-26 00:42:34 +000095 return UndefValue::get(VTy->getElementType());
Bob Wilson11ee4562010-10-29 22:03:05 +000096 if (InEl < (int)LHSWidth)
97 return FindScalarElement(SVI->getOperand(0), InEl);
98 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattnerec97a902010-01-05 05:36:20 +000099 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000100
Nadav Rotem7df85092013-01-15 23:43:14 +0000101 // Extract a value from a vector add operation with a constant zero.
Craig Topperf40110f2014-04-25 05:29:35 +0000102 Value *Val = nullptr; Constant *Con = nullptr;
Nadav Rotem7df85092013-01-15 23:43:14 +0000103 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
104 if (Con->getAggregateElement(EltNo)->isNullValue())
105 return FindScalarElement(Val, EltNo);
106 }
107
Chris Lattnerec97a902010-01-05 05:36:20 +0000108 // Otherwise, we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000109 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000110}
111
Anat Shemer0c95efa2013-04-18 19:35:39 +0000112// If we have a PHI node with a vector type that has only 2 uses: feed
Matt Arsenault38874732013-08-28 22:17:26 +0000113// itself and be an operand of extractelement at a constant location,
114// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +0000115Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
116 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
117 if (!PN->hasNUses(2))
Craig Topperf40110f2014-04-25 05:29:35 +0000118 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000119
120 // If so, it's known at this point that one operand is PHI and the other is
121 // an extractelement node. Find the PHI user that is not the extractelement
122 // node.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000123 auto iu = PN->user_begin();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000124 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
125 if (PHIUser == cast<Instruction>(&EI))
126 PHIUser = cast<Instruction>(*(++iu));
127
128 // Verify that this PHI user has one use, which is the PHI itself,
129 // and that it is a binary operation which is cheap to scalarize.
130 // otherwise return NULL.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000131 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Joey Goulyb34294d2013-05-24 12:33:28 +0000132 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000133 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000134
135 // Create a scalar PHI node that will replace the vector PHI node
136 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000137 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
138 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000139 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000140 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000141 Value *PHIInVal = PN->getIncomingValue(i);
142 BasicBlock *inBB = PN->getIncomingBlock(i);
143 Value *Elt = EI.getIndexOperand();
144 // If the operand is the PHI induction variable:
145 if (PHIInVal == PHIUser) {
146 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000147 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000148 // vector operand.
149 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000150 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000151 Value *Op = InsertNewInstWith(
152 ExtractElementInst::Create(B0->getOperand(opId), Elt,
153 B0->getOperand(opId)->getName() + ".Elt"),
154 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000155 Value *newPHIUser = InsertNewInstWith(
Joey Goulyb34294d2013-05-24 12:33:28 +0000156 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000157 scalarPHI->addIncoming(newPHIUser, inBB);
158 } else {
159 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000160 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000161 // Insert the new instruction into the predecessor basic block.
162 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
163 BasicBlock::iterator InsertPos;
164 if (pos && !isa<PHINode>(pos)) {
165 InsertPos = pos;
166 ++InsertPos;
167 } else {
168 InsertPos = inBB->getFirstInsertionPt();
169 }
170
171 InsertNewInstWith(newEI, *InsertPos);
172
173 scalarPHI->addIncoming(newEI, inBB);
174 }
175 }
176 return ReplaceInstUsesWith(EI, scalarPHI);
177}
178
Chris Lattnerec97a902010-01-05 05:36:20 +0000179Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000180 // If vector val is constant with all elements the same, replace EI with
181 // that element. We handle a known element # below.
182 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
183 if (CheapToScalarize(C, false))
184 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000185
Chris Lattnerec97a902010-01-05 05:36:20 +0000186 // If extracting a specified index from the vector, see if we can recursively
187 // find a previously computed scalar that was inserted into the vector.
188 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
189 unsigned IndexVal = IdxC->getZExtValue();
190 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000191
Chris Lattnerec97a902010-01-05 05:36:20 +0000192 // If this is extracting an invalid index, turn this into undef, to avoid
193 // crashing the code below.
194 if (IndexVal >= VectorWidth)
195 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000196
Chris Lattnerec97a902010-01-05 05:36:20 +0000197 // This instruction only demands the single element from the input vector.
198 // If the input vector has a single use, simplify it based on this use
199 // property.
200 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
201 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000202 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000203 DemandedMask.setBit(IndexVal);
Chris Lattnerec97a902010-01-05 05:36:20 +0000204 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
205 DemandedMask, UndefElts)) {
206 EI.setOperand(0, V);
207 return &EI;
208 }
209 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000210
Chris Lattnerec97a902010-01-05 05:36:20 +0000211 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
212 return ReplaceInstUsesWith(EI, Elt);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000213
Chris Lattnerec97a902010-01-05 05:36:20 +0000214 // If the this extractelement is directly using a bitcast from a vector of
215 // the same number of elements, see if we can find the source element from
216 // it. In this case, we will end up needing to bitcast the scalars.
217 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000218 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000219 if (VT->getNumElements() == VectorWidth)
220 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
221 return new BitCastInst(Elt, EI.getType());
222 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000223
224 // If there's a vector PHI feeding a scalar use through this extractelement
225 // instruction, try to scalarize the PHI.
226 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000227 Instruction *scalarPHI = scalarizePHI(EI, PN);
228 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000229 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000230 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000231 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000232
Chris Lattnerec97a902010-01-05 05:36:20 +0000233 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
234 // Push extractelement into predecessor operation if legal and
235 // profitable to do so
236 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
237 if (I->hasOneUse() &&
238 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
239 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000240 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
241 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000242 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000243 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
244 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000245 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
246 }
247 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
248 // Extracting the inserted element?
249 if (IE->getOperand(2) == EI.getOperand(1))
250 return ReplaceInstUsesWith(EI, IE->getOperand(1));
251 // If the inserted and extracted elements are constants, they must not
252 // be the same value, extract from the pre-inserted value instead.
253 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
254 Worklist.AddValue(EI.getOperand(0));
255 EI.setOperand(0, IE->getOperand(0));
256 return &EI;
257 }
258 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
259 // If this is extracting an element from a shufflevector, figure out where
260 // it came from and extract from the appropriate input element instead.
261 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000262 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000263 Value *Src;
264 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000265 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000266
Bob Wilson11ee4562010-10-29 22:03:05 +0000267 if (SrcIdx < 0)
268 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
269 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000270 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000271 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000272 SrcIdx -= LHSWidth;
273 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000274 }
Chris Lattner229907c2011-07-18 04:54:35 +0000275 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000276 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000277 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000278 SrcIdx, false));
279 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000280 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
281 // Canonicalize extractelement(cast) -> cast(extractelement)
282 // bitcasts can change the number of vector elements and they cost nothing
Anat Shemer55703182013-04-18 19:56:44 +0000283 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Anat Shemer10260a72013-04-22 20:51:10 +0000284 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
285 EI.getIndexOperand());
286 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000287 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
288 }
Matt Arsenault243140f2013-11-04 20:36:06 +0000289 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
290 if (SI->hasOneUse()) {
291 // TODO: For a select on vectors, it might be useful to do this if it
292 // has multiple extractelement uses. For vector select, that seems to
293 // fight the vectorizer.
294
295 // If we are extracting an element from a vector select or a select on
296 // vectors, a select on the scalars extracted from the vector arguments.
297 Value *TrueVal = SI->getTrueValue();
298 Value *FalseVal = SI->getFalseValue();
299
300 Value *Cond = SI->getCondition();
301 if (Cond->getType()->isVectorTy()) {
302 Cond = Builder->CreateExtractElement(Cond,
303 EI.getIndexOperand(),
304 Cond->getName() + ".elt");
305 }
306
307 Value *V1Elem
308 = Builder->CreateExtractElement(TrueVal,
309 EI.getIndexOperand(),
310 TrueVal->getName() + ".elt");
311
312 Value *V2Elem
313 = Builder->CreateExtractElement(FalseVal,
314 EI.getIndexOperand(),
315 FalseVal->getName() + ".elt");
316 return SelectInst::Create(Cond,
317 V1Elem,
318 V2Elem,
319 SI->getName() + ".elt");
320 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000321 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000322 }
Craig Topperf40110f2014-04-25 05:29:35 +0000323 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000324}
325
326/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000327/// elements from either LHS or RHS, return the shuffle mask and true.
Chris Lattnerec97a902010-01-05 05:36:20 +0000328/// Otherwise, return false.
329static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000330 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000331 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000332 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000333 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000334
Chris Lattnerec97a902010-01-05 05:36:20 +0000335 if (isa<UndefValue>(V)) {
336 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
337 return true;
338 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000339
Chris Lattnerec97a902010-01-05 05:36:20 +0000340 if (V == LHS) {
341 for (unsigned i = 0; i != NumElts; ++i)
342 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
343 return true;
344 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000345
Chris Lattnerec97a902010-01-05 05:36:20 +0000346 if (V == RHS) {
347 for (unsigned i = 0; i != NumElts; ++i)
348 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
349 i+NumElts));
350 return true;
351 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000352
Chris Lattnerec97a902010-01-05 05:36:20 +0000353 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
354 // If this is an insert of an extract from some other vector, include it.
355 Value *VecOp = IEI->getOperand(0);
356 Value *ScalarOp = IEI->getOperand(1);
357 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000358
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 if (!isa<ConstantInt>(IdxOp))
360 return false;
361 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000362
Chris Lattnerec97a902010-01-05 05:36:20 +0000363 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000364 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000365 // transitively ok.
366 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
367 // If so, update the mask to reflect the inserted undef.
368 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
369 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000370 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000371 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000372 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000373 unsigned ExtractedIdx =
374 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000375 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000376
Chris Lattnerec97a902010-01-05 05:36:20 +0000377 // This must be extracting from either LHS or RHS.
378 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000379 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000380 // transitively ok.
381 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
382 // If so, update the mask to reflect the inserted value.
383 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000384 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000385 ConstantInt::get(Type::getInt32Ty(V->getContext()),
386 ExtractedIdx);
387 } else {
388 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000389 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000390 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000391 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000392 }
393 return true;
394 }
395 }
396 }
397 }
398 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000399
Chris Lattnerec97a902010-01-05 05:36:20 +0000400 return false;
401}
402
Tim Northoverfad27612014-03-07 10:24:44 +0000403
404/// We are building a shuffle to create V, which is a sequence of insertelement,
405/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000406/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000407/// left and right vectors of the proposed shuffle (or 0), and set the Mask
408/// parameter as required.
409///
410/// Note: we intentionally don't try to fold earlier shuffles since they have
411/// often been chosen carefully to be efficiently implementable on the target.
412typedef std::pair<Value *, Value *> ShuffleOps;
413
414static ShuffleOps CollectShuffleElements(Value *V,
415 SmallVectorImpl<Constant *> &Mask,
416 Value *PermittedRHS) {
417 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Chris Lattnerec97a902010-01-05 05:36:20 +0000418 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000419
Chris Lattnerec97a902010-01-05 05:36:20 +0000420 if (isa<UndefValue>(V)) {
421 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000422 return std::make_pair(
423 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000424 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000425
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000426 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000427 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000428 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000429 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000430
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000431 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000432 // If this is an insert of an extract from some other vector, include it.
433 Value *VecOp = IEI->getOperand(0);
434 Value *ScalarOp = IEI->getOperand(1);
435 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000436
Chris Lattnerec97a902010-01-05 05:36:20 +0000437 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000438 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000439 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000440 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000441 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000442
Chris Lattnerec97a902010-01-05 05:36:20 +0000443 // Either the extracted from or inserted into vector must be RHSVec,
444 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000445 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000446 Value *RHS = EI->getOperand(0);
447 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
Craig Toppere73658d2014-04-28 04:05:08 +0000448 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000449
450 if (LR.first->getType() != RHS->getType()) {
451 // We tried our best, but we can't find anything compatible with RHS
452 // further up the chain. Return a trivial shuffle.
453 for (unsigned i = 0; i < NumElts; ++i)
454 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
455 return std::make_pair(V, nullptr);
456 }
457
458 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000459 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000460 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000461 NumLHSElts+ExtractedIdx);
462 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000463 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000464
Tim Northoverfad27612014-03-07 10:24:44 +0000465 if (VecOp == PermittedRHS) {
466 // We've gone as far as we can: anything on the other side of the
467 // extractelement will already have been converted into a shuffle.
468 unsigned NumLHSElts =
469 EI->getOperand(0)->getType()->getVectorNumElements();
470 for (unsigned i = 0; i != NumElts; ++i)
471 Mask.push_back(ConstantInt::get(
472 Type::getInt32Ty(V->getContext()),
473 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
474 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000475 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000476
Chris Lattnerec97a902010-01-05 05:36:20 +0000477 // If this insertelement is a chain that comes from exactly these two
478 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000479 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
480 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
481 Mask))
482 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000483 }
484 }
485 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000486
Chris Lattnerec97a902010-01-05 05:36:20 +0000487 // Otherwise, can't do anything fancy. Return an identity vector.
488 for (unsigned i = 0; i != NumElts; ++i)
489 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000490 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000491}
492
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000493/// Try to find redundant insertvalue instructions, like the following ones:
494/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
495/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
496/// Here the second instruction inserts values at the same indices, as the
497/// first one, making the first one redundant.
498/// It should be transformed to:
499/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
500Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
501 bool IsRedundant = false;
502 ArrayRef<unsigned int> FirstIndices = I.getIndices();
503
504 // If there is a chain of insertvalue instructions (each of them except the
505 // last one has only one use and it's another insertvalue insn from this
506 // chain), check if any of the 'children' uses the same indices as the first
507 // instruction. In this case, the first one is redundant.
508 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000509 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000510 while (V->hasOneUse() && Depth < 10) {
511 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000512 auto UserInsInst = dyn_cast<InsertValueInst>(U);
513 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000514 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000515 if (UserInsInst->getIndices() == FirstIndices) {
516 IsRedundant = true;
517 break;
518 }
519 V = UserInsInst;
520 Depth++;
521 }
522
523 if (IsRedundant)
524 return ReplaceInstUsesWith(I, I.getOperand(0));
525 return nullptr;
526}
527
Chris Lattnerec97a902010-01-05 05:36:20 +0000528Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
529 Value *VecOp = IE.getOperand(0);
530 Value *ScalarOp = IE.getOperand(1);
531 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000532
Chris Lattnerec97a902010-01-05 05:36:20 +0000533 // Inserting an undef or into an undefined place, remove this.
534 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
535 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000536
537 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000538 // indexes are constant, try to turn this into a shufflevector operation.
539 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000540 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
541 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
542 unsigned NumExtractVectorElts =
543 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000544 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000545 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000546 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000547
Tim Northoverfad27612014-03-07 10:24:44 +0000548 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Chris Lattnerec97a902010-01-05 05:36:20 +0000549 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000550
Tim Northoverfad27612014-03-07 10:24:44 +0000551 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Chris Lattnerec97a902010-01-05 05:36:20 +0000552 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000553
Chris Lattnerec97a902010-01-05 05:36:20 +0000554 // If we are extracting a value from a vector, then inserting it right
555 // back into the same place, just use the input vector.
556 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000557 return ReplaceInstUsesWith(IE, VecOp);
558
Chris Lattnerec97a902010-01-05 05:36:20 +0000559 // If this insertelement isn't used by some other insertelement, turn it
560 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000561 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000562 SmallVector<Constant*, 16> Mask;
Craig Topperf40110f2014-04-25 05:29:35 +0000563 ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
Tim Northoverfad27612014-03-07 10:24:44 +0000564
565 // The proposed shuffle may be trivial, in which case we shouldn't
566 // perform the combine.
567 if (LR.first != &IE && LR.second != &IE) {
568 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000569 if (LR.second == nullptr)
570 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000571 return new ShuffleVectorInst(LR.first, LR.second,
572 ConstantVector::get(Mask));
573 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000574 }
575 }
576 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000577
Chris Lattnerec97a902010-01-05 05:36:20 +0000578 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
579 APInt UndefElts(VWidth, 0);
580 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000581 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
582 if (V != &IE)
583 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000584 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000585 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000586
Craig Topperf40110f2014-04-25 05:29:35 +0000587 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000588}
589
Nick Lewyckya2b77202013-05-31 00:59:42 +0000590/// Return true if we can evaluate the specified expression tree if the vector
591/// elements were shuffled in a different order.
592static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000593 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000594 // We can always reorder the elements of a constant.
595 if (isa<Constant>(V))
596 return true;
597
598 // We won't reorder vector arguments. No IPO here.
599 Instruction *I = dyn_cast<Instruction>(V);
600 if (!I) return false;
601
602 // Two users may expect different orders of the elements. Don't try it.
603 if (!I->hasOneUse())
604 return false;
605
606 if (Depth == 0) return false;
607
608 switch (I->getOpcode()) {
609 case Instruction::Add:
610 case Instruction::FAdd:
611 case Instruction::Sub:
612 case Instruction::FSub:
613 case Instruction::Mul:
614 case Instruction::FMul:
615 case Instruction::UDiv:
616 case Instruction::SDiv:
617 case Instruction::FDiv:
618 case Instruction::URem:
619 case Instruction::SRem:
620 case Instruction::FRem:
621 case Instruction::Shl:
622 case Instruction::LShr:
623 case Instruction::AShr:
624 case Instruction::And:
625 case Instruction::Or:
626 case Instruction::Xor:
627 case Instruction::ICmp:
628 case Instruction::FCmp:
629 case Instruction::Trunc:
630 case Instruction::ZExt:
631 case Instruction::SExt:
632 case Instruction::FPToUI:
633 case Instruction::FPToSI:
634 case Instruction::UIToFP:
635 case Instruction::SIToFP:
636 case Instruction::FPTrunc:
637 case Instruction::FPExt:
638 case Instruction::GetElementPtr: {
639 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
640 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
641 return false;
642 }
643 return true;
644 }
645 case Instruction::InsertElement: {
646 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
647 if (!CI) return false;
648 int ElementNumber = CI->getLimitedValue();
649
650 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
651 // can't put an element into multiple indices.
652 bool SeenOnce = false;
653 for (int i = 0, e = Mask.size(); i != e; ++i) {
654 if (Mask[i] == ElementNumber) {
655 if (SeenOnce)
656 return false;
657 SeenOnce = true;
658 }
659 }
660 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
661 }
662 }
663 return false;
664}
665
666/// Rebuild a new instruction just like 'I' but with the new operands given.
667/// In the event of type mismatch, the type of the operands is correct.
668static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
669 // We don't want to use the IRBuilder here because we want the replacement
670 // instructions to appear next to 'I', not the builder's insertion point.
671 switch (I->getOpcode()) {
672 case Instruction::Add:
673 case Instruction::FAdd:
674 case Instruction::Sub:
675 case Instruction::FSub:
676 case Instruction::Mul:
677 case Instruction::FMul:
678 case Instruction::UDiv:
679 case Instruction::SDiv:
680 case Instruction::FDiv:
681 case Instruction::URem:
682 case Instruction::SRem:
683 case Instruction::FRem:
684 case Instruction::Shl:
685 case Instruction::LShr:
686 case Instruction::AShr:
687 case Instruction::And:
688 case Instruction::Or:
689 case Instruction::Xor: {
690 BinaryOperator *BO = cast<BinaryOperator>(I);
691 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
692 BinaryOperator *New =
693 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
694 NewOps[0], NewOps[1], "", BO);
695 if (isa<OverflowingBinaryOperator>(BO)) {
696 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
697 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
698 }
699 if (isa<PossiblyExactOperator>(BO)) {
700 New->setIsExact(BO->isExact());
701 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000702 if (isa<FPMathOperator>(BO))
703 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000704 return New;
705 }
706 case Instruction::ICmp:
707 assert(NewOps.size() == 2 && "icmp with #ops != 2");
708 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
709 NewOps[0], NewOps[1]);
710 case Instruction::FCmp:
711 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
712 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
713 NewOps[0], NewOps[1]);
714 case Instruction::Trunc:
715 case Instruction::ZExt:
716 case Instruction::SExt:
717 case Instruction::FPToUI:
718 case Instruction::FPToSI:
719 case Instruction::UIToFP:
720 case Instruction::SIToFP:
721 case Instruction::FPTrunc:
722 case Instruction::FPExt: {
723 // It's possible that the mask has a different number of elements from
724 // the original cast. We recompute the destination type to match the mask.
725 Type *DestTy =
726 VectorType::get(I->getType()->getScalarType(),
727 NewOps[0]->getType()->getVectorNumElements());
728 assert(NewOps.size() == 1 && "cast with #ops != 1");
729 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
730 "", I);
731 }
732 case Instruction::GetElementPtr: {
733 Value *Ptr = NewOps[0];
734 ArrayRef<Value*> Idx = NewOps.slice(1);
735 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
736 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
737 return GEP;
738 }
739 }
740 llvm_unreachable("failed to rebuild vector instructions");
741}
742
743Value *
744InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
745 // Mask.size() does not need to be equal to the number of vector elements.
746
747 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
748 if (isa<UndefValue>(V)) {
749 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
750 Mask.size()));
751 }
752 if (isa<ConstantAggregateZero>(V)) {
753 return ConstantAggregateZero::get(
754 VectorType::get(V->getType()->getScalarType(),
755 Mask.size()));
756 }
757 if (Constant *C = dyn_cast<Constant>(V)) {
758 SmallVector<Constant *, 16> MaskValues;
759 for (int i = 0, e = Mask.size(); i != e; ++i) {
760 if (Mask[i] == -1)
761 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
762 else
763 MaskValues.push_back(Builder->getInt32(Mask[i]));
764 }
765 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
766 ConstantVector::get(MaskValues));
767 }
768
769 Instruction *I = cast<Instruction>(V);
770 switch (I->getOpcode()) {
771 case Instruction::Add:
772 case Instruction::FAdd:
773 case Instruction::Sub:
774 case Instruction::FSub:
775 case Instruction::Mul:
776 case Instruction::FMul:
777 case Instruction::UDiv:
778 case Instruction::SDiv:
779 case Instruction::FDiv:
780 case Instruction::URem:
781 case Instruction::SRem:
782 case Instruction::FRem:
783 case Instruction::Shl:
784 case Instruction::LShr:
785 case Instruction::AShr:
786 case Instruction::And:
787 case Instruction::Or:
788 case Instruction::Xor:
789 case Instruction::ICmp:
790 case Instruction::FCmp:
791 case Instruction::Trunc:
792 case Instruction::ZExt:
793 case Instruction::SExt:
794 case Instruction::FPToUI:
795 case Instruction::FPToSI:
796 case Instruction::UIToFP:
797 case Instruction::SIToFP:
798 case Instruction::FPTrunc:
799 case Instruction::FPExt:
800 case Instruction::Select:
801 case Instruction::GetElementPtr: {
802 SmallVector<Value*, 8> NewOps;
803 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
804 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
805 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
806 NewOps.push_back(V);
807 NeedsRebuild |= (V != I->getOperand(i));
808 }
809 if (NeedsRebuild) {
810 return BuildNew(I, NewOps);
811 }
812 return I;
813 }
814 case Instruction::InsertElement: {
815 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +0000816
817 // The insertelement was inserting at Element. Figure out which element
818 // that becomes after shuffling. The answer is guaranteed to be unique
819 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000820 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000821 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000822 for (int e = Mask.size(); Index != e; ++Index) {
823 if (Mask[Index] == Element) {
824 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000825 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000826 }
827 }
Nick Lewyckya2b77202013-05-31 00:59:42 +0000828
Hao Liu26abebb2014-01-08 03:06:15 +0000829 // If element is not in Mask, no need to handle the operand 1 (element to
830 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000831 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +0000832 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +0000833
Nick Lewyckya2b77202013-05-31 00:59:42 +0000834 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
835 return InsertElementInst::Create(V, I->getOperand(1),
836 Builder->getInt32(Index), "", I);
837 }
838 }
839 llvm_unreachable("failed to reorder elements of vector instruction!");
840}
Chris Lattnerec97a902010-01-05 05:36:20 +0000841
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000842static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
843 bool &isLHSID, bool &isRHSID) {
844 isLHSID = isRHSID = true;
845
846 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
847 if (Mask[i] < 0) continue; // Ignore undef values.
848 // Is this an identity shuffle of the LHS value?
849 isLHSID &= (Mask[i] == (int)i);
850
851 // Is this an identity shuffle of the RHS value?
852 isRHSID &= (Mask[i]-e == i);
853 }
854}
855
Chris Lattnerec97a902010-01-05 05:36:20 +0000856Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
857 Value *LHS = SVI.getOperand(0);
858 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000859 SmallVector<int, 16> Mask = SVI.getShuffleMask();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000860
Chris Lattnerec97a902010-01-05 05:36:20 +0000861 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000862
Chris Lattnerec97a902010-01-05 05:36:20 +0000863 // Undefined shuffle mask -> undefined value.
864 if (isa<UndefValue>(SVI.getOperand(2)))
865 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000866
Eric Christopher51edc7b2010-08-17 22:55:27 +0000867 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000868
Chris Lattnerec97a902010-01-05 05:36:20 +0000869 APInt UndefElts(VWidth, 0);
870 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000871 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
872 if (V != &SVI)
873 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000874 LHS = SVI.getOperand(0);
875 RHS = SVI.getOperand(1);
876 MadeChange = true;
877 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000878
Eli Friedmance818272011-10-21 19:06:29 +0000879 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
880
Chris Lattnerec97a902010-01-05 05:36:20 +0000881 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
882 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
883 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000884 if (isa<UndefValue>(LHS) && LHS == RHS) {
885 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +0000886 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +0000887 ? LHS : UndefValue::get(SVI.getType());
Nick Lewyckya2b77202013-05-31 00:59:42 +0000888 return ReplaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000889 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000890
Chris Lattnerec97a902010-01-05 05:36:20 +0000891 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +0000892 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000893 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000894 if (Mask[i] < 0) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000895 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner0256be92012-01-27 03:08:05 +0000896 continue;
897 }
898
899 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
900 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
901 Mask[i] = -1; // Turn into undef.
902 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
903 } else {
904 Mask[i] = Mask[i] % e; // Force to LHS.
905 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
906 Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +0000907 }
908 }
909 SVI.setOperand(0, SVI.getOperand(1));
910 SVI.setOperand(1, UndefValue::get(RHS->getType()));
911 SVI.setOperand(2, ConstantVector::get(Elts));
912 LHS = SVI.getOperand(0);
913 RHS = SVI.getOperand(1);
914 MadeChange = true;
915 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000916
Eli Friedmance818272011-10-21 19:06:29 +0000917 if (VWidth == LHSWidth) {
918 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000919 bool isLHSID, isRHSID;
920 RecognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +0000921
922 // Eliminate identity shuffles.
923 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
924 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000925 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000926
Nick Lewycky688d6682013-06-03 23:15:20 +0000927 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000928 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
929 return ReplaceInstUsesWith(SVI, V);
930 }
931
Eric Christopher51edc7b2010-08-17 22:55:27 +0000932 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +0000933 // one without producing an unusual shuffle.
934 // Cases that might be simplified:
935 // 1.
936 // x1=shuffle(v1,v2,mask1)
937 // x=shuffle(x1,undef,mask)
938 // ==>
939 // x=shuffle(v1,undef,newMask)
940 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
941 // 2.
942 // x1=shuffle(v1,undef,mask1)
943 // x=shuffle(x1,x2,mask)
944 // where v1.size() == mask1.size()
945 // ==>
946 // x=shuffle(v1,x2,newMask)
947 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
948 // 3.
949 // x2=shuffle(v2,undef,mask2)
950 // x=shuffle(x1,x2,mask)
951 // where v2.size() == mask2.size()
952 // ==>
953 // x=shuffle(x1,v2,newMask)
954 // newMask[i] = (mask[i] < x1.size())
955 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
956 // 4.
957 // x1=shuffle(v1,undef,mask1)
958 // x2=shuffle(v2,undef,mask2)
959 // x=shuffle(x1,x2,mask)
960 // where v1.size() == v2.size()
961 // ==>
962 // x=shuffle(v1,v2,newMask)
963 // newMask[i] = (mask[i] < x1.size())
964 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
965 //
966 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +0000967 // we are absolutely afraid of producing a shuffle mask not in the input
968 // program, because the code gen may not be smart enough to turn a merged
969 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +0000970 // we only merge two shuffles if the result is either a splat or one of the
971 // input shuffle masks. In this case, merging the shuffles just removes
972 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +0000973 // turning: (splat(splat)) -> splat, or
974 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
975 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
976 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
977 if (LHSShuffle)
978 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +0000979 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +0000980 if (RHSShuffle)
981 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000982 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +0000983 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +0000984 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +0000985
Craig Topperf40110f2014-04-25 05:29:35 +0000986 Value* LHSOp0 = nullptr;
987 Value* LHSOp1 = nullptr;
988 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +0000989 unsigned LHSOp0Width = 0;
990 unsigned RHSOp0Width = 0;
991 if (LHSShuffle) {
992 LHSOp0 = LHSShuffle->getOperand(0);
993 LHSOp1 = LHSShuffle->getOperand(1);
994 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
995 }
996 if (RHSShuffle) {
997 RHSOp0 = RHSShuffle->getOperand(0);
998 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
999 }
1000 Value* newLHS = LHS;
1001 Value* newRHS = RHS;
1002 if (LHSShuffle) {
1003 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001004 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001005 newLHS = LHSOp0;
1006 newRHS = LHSOp1;
1007 }
1008 // case 2 or 4
1009 else if (LHSOp0Width == LHSWidth) {
1010 newLHS = LHSOp0;
1011 }
1012 }
1013 // case 3 or 4
1014 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1015 newRHS = RHSOp0;
1016 }
1017 // case 4
1018 if (LHSOp0 == RHSOp0) {
1019 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001020 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001021 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001022
Eli Friedmance818272011-10-21 19:06:29 +00001023 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001024 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001025
Eli Friedmance818272011-10-21 19:06:29 +00001026 SmallVector<int, 16> LHSMask;
1027 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001028 if (newLHS != LHS)
1029 LHSMask = LHSShuffle->getShuffleMask();
1030 if (RHSShuffle && newRHS != RHS)
1031 RHSMask = RHSShuffle->getShuffleMask();
1032
Eli Friedmance818272011-10-21 19:06:29 +00001033 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1034 SmallVector<int, 16> newMask;
1035 bool isSplat = true;
1036 int SplatElt = -1;
1037 // Create a new mask for the new ShuffleVectorInst so that the new
1038 // ShuffleVectorInst is equivalent to the original one.
1039 for (unsigned i = 0; i < VWidth; ++i) {
1040 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001041 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001042 // This element is an undef value.
1043 eltMask = -1;
1044 } else if (Mask[i] < (int)LHSWidth) {
1045 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001046 //
Eli Friedmance818272011-10-21 19:06:29 +00001047 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1048 // new mask value for the element.
1049 if (newLHS != LHS) {
1050 eltMask = LHSMask[Mask[i]];
1051 // If the value selected is an undef value, explicitly specify it
1052 // with a -1 mask value.
1053 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1054 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001055 } else
Eli Friedmance818272011-10-21 19:06:29 +00001056 eltMask = Mask[i];
1057 } else {
1058 // This element is from right hand side vector operand
1059 //
1060 // If the value selected is an undef value, explicitly specify it
1061 // with a -1 mask value. (case 1)
1062 if (isa<UndefValue>(RHS))
1063 eltMask = -1;
1064 // If RHS is going to be replaced (case 3 or 4), calculate the
1065 // new mask value for the element.
1066 else if (newRHS != RHS) {
1067 eltMask = RHSMask[Mask[i]-LHSWidth];
1068 // If the value selected is an undef value, explicitly specify it
1069 // with a -1 mask value.
1070 if (eltMask >= (int)RHSOp0Width) {
1071 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1072 && "should have been check above");
1073 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001074 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001075 } else
Eli Friedmance818272011-10-21 19:06:29 +00001076 eltMask = Mask[i]-LHSWidth;
1077
1078 // If LHS's width is changed, shift the mask value accordingly.
1079 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001080 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1081 // If newRHS == newLHS, we want to remap any references from newRHS to
1082 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001083 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001084 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001085 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001086 }
Eli Friedmance818272011-10-21 19:06:29 +00001087
1088 // Check if this could still be a splat.
1089 if (eltMask >= 0) {
1090 if (SplatElt >= 0 && SplatElt != eltMask)
1091 isSplat = false;
1092 SplatElt = eltMask;
1093 }
1094
1095 newMask.push_back(eltMask);
1096 }
1097
1098 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001099 // or is a splat, do the replacement.
1100 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001101 SmallVector<Constant*, 16> Elts;
1102 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1103 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1104 if (newMask[i] < 0) {
1105 Elts.push_back(UndefValue::get(Int32Ty));
1106 } else {
1107 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1108 }
1109 }
Craig Topperf40110f2014-04-25 05:29:35 +00001110 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001111 newRHS = UndefValue::get(newLHS->getType());
1112 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001113 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001114
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001115 // If the result mask is an identity, replace uses of this instruction with
1116 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001117 bool isLHSID, isRHSID;
1118 RecognizeIdentityMask(newMask, isLHSID, isRHSID);
1119 if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1120 if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001121
Craig Topperf40110f2014-04-25 05:29:35 +00001122 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001123}