blob: 24446c8578e0414250db95b12f495fbaa03aadf3 [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
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
JF Bastiend52c9902015-02-25 22:30:51 +000016#include "llvm/ADT/DenseMap.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chris Lattnerec97a902010-01-05 05:36:20 +000018using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000019using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000020
Chandler Carruth964daaa2014-04-22 02:55:47 +000021#define DEBUG_TYPE "instcombine"
22
Chris Lattnerec97a902010-01-05 05:36:20 +000023/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
Chris Lattnera0d01ff2012-01-24 14:31:22 +000024/// is to leave as a vector operation. isConstant indicates whether we're
25/// extracting one known element. If false we're extracting a variable index.
Chris Lattnerec97a902010-01-05 05:36:20 +000026static bool CheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000027 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000028 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000029
30 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000031 if (Constant *Op0 = C->getAggregateElement(0U)) {
32 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
33 ++i)
34 if (C->getAggregateElement(i) != Op0)
35 return false;
36 return true;
37 }
Chris Lattnerec97a902010-01-05 05:36:20 +000038 }
39 Instruction *I = dyn_cast<Instruction>(V);
40 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000041
Chris Lattnerec97a902010-01-05 05:36:20 +000042 // Insert element gets simplified to the inserted element or is deleted if
43 // this is constant idx extract element and its a constant idx insertelt.
44 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
45 isa<ConstantInt>(I->getOperand(2)))
46 return true;
47 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
48 return true;
49 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
50 if (BO->hasOneUse() &&
51 (CheapToScalarize(BO->getOperand(0), isConstant) ||
52 CheapToScalarize(BO->getOperand(1), isConstant)))
53 return true;
54 if (CmpInst *CI = dyn_cast<CmpInst>(I))
55 if (CI->hasOneUse() &&
56 (CheapToScalarize(CI->getOperand(0), isConstant) ||
57 CheapToScalarize(CI->getOperand(1), isConstant)))
58 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000059
Chris Lattnerec97a902010-01-05 05:36:20 +000060 return false;
61}
62
Chris Lattnerec97a902010-01-05 05:36:20 +000063/// FindScalarElement - Given a vector and an element number, see if the scalar
64/// value is already around as a register, for example if it were inserted then
65/// extracted from the vector.
66static Value *FindScalarElement(Value *V, unsigned EltNo) {
Duncan Sands19d0b472010-02-16 11:11:14 +000067 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
Chris Lattner8326bd82012-01-26 00:42:34 +000068 VectorType *VTy = cast<VectorType>(V->getType());
69 unsigned Width = VTy->getNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +000070 if (EltNo >= Width) // Out of range access.
Chris Lattner8326bd82012-01-26 00:42:34 +000071 return UndefValue::get(VTy->getElementType());
Bob Wilson8ecf98b2010-10-29 22:20:43 +000072
Chris Lattner8326bd82012-01-26 00:42:34 +000073 if (Constant *C = dyn_cast<Constant>(V))
74 return C->getAggregateElement(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000075
Chris Lattner841af4f2010-01-05 05:42:08 +000076 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000077 // If this is an insert to a variable element, we don't know what it is.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000078 if (!isa<ConstantInt>(III->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +000079 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +000080 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +000081
Chris Lattnerec97a902010-01-05 05:36:20 +000082 // If this is an insert to the element we are looking for, return the
83 // inserted value.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000084 if (EltNo == IIElt)
Chris Lattnerec97a902010-01-05 05:36:20 +000085 return III->getOperand(1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000086
Chris Lattnerec97a902010-01-05 05:36:20 +000087 // Otherwise, the insertelement doesn't modify the value, recurse on its
88 // vector input.
89 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner841af4f2010-01-05 05:42:08 +000090 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000091
Chris Lattner841af4f2010-01-05 05:42:08 +000092 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner8326bd82012-01-26 00:42:34 +000093 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
Eli Friedman303c81c2011-10-21 19:11:34 +000094 int InEl = SVI->getMaskValue(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000095 if (InEl < 0)
Chris Lattner8326bd82012-01-26 00:42:34 +000096 return UndefValue::get(VTy->getElementType());
Bob Wilson11ee4562010-10-29 22:03:05 +000097 if (InEl < (int)LHSWidth)
98 return FindScalarElement(SVI->getOperand(0), InEl);
99 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattnerec97a902010-01-05 05:36:20 +0000100 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000101
Nadav Rotem7df85092013-01-15 23:43:14 +0000102 // Extract a value from a vector add operation with a constant zero.
Craig Topperf40110f2014-04-25 05:29:35 +0000103 Value *Val = nullptr; Constant *Con = nullptr;
Nadav Rotem7df85092013-01-15 23:43:14 +0000104 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
105 if (Con->getAggregateElement(EltNo)->isNullValue())
106 return FindScalarElement(Val, EltNo);
107 }
108
Chris Lattnerec97a902010-01-05 05:36:20 +0000109 // Otherwise, we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000110 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000111}
112
Anat Shemer0c95efa2013-04-18 19:35:39 +0000113// If we have a PHI node with a vector type that has only 2 uses: feed
Matt Arsenault38874732013-08-28 22:17:26 +0000114// itself and be an operand of extractelement at a constant location,
115// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +0000116Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
117 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
118 if (!PN->hasNUses(2))
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000120
121 // If so, it's known at this point that one operand is PHI and the other is
122 // an extractelement node. Find the PHI user that is not the extractelement
123 // node.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000124 auto iu = PN->user_begin();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000125 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
126 if (PHIUser == cast<Instruction>(&EI))
127 PHIUser = cast<Instruction>(*(++iu));
128
129 // Verify that this PHI user has one use, which is the PHI itself,
130 // and that it is a binary operation which is cheap to scalarize.
131 // otherwise return NULL.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000132 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Joey Goulyb34294d2013-05-24 12:33:28 +0000133 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000134 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000135
136 // Create a scalar PHI node that will replace the vector PHI node
137 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000138 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
139 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000140 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000141 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000142 Value *PHIInVal = PN->getIncomingValue(i);
143 BasicBlock *inBB = PN->getIncomingBlock(i);
144 Value *Elt = EI.getIndexOperand();
145 // If the operand is the PHI induction variable:
146 if (PHIInVal == PHIUser) {
147 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000148 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000149 // vector operand.
150 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000151 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000152 Value *Op = InsertNewInstWith(
153 ExtractElementInst::Create(B0->getOperand(opId), Elt,
154 B0->getOperand(opId)->getName() + ".Elt"),
155 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000156 Value *newPHIUser = InsertNewInstWith(
Joey Goulyb34294d2013-05-24 12:33:28 +0000157 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000158 scalarPHI->addIncoming(newPHIUser, inBB);
159 } else {
160 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000161 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000162 // Insert the new instruction into the predecessor basic block.
163 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
164 BasicBlock::iterator InsertPos;
165 if (pos && !isa<PHINode>(pos)) {
166 InsertPos = pos;
167 ++InsertPos;
168 } else {
169 InsertPos = inBB->getFirstInsertionPt();
170 }
171
172 InsertNewInstWith(newEI, *InsertPos);
173
174 scalarPHI->addIncoming(newEI, inBB);
175 }
176 }
177 return ReplaceInstUsesWith(EI, scalarPHI);
178}
179
Chris Lattnerec97a902010-01-05 05:36:20 +0000180Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000181 // If vector val is constant with all elements the same, replace EI with
182 // that element. We handle a known element # below.
183 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
184 if (CheapToScalarize(C, false))
185 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000186
Chris Lattnerec97a902010-01-05 05:36:20 +0000187 // If extracting a specified index from the vector, see if we can recursively
188 // find a previously computed scalar that was inserted into the vector.
189 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
190 unsigned IndexVal = IdxC->getZExtValue();
191 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000192
Chris Lattnerec97a902010-01-05 05:36:20 +0000193 // If this is extracting an invalid index, turn this into undef, to avoid
194 // crashing the code below.
195 if (IndexVal >= VectorWidth)
196 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000197
Chris Lattnerec97a902010-01-05 05:36:20 +0000198 // This instruction only demands the single element from the input vector.
199 // If the input vector has a single use, simplify it based on this use
200 // property.
201 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
202 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000203 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000204 DemandedMask.setBit(IndexVal);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000205 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
206 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000207 EI.setOperand(0, V);
208 return &EI;
209 }
210 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000211
Chris Lattnerec97a902010-01-05 05:36:20 +0000212 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
213 return ReplaceInstUsesWith(EI, Elt);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000214
Chris Lattnerec97a902010-01-05 05:36:20 +0000215 // If the this extractelement is directly using a bitcast from a vector of
216 // the same number of elements, see if we can find the source element from
217 // it. In this case, we will end up needing to bitcast the scalars.
218 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000219 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000220 if (VT->getNumElements() == VectorWidth)
221 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
222 return new BitCastInst(Elt, EI.getType());
223 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000224
225 // If there's a vector PHI feeding a scalar use through this extractelement
226 // instruction, try to scalarize the PHI.
227 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000228 Instruction *scalarPHI = scalarizePHI(EI, PN);
229 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000230 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000231 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000232 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000233
Chris Lattnerec97a902010-01-05 05:36:20 +0000234 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
235 // Push extractelement into predecessor operation if legal and
236 // profitable to do so
237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
238 if (I->hasOneUse() &&
239 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
240 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000241 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
242 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000243 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000244 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
245 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000246 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
247 }
248 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
249 // Extracting the inserted element?
250 if (IE->getOperand(2) == EI.getOperand(1))
251 return ReplaceInstUsesWith(EI, IE->getOperand(1));
252 // If the inserted and extracted elements are constants, they must not
253 // be the same value, extract from the pre-inserted value instead.
254 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
255 Worklist.AddValue(EI.getOperand(0));
256 EI.setOperand(0, IE->getOperand(0));
257 return &EI;
258 }
259 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
260 // If this is extracting an element from a shufflevector, figure out where
261 // it came from and extract from the appropriate input element instead.
262 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000263 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000264 Value *Src;
265 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000266 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000267
Bob Wilson11ee4562010-10-29 22:03:05 +0000268 if (SrcIdx < 0)
269 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
270 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000271 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000272 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000273 SrcIdx -= LHSWidth;
274 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000275 }
Chris Lattner229907c2011-07-18 04:54:35 +0000276 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000277 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000278 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000279 SrcIdx, false));
280 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000281 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
282 // Canonicalize extractelement(cast) -> cast(extractelement)
283 // bitcasts can change the number of vector elements and they cost nothing
Anat Shemer55703182013-04-18 19:56:44 +0000284 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Anat Shemer10260a72013-04-22 20:51:10 +0000285 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
286 EI.getIndexOperand());
287 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000288 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
289 }
Matt Arsenault243140f2013-11-04 20:36:06 +0000290 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
291 if (SI->hasOneUse()) {
292 // TODO: For a select on vectors, it might be useful to do this if it
293 // has multiple extractelement uses. For vector select, that seems to
294 // fight the vectorizer.
295
296 // If we are extracting an element from a vector select or a select on
297 // vectors, a select on the scalars extracted from the vector arguments.
298 Value *TrueVal = SI->getTrueValue();
299 Value *FalseVal = SI->getFalseValue();
300
301 Value *Cond = SI->getCondition();
302 if (Cond->getType()->isVectorTy()) {
303 Cond = Builder->CreateExtractElement(Cond,
304 EI.getIndexOperand(),
305 Cond->getName() + ".elt");
306 }
307
308 Value *V1Elem
309 = Builder->CreateExtractElement(TrueVal,
310 EI.getIndexOperand(),
311 TrueVal->getName() + ".elt");
312
313 Value *V2Elem
314 = Builder->CreateExtractElement(FalseVal,
315 EI.getIndexOperand(),
316 FalseVal->getName() + ".elt");
317 return SelectInst::Create(Cond,
318 V1Elem,
319 V2Elem,
320 SI->getName() + ".elt");
321 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000322 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000323 }
Craig Topperf40110f2014-04-25 05:29:35 +0000324 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000325}
326
327/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000328/// elements from either LHS or RHS, return the shuffle mask and true.
Chris Lattnerec97a902010-01-05 05:36:20 +0000329/// Otherwise, return false.
330static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000331 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000332 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000333 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000334 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000335
Chris Lattnerec97a902010-01-05 05:36:20 +0000336 if (isa<UndefValue>(V)) {
337 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
338 return true;
339 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000340
Chris Lattnerec97a902010-01-05 05:36:20 +0000341 if (V == LHS) {
342 for (unsigned i = 0; i != NumElts; ++i)
343 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
344 return true;
345 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000346
Chris Lattnerec97a902010-01-05 05:36:20 +0000347 if (V == RHS) {
348 for (unsigned i = 0; i != NumElts; ++i)
349 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
350 i+NumElts));
351 return true;
352 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000353
Chris Lattnerec97a902010-01-05 05:36:20 +0000354 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
355 // If this is an insert of an extract from some other vector, include it.
356 Value *VecOp = IEI->getOperand(0);
357 Value *ScalarOp = IEI->getOperand(1);
358 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000359
Chris Lattnerec97a902010-01-05 05:36:20 +0000360 if (!isa<ConstantInt>(IdxOp))
361 return false;
362 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000363
Chris Lattnerec97a902010-01-05 05:36:20 +0000364 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000365 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000366 // transitively ok.
367 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
368 // If so, update the mask to reflect the inserted undef.
369 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
370 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000371 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000372 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000373 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000374 unsigned ExtractedIdx =
375 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000376 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000377
Chris Lattnerec97a902010-01-05 05:36:20 +0000378 // This must be extracting from either LHS or RHS.
379 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000380 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000381 // transitively ok.
382 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
383 // If so, update the mask to reflect the inserted value.
384 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000385 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000386 ConstantInt::get(Type::getInt32Ty(V->getContext()),
387 ExtractedIdx);
388 } else {
389 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000390 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000391 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000392 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000393 }
394 return true;
395 }
396 }
397 }
398 }
399 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000400
Chris Lattnerec97a902010-01-05 05:36:20 +0000401 return false;
402}
403
Tim Northoverfad27612014-03-07 10:24:44 +0000404
405/// We are building a shuffle to create V, which is a sequence of insertelement,
406/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000407/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000408/// left and right vectors of the proposed shuffle (or 0), and set the Mask
409/// parameter as required.
410///
411/// Note: we intentionally don't try to fold earlier shuffles since they have
412/// often been chosen carefully to be efficiently implementable on the target.
413typedef std::pair<Value *, Value *> ShuffleOps;
414
415static ShuffleOps CollectShuffleElements(Value *V,
416 SmallVectorImpl<Constant *> &Mask,
417 Value *PermittedRHS) {
418 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Chris Lattnerec97a902010-01-05 05:36:20 +0000419 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000420
Chris Lattnerec97a902010-01-05 05:36:20 +0000421 if (isa<UndefValue>(V)) {
422 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000423 return std::make_pair(
424 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000425 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000426
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000427 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000428 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000429 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000430 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000431
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000432 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000433 // If this is an insert of an extract from some other vector, include it.
434 Value *VecOp = IEI->getOperand(0);
435 Value *ScalarOp = IEI->getOperand(1);
436 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000437
Chris Lattnerec97a902010-01-05 05:36:20 +0000438 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000439 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000440 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000441 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000442 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000443
Chris Lattnerec97a902010-01-05 05:36:20 +0000444 // Either the extracted from or inserted into vector must be RHSVec,
445 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000446 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000447 Value *RHS = EI->getOperand(0);
448 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
Craig Toppere73658d2014-04-28 04:05:08 +0000449 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000450
451 if (LR.first->getType() != RHS->getType()) {
452 // We tried our best, but we can't find anything compatible with RHS
453 // further up the chain. Return a trivial shuffle.
454 for (unsigned i = 0; i < NumElts; ++i)
455 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
456 return std::make_pair(V, nullptr);
457 }
458
459 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000460 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000461 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000462 NumLHSElts+ExtractedIdx);
463 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000464 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000465
Tim Northoverfad27612014-03-07 10:24:44 +0000466 if (VecOp == PermittedRHS) {
467 // We've gone as far as we can: anything on the other side of the
468 // extractelement will already have been converted into a shuffle.
469 unsigned NumLHSElts =
470 EI->getOperand(0)->getType()->getVectorNumElements();
471 for (unsigned i = 0; i != NumElts; ++i)
472 Mask.push_back(ConstantInt::get(
473 Type::getInt32Ty(V->getContext()),
474 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
475 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000476 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000477
Chris Lattnerec97a902010-01-05 05:36:20 +0000478 // If this insertelement is a chain that comes from exactly these two
479 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000480 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
481 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
482 Mask))
483 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000484 }
485 }
486 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000487
Chris Lattnerec97a902010-01-05 05:36:20 +0000488 // Otherwise, can't do anything fancy. Return an identity vector.
489 for (unsigned i = 0; i != NumElts; ++i)
490 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000491 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000492}
493
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000494/// Try to find redundant insertvalue instructions, like the following ones:
495/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
496/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
497/// Here the second instruction inserts values at the same indices, as the
498/// first one, making the first one redundant.
499/// It should be transformed to:
500/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
501Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
502 bool IsRedundant = false;
503 ArrayRef<unsigned int> FirstIndices = I.getIndices();
504
505 // If there is a chain of insertvalue instructions (each of them except the
506 // last one has only one use and it's another insertvalue insn from this
507 // chain), check if any of the 'children' uses the same indices as the first
508 // instruction. In this case, the first one is redundant.
509 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000510 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000511 while (V->hasOneUse() && Depth < 10) {
512 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000513 auto UserInsInst = dyn_cast<InsertValueInst>(U);
514 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000515 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000516 if (UserInsInst->getIndices() == FirstIndices) {
517 IsRedundant = true;
518 break;
519 }
520 V = UserInsInst;
521 Depth++;
522 }
523
524 if (IsRedundant)
525 return ReplaceInstUsesWith(I, I.getOperand(0));
526 return nullptr;
527}
528
Chris Lattnerec97a902010-01-05 05:36:20 +0000529Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
530 Value *VecOp = IE.getOperand(0);
531 Value *ScalarOp = IE.getOperand(1);
532 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000533
Chris Lattnerec97a902010-01-05 05:36:20 +0000534 // Inserting an undef or into an undefined place, remove this.
535 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
536 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000537
538 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000539 // indexes are constant, try to turn this into a shufflevector operation.
540 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000541 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
542 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
543 unsigned NumExtractVectorElts =
544 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000545 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000546 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000547 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000548
Tim Northoverfad27612014-03-07 10:24:44 +0000549 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Chris Lattnerec97a902010-01-05 05:36:20 +0000550 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000551
Tim Northoverfad27612014-03-07 10:24:44 +0000552 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Chris Lattnerec97a902010-01-05 05:36:20 +0000553 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000554
Chris Lattnerec97a902010-01-05 05:36:20 +0000555 // If we are extracting a value from a vector, then inserting it right
556 // back into the same place, just use the input vector.
557 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000558 return ReplaceInstUsesWith(IE, VecOp);
559
Chris Lattnerec97a902010-01-05 05:36:20 +0000560 // If this insertelement isn't used by some other insertelement, turn it
561 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000562 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000563 SmallVector<Constant*, 16> Mask;
Craig Topperf40110f2014-04-25 05:29:35 +0000564 ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
Tim Northoverfad27612014-03-07 10:24:44 +0000565
566 // The proposed shuffle may be trivial, in which case we shouldn't
567 // perform the combine.
568 if (LR.first != &IE && LR.second != &IE) {
569 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000570 if (LR.second == nullptr)
571 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000572 return new ShuffleVectorInst(LR.first, LR.second,
573 ConstantVector::get(Mask));
574 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000575 }
576 }
577 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000578
Chris Lattnerec97a902010-01-05 05:36:20 +0000579 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
580 APInt UndefElts(VWidth, 0);
581 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000582 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
583 if (V != &IE)
584 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000585 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000586 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000587
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000589}
590
Nick Lewyckya2b77202013-05-31 00:59:42 +0000591/// Return true if we can evaluate the specified expression tree if the vector
592/// elements were shuffled in a different order.
593static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000594 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000595 // We can always reorder the elements of a constant.
596 if (isa<Constant>(V))
597 return true;
598
599 // We won't reorder vector arguments. No IPO here.
600 Instruction *I = dyn_cast<Instruction>(V);
601 if (!I) return false;
602
603 // Two users may expect different orders of the elements. Don't try it.
604 if (!I->hasOneUse())
605 return false;
606
607 if (Depth == 0) return false;
608
609 switch (I->getOpcode()) {
610 case Instruction::Add:
611 case Instruction::FAdd:
612 case Instruction::Sub:
613 case Instruction::FSub:
614 case Instruction::Mul:
615 case Instruction::FMul:
616 case Instruction::UDiv:
617 case Instruction::SDiv:
618 case Instruction::FDiv:
619 case Instruction::URem:
620 case Instruction::SRem:
621 case Instruction::FRem:
622 case Instruction::Shl:
623 case Instruction::LShr:
624 case Instruction::AShr:
625 case Instruction::And:
626 case Instruction::Or:
627 case Instruction::Xor:
628 case Instruction::ICmp:
629 case Instruction::FCmp:
630 case Instruction::Trunc:
631 case Instruction::ZExt:
632 case Instruction::SExt:
633 case Instruction::FPToUI:
634 case Instruction::FPToSI:
635 case Instruction::UIToFP:
636 case Instruction::SIToFP:
637 case Instruction::FPTrunc:
638 case Instruction::FPExt:
639 case Instruction::GetElementPtr: {
640 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
641 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
642 return false;
643 }
644 return true;
645 }
646 case Instruction::InsertElement: {
647 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
648 if (!CI) return false;
649 int ElementNumber = CI->getLimitedValue();
650
651 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
652 // can't put an element into multiple indices.
653 bool SeenOnce = false;
654 for (int i = 0, e = Mask.size(); i != e; ++i) {
655 if (Mask[i] == ElementNumber) {
656 if (SeenOnce)
657 return false;
658 SeenOnce = true;
659 }
660 }
661 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
662 }
663 }
664 return false;
665}
666
667/// Rebuild a new instruction just like 'I' but with the new operands given.
668/// In the event of type mismatch, the type of the operands is correct.
669static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
670 // We don't want to use the IRBuilder here because we want the replacement
671 // instructions to appear next to 'I', not the builder's insertion point.
672 switch (I->getOpcode()) {
673 case Instruction::Add:
674 case Instruction::FAdd:
675 case Instruction::Sub:
676 case Instruction::FSub:
677 case Instruction::Mul:
678 case Instruction::FMul:
679 case Instruction::UDiv:
680 case Instruction::SDiv:
681 case Instruction::FDiv:
682 case Instruction::URem:
683 case Instruction::SRem:
684 case Instruction::FRem:
685 case Instruction::Shl:
686 case Instruction::LShr:
687 case Instruction::AShr:
688 case Instruction::And:
689 case Instruction::Or:
690 case Instruction::Xor: {
691 BinaryOperator *BO = cast<BinaryOperator>(I);
692 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
693 BinaryOperator *New =
694 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
695 NewOps[0], NewOps[1], "", BO);
696 if (isa<OverflowingBinaryOperator>(BO)) {
697 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
698 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
699 }
700 if (isa<PossiblyExactOperator>(BO)) {
701 New->setIsExact(BO->isExact());
702 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000703 if (isa<FPMathOperator>(BO))
704 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000705 return New;
706 }
707 case Instruction::ICmp:
708 assert(NewOps.size() == 2 && "icmp with #ops != 2");
709 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
710 NewOps[0], NewOps[1]);
711 case Instruction::FCmp:
712 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
713 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
714 NewOps[0], NewOps[1]);
715 case Instruction::Trunc:
716 case Instruction::ZExt:
717 case Instruction::SExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::UIToFP:
721 case Instruction::SIToFP:
722 case Instruction::FPTrunc:
723 case Instruction::FPExt: {
724 // It's possible that the mask has a different number of elements from
725 // the original cast. We recompute the destination type to match the mask.
726 Type *DestTy =
727 VectorType::get(I->getType()->getScalarType(),
728 NewOps[0]->getType()->getVectorNumElements());
729 assert(NewOps.size() == 1 && "cast with #ops != 1");
730 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
731 "", I);
732 }
733 case Instruction::GetElementPtr: {
734 Value *Ptr = NewOps[0];
735 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +0000736 GetElementPtrInst *GEP = GetElementPtrInst::Create(
737 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000738 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
739 return GEP;
740 }
741 }
742 llvm_unreachable("failed to rebuild vector instructions");
743}
744
745Value *
746InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
747 // Mask.size() does not need to be equal to the number of vector elements.
748
749 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
750 if (isa<UndefValue>(V)) {
751 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
752 Mask.size()));
753 }
754 if (isa<ConstantAggregateZero>(V)) {
755 return ConstantAggregateZero::get(
756 VectorType::get(V->getType()->getScalarType(),
757 Mask.size()));
758 }
759 if (Constant *C = dyn_cast<Constant>(V)) {
760 SmallVector<Constant *, 16> MaskValues;
761 for (int i = 0, e = Mask.size(); i != e; ++i) {
762 if (Mask[i] == -1)
763 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
764 else
765 MaskValues.push_back(Builder->getInt32(Mask[i]));
766 }
767 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
768 ConstantVector::get(MaskValues));
769 }
770
771 Instruction *I = cast<Instruction>(V);
772 switch (I->getOpcode()) {
773 case Instruction::Add:
774 case Instruction::FAdd:
775 case Instruction::Sub:
776 case Instruction::FSub:
777 case Instruction::Mul:
778 case Instruction::FMul:
779 case Instruction::UDiv:
780 case Instruction::SDiv:
781 case Instruction::FDiv:
782 case Instruction::URem:
783 case Instruction::SRem:
784 case Instruction::FRem:
785 case Instruction::Shl:
786 case Instruction::LShr:
787 case Instruction::AShr:
788 case Instruction::And:
789 case Instruction::Or:
790 case Instruction::Xor:
791 case Instruction::ICmp:
792 case Instruction::FCmp:
793 case Instruction::Trunc:
794 case Instruction::ZExt:
795 case Instruction::SExt:
796 case Instruction::FPToUI:
797 case Instruction::FPToSI:
798 case Instruction::UIToFP:
799 case Instruction::SIToFP:
800 case Instruction::FPTrunc:
801 case Instruction::FPExt:
802 case Instruction::Select:
803 case Instruction::GetElementPtr: {
804 SmallVector<Value*, 8> NewOps;
805 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
806 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
807 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
808 NewOps.push_back(V);
809 NeedsRebuild |= (V != I->getOperand(i));
810 }
811 if (NeedsRebuild) {
812 return BuildNew(I, NewOps);
813 }
814 return I;
815 }
816 case Instruction::InsertElement: {
817 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +0000818
819 // The insertelement was inserting at Element. Figure out which element
820 // that becomes after shuffling. The answer is guaranteed to be unique
821 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000822 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000823 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000824 for (int e = Mask.size(); Index != e; ++Index) {
825 if (Mask[Index] == Element) {
826 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000827 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000828 }
829 }
Nick Lewyckya2b77202013-05-31 00:59:42 +0000830
Hao Liu26abebb2014-01-08 03:06:15 +0000831 // If element is not in Mask, no need to handle the operand 1 (element to
832 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000833 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +0000834 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +0000835
Nick Lewyckya2b77202013-05-31 00:59:42 +0000836 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
837 return InsertElementInst::Create(V, I->getOperand(1),
838 Builder->getInt32(Index), "", I);
839 }
840 }
841 llvm_unreachable("failed to reorder elements of vector instruction!");
842}
Chris Lattnerec97a902010-01-05 05:36:20 +0000843
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000844static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
845 bool &isLHSID, bool &isRHSID) {
846 isLHSID = isRHSID = true;
847
848 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
849 if (Mask[i] < 0) continue; // Ignore undef values.
850 // Is this an identity shuffle of the LHS value?
851 isLHSID &= (Mask[i] == (int)i);
852
853 // Is this an identity shuffle of the RHS value?
854 isRHSID &= (Mask[i]-e == i);
855 }
856}
857
JF Bastiend52c9902015-02-25 22:30:51 +0000858// Returns true if the shuffle is extracting a contiguous range of values from
859// LHS, for example:
860// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
861// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
862// Shuffles to: |EE|FF|GG|HH|
863// +--+--+--+--+
864static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
865 SmallVector<int, 16> &Mask) {
866 unsigned LHSElems =
867 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
868 unsigned MaskElems = Mask.size();
869 unsigned BegIdx = Mask.front();
870 unsigned EndIdx = Mask.back();
871 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
872 return false;
873 for (unsigned I = 0; I != MaskElems; ++I)
874 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
875 return false;
876 return true;
877}
878
Chris Lattnerec97a902010-01-05 05:36:20 +0000879Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
880 Value *LHS = SVI.getOperand(0);
881 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000882 SmallVector<int, 16> Mask = SVI.getShuffleMask();
JF Bastiend52c9902015-02-25 22:30:51 +0000883 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000884
Chris Lattnerec97a902010-01-05 05:36:20 +0000885 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000886
Chris Lattnerec97a902010-01-05 05:36:20 +0000887 // Undefined shuffle mask -> undefined value.
888 if (isa<UndefValue>(SVI.getOperand(2)))
889 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000890
Eric Christopher51edc7b2010-08-17 22:55:27 +0000891 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000892
Chris Lattnerec97a902010-01-05 05:36:20 +0000893 APInt UndefElts(VWidth, 0);
894 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000895 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
896 if (V != &SVI)
897 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000898 LHS = SVI.getOperand(0);
899 RHS = SVI.getOperand(1);
900 MadeChange = true;
901 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000902
Eli Friedmance818272011-10-21 19:06:29 +0000903 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
904
Chris Lattnerec97a902010-01-05 05:36:20 +0000905 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
906 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
907 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000908 if (isa<UndefValue>(LHS) && LHS == RHS) {
909 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +0000910 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +0000911 ? LHS : UndefValue::get(SVI.getType());
Nick Lewyckya2b77202013-05-31 00:59:42 +0000912 return ReplaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000913 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000914
Chris Lattnerec97a902010-01-05 05:36:20 +0000915 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +0000916 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000917 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000918 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +0000919 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000920 continue;
921 }
922
923 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
924 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
925 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +0000926 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000927 } else {
928 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +0000929 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +0000930 }
931 }
932 SVI.setOperand(0, SVI.getOperand(1));
933 SVI.setOperand(1, UndefValue::get(RHS->getType()));
934 SVI.setOperand(2, ConstantVector::get(Elts));
935 LHS = SVI.getOperand(0);
936 RHS = SVI.getOperand(1);
937 MadeChange = true;
938 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000939
Eli Friedmance818272011-10-21 19:06:29 +0000940 if (VWidth == LHSWidth) {
941 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000942 bool isLHSID, isRHSID;
943 RecognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +0000944
945 // Eliminate identity shuffles.
946 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
947 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000948 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000949
Nick Lewycky688d6682013-06-03 23:15:20 +0000950 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000951 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
952 return ReplaceInstUsesWith(SVI, V);
953 }
954
JF Bastiend52c9902015-02-25 22:30:51 +0000955 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
956 // a non-vector type. We can instead bitcast the original vector followed by
957 // an extract of the desired element:
958 //
959 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
960 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
961 // %1 = bitcast <4 x i8> %sroa to i32
962 // Becomes:
963 // %bc = bitcast <16 x i8> %in to <4 x i32>
964 // %ext = extractelement <4 x i32> %bc, i32 0
965 //
966 // If the shuffle is extracting a contiguous range of values from the input
967 // vector then each use which is a bitcast of the extracted size can be
968 // replaced. This will work if the vector types are compatible, and the begin
969 // index is aligned to a value in the casted vector type. If the begin index
970 // isn't aligned then we can shuffle the original vector (keeping the same
971 // vector type) before extracting.
972 //
973 // This code will bail out if the target type is fundamentally incompatible
974 // with vectors of the source type.
975 //
976 // Example of <16 x i8>, target type i32:
977 // Index range [4,8): v-----------v Will work.
978 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
979 // <16 x i8>: | | | | | | | | | | | | | | | | |
980 // <4 x i32>: | | | | |
981 // +-----------+-----------+-----------+-----------+
982 // Index range [6,10): ^-----------^ Needs an extra shuffle.
983 // Target type i40: ^--------------^ Won't work, bail.
984 if (isShuffleExtractingFromLHS(SVI, Mask)) {
985 Value *V = LHS;
986 unsigned MaskElems = Mask.size();
987 unsigned BegIdx = Mask.front();
988 VectorType *SrcTy = cast<VectorType>(V->getType());
989 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +0000990 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +0000991 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
992 unsigned SrcNumElems = SrcTy->getNumElements();
993 SmallVector<BitCastInst *, 8> BCs;
994 DenseMap<Type *, Value *> NewBCs;
995 for (User *U : SVI.users())
996 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
997 if (!BC->use_empty())
998 // Only visit bitcasts that weren't previously handled.
999 BCs.push_back(BC);
1000 for (BitCastInst *BC : BCs) {
1001 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001002 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00001003 if (!TgtElemBitWidth)
1004 continue;
1005 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1006 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1007 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1008 if (!VecBitWidthsEqual)
1009 continue;
1010 if (!VectorType::isValidElementType(TgtTy))
1011 continue;
1012 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1013 if (!BegIsAligned) {
1014 // Shuffle the input so [0,NumElements) contains the output, and
1015 // [NumElems,SrcNumElems) is undef.
1016 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1017 UndefValue::get(Int32Ty));
1018 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1019 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1020 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1021 ConstantVector::get(ShuffleMask),
1022 SVI.getName() + ".extract");
1023 BegIdx = 0;
1024 }
1025 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1026 assert(SrcElemsPerTgtElem);
1027 BegIdx /= SrcElemsPerTgtElem;
1028 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1029 auto *NewBC =
1030 BCAlreadyExists
1031 ? NewBCs[CastSrcTy]
1032 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1033 if (!BCAlreadyExists)
1034 NewBCs[CastSrcTy] = NewBC;
1035 auto *Ext = Builder->CreateExtractElement(
1036 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1037 // The shufflevector isn't being replaced: the bitcast that used it
1038 // is. InstCombine will visit the newly-created instructions.
1039 ReplaceInstUsesWith(*BC, Ext);
1040 MadeChange = true;
1041 }
1042 }
1043
Eric Christopher51edc7b2010-08-17 22:55:27 +00001044 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00001045 // one without producing an unusual shuffle.
1046 // Cases that might be simplified:
1047 // 1.
1048 // x1=shuffle(v1,v2,mask1)
1049 // x=shuffle(x1,undef,mask)
1050 // ==>
1051 // x=shuffle(v1,undef,newMask)
1052 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1053 // 2.
1054 // x1=shuffle(v1,undef,mask1)
1055 // x=shuffle(x1,x2,mask)
1056 // where v1.size() == mask1.size()
1057 // ==>
1058 // x=shuffle(v1,x2,newMask)
1059 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1060 // 3.
1061 // x2=shuffle(v2,undef,mask2)
1062 // x=shuffle(x1,x2,mask)
1063 // where v2.size() == mask2.size()
1064 // ==>
1065 // x=shuffle(x1,v2,newMask)
1066 // newMask[i] = (mask[i] < x1.size())
1067 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1068 // 4.
1069 // x1=shuffle(v1,undef,mask1)
1070 // x2=shuffle(v2,undef,mask2)
1071 // x=shuffle(x1,x2,mask)
1072 // where v1.size() == v2.size()
1073 // ==>
1074 // x=shuffle(v1,v2,newMask)
1075 // newMask[i] = (mask[i] < x1.size())
1076 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1077 //
1078 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001079 // we are absolutely afraid of producing a shuffle mask not in the input
1080 // program, because the code gen may not be smart enough to turn a merged
1081 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001082 // we only merge two shuffles if the result is either a splat or one of the
1083 // input shuffle masks. In this case, merging the shuffles just removes
1084 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001085 // turning: (splat(splat)) -> splat, or
1086 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1087 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1088 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1089 if (LHSShuffle)
1090 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001091 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001092 if (RHSShuffle)
1093 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001094 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001095 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001096 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001097
Craig Topperf40110f2014-04-25 05:29:35 +00001098 Value* LHSOp0 = nullptr;
1099 Value* LHSOp1 = nullptr;
1100 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001101 unsigned LHSOp0Width = 0;
1102 unsigned RHSOp0Width = 0;
1103 if (LHSShuffle) {
1104 LHSOp0 = LHSShuffle->getOperand(0);
1105 LHSOp1 = LHSShuffle->getOperand(1);
1106 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1107 }
1108 if (RHSShuffle) {
1109 RHSOp0 = RHSShuffle->getOperand(0);
1110 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1111 }
1112 Value* newLHS = LHS;
1113 Value* newRHS = RHS;
1114 if (LHSShuffle) {
1115 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001116 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001117 newLHS = LHSOp0;
1118 newRHS = LHSOp1;
1119 }
1120 // case 2 or 4
1121 else if (LHSOp0Width == LHSWidth) {
1122 newLHS = LHSOp0;
1123 }
1124 }
1125 // case 3 or 4
1126 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1127 newRHS = RHSOp0;
1128 }
1129 // case 4
1130 if (LHSOp0 == RHSOp0) {
1131 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001132 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001133 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001134
Eli Friedmance818272011-10-21 19:06:29 +00001135 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001136 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001137
Eli Friedmance818272011-10-21 19:06:29 +00001138 SmallVector<int, 16> LHSMask;
1139 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001140 if (newLHS != LHS)
1141 LHSMask = LHSShuffle->getShuffleMask();
1142 if (RHSShuffle && newRHS != RHS)
1143 RHSMask = RHSShuffle->getShuffleMask();
1144
Eli Friedmance818272011-10-21 19:06:29 +00001145 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1146 SmallVector<int, 16> newMask;
1147 bool isSplat = true;
1148 int SplatElt = -1;
1149 // Create a new mask for the new ShuffleVectorInst so that the new
1150 // ShuffleVectorInst is equivalent to the original one.
1151 for (unsigned i = 0; i < VWidth; ++i) {
1152 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001153 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001154 // This element is an undef value.
1155 eltMask = -1;
1156 } else if (Mask[i] < (int)LHSWidth) {
1157 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001158 //
Eli Friedmance818272011-10-21 19:06:29 +00001159 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1160 // new mask value for the element.
1161 if (newLHS != LHS) {
1162 eltMask = LHSMask[Mask[i]];
1163 // If the value selected is an undef value, explicitly specify it
1164 // with a -1 mask value.
1165 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1166 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001167 } else
Eli Friedmance818272011-10-21 19:06:29 +00001168 eltMask = Mask[i];
1169 } else {
1170 // This element is from right hand side vector operand
1171 //
1172 // If the value selected is an undef value, explicitly specify it
1173 // with a -1 mask value. (case 1)
1174 if (isa<UndefValue>(RHS))
1175 eltMask = -1;
1176 // If RHS is going to be replaced (case 3 or 4), calculate the
1177 // new mask value for the element.
1178 else if (newRHS != RHS) {
1179 eltMask = RHSMask[Mask[i]-LHSWidth];
1180 // If the value selected is an undef value, explicitly specify it
1181 // with a -1 mask value.
1182 if (eltMask >= (int)RHSOp0Width) {
1183 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1184 && "should have been check above");
1185 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001186 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001187 } else
Eli Friedmance818272011-10-21 19:06:29 +00001188 eltMask = Mask[i]-LHSWidth;
1189
1190 // If LHS's width is changed, shift the mask value accordingly.
1191 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001192 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1193 // If newRHS == newLHS, we want to remap any references from newRHS to
1194 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001195 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001196 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001197 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001198 }
Eli Friedmance818272011-10-21 19:06:29 +00001199
1200 // Check if this could still be a splat.
1201 if (eltMask >= 0) {
1202 if (SplatElt >= 0 && SplatElt != eltMask)
1203 isSplat = false;
1204 SplatElt = eltMask;
1205 }
1206
1207 newMask.push_back(eltMask);
1208 }
1209
1210 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001211 // or is a splat, do the replacement.
1212 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001213 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001214 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1215 if (newMask[i] < 0) {
1216 Elts.push_back(UndefValue::get(Int32Ty));
1217 } else {
1218 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1219 }
1220 }
Craig Topperf40110f2014-04-25 05:29:35 +00001221 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001222 newRHS = UndefValue::get(newLHS->getType());
1223 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001224 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001225
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001226 // If the result mask is an identity, replace uses of this instruction with
1227 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001228 bool isLHSID, isRHSID;
1229 RecognizeIdentityMask(newMask, isLHSID, isRHSID);
1230 if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1231 if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001232
Craig Topperf40110f2014-04-25 05:29:35 +00001233 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001234}