blob: 050cb48d37927a345c99674d096f80d7f23b7d5a [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"
16using namespace llvm;
17
18/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
Chris Lattnera0d01ff2012-01-24 14:31:22 +000019/// is to leave as a vector operation. isConstant indicates whether we're
20/// extracting one known element. If false we're extracting a variable index.
Chris Lattnerec97a902010-01-05 05:36:20 +000021static bool CheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000022 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000023 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000024
25 // If all elts are the same, we can extract it and use any of the values.
26 Constant *Op0 = C->getAggregateElement(0U);
27 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; ++i)
28 if (C->getAggregateElement(i) != Op0)
Chris Lattnerec97a902010-01-05 05:36:20 +000029 return false;
30 return true;
31 }
32 Instruction *I = dyn_cast<Instruction>(V);
33 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000034
Chris Lattnerec97a902010-01-05 05:36:20 +000035 // Insert element gets simplified to the inserted element or is deleted if
36 // this is constant idx extract element and its a constant idx insertelt.
37 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
38 isa<ConstantInt>(I->getOperand(2)))
39 return true;
40 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
41 return true;
42 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
43 if (BO->hasOneUse() &&
44 (CheapToScalarize(BO->getOperand(0), isConstant) ||
45 CheapToScalarize(BO->getOperand(1), isConstant)))
46 return true;
47 if (CmpInst *CI = dyn_cast<CmpInst>(I))
48 if (CI->hasOneUse() &&
49 (CheapToScalarize(CI->getOperand(0), isConstant) ||
50 CheapToScalarize(CI->getOperand(1), isConstant)))
51 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000052
Chris Lattnerec97a902010-01-05 05:36:20 +000053 return false;
54}
55
Chris Lattnerec97a902010-01-05 05:36:20 +000056/// FindScalarElement - Given a vector and an element number, see if the scalar
57/// value is already around as a register, for example if it were inserted then
58/// extracted from the vector.
59static Value *FindScalarElement(Value *V, unsigned EltNo) {
Duncan Sands19d0b472010-02-16 11:11:14 +000060 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
Chris Lattner8326bd82012-01-26 00:42:34 +000061 VectorType *VTy = cast<VectorType>(V->getType());
62 unsigned Width = VTy->getNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +000063 if (EltNo >= Width) // Out of range access.
Chris Lattner8326bd82012-01-26 00:42:34 +000064 return UndefValue::get(VTy->getElementType());
Bob Wilson8ecf98b2010-10-29 22:20:43 +000065
Chris Lattner8326bd82012-01-26 00:42:34 +000066 if (Constant *C = dyn_cast<Constant>(V))
67 return C->getAggregateElement(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000068
Chris Lattner841af4f2010-01-05 05:42:08 +000069 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000070 // If this is an insert to a variable element, we don't know what it is.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000071 if (!isa<ConstantInt>(III->getOperand(2)))
Chris Lattnerec97a902010-01-05 05:36:20 +000072 return 0;
73 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +000074
Chris Lattnerec97a902010-01-05 05:36:20 +000075 // If this is an insert to the element we are looking for, return the
76 // inserted value.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000077 if (EltNo == IIElt)
Chris Lattnerec97a902010-01-05 05:36:20 +000078 return III->getOperand(1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000079
Chris Lattnerec97a902010-01-05 05:36:20 +000080 // Otherwise, the insertelement doesn't modify the value, recurse on its
81 // vector input.
82 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner841af4f2010-01-05 05:42:08 +000083 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000084
Chris Lattner841af4f2010-01-05 05:42:08 +000085 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner8326bd82012-01-26 00:42:34 +000086 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
Eli Friedman303c81c2011-10-21 19:11:34 +000087 int InEl = SVI->getMaskValue(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000088 if (InEl < 0)
Chris Lattner8326bd82012-01-26 00:42:34 +000089 return UndefValue::get(VTy->getElementType());
Bob Wilson11ee4562010-10-29 22:03:05 +000090 if (InEl < (int)LHSWidth)
91 return FindScalarElement(SVI->getOperand(0), InEl);
92 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattnerec97a902010-01-05 05:36:20 +000093 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000094
Chris Lattnerec97a902010-01-05 05:36:20 +000095 // Otherwise, we don't know.
96 return 0;
97}
98
99Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000100 // If vector val is constant with all elements the same, replace EI with
101 // that element. We handle a known element # below.
102 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
103 if (CheapToScalarize(C, false))
104 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000105
Chris Lattnerec97a902010-01-05 05:36:20 +0000106 // If extracting a specified index from the vector, see if we can recursively
107 // find a previously computed scalar that was inserted into the vector.
108 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
109 unsigned IndexVal = IdxC->getZExtValue();
110 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000111
Chris Lattnerec97a902010-01-05 05:36:20 +0000112 // If this is extracting an invalid index, turn this into undef, to avoid
113 // crashing the code below.
114 if (IndexVal >= VectorWidth)
115 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000116
Chris Lattnerec97a902010-01-05 05:36:20 +0000117 // This instruction only demands the single element from the input vector.
118 // If the input vector has a single use, simplify it based on this use
119 // property.
120 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
121 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000122 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000123 DemandedMask.setBit(IndexVal);
Chris Lattnerec97a902010-01-05 05:36:20 +0000124 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
125 DemandedMask, UndefElts)) {
126 EI.setOperand(0, V);
127 return &EI;
128 }
129 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000130
Chris Lattnerec97a902010-01-05 05:36:20 +0000131 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
132 return ReplaceInstUsesWith(EI, Elt);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000133
Chris Lattnerec97a902010-01-05 05:36:20 +0000134 // If the this extractelement is directly using a bitcast from a vector of
135 // the same number of elements, see if we can find the source element from
136 // it. In this case, we will end up needing to bitcast the scalars.
137 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000138 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000139 if (VT->getNumElements() == VectorWidth)
140 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
141 return new BitCastInst(Elt, EI.getType());
142 }
143 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000144
Chris Lattnerec97a902010-01-05 05:36:20 +0000145 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
146 // Push extractelement into predecessor operation if legal and
147 // profitable to do so
148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
149 if (I->hasOneUse() &&
150 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
151 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000152 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
153 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000154 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000155 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
156 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000157 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
158 }
159 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
160 // Extracting the inserted element?
161 if (IE->getOperand(2) == EI.getOperand(1))
162 return ReplaceInstUsesWith(EI, IE->getOperand(1));
163 // If the inserted and extracted elements are constants, they must not
164 // be the same value, extract from the pre-inserted value instead.
165 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
166 Worklist.AddValue(EI.getOperand(0));
167 EI.setOperand(0, IE->getOperand(0));
168 return &EI;
169 }
170 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
171 // If this is extracting an element from a shufflevector, figure out where
172 // it came from and extract from the appropriate input element instead.
173 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000174 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000175 Value *Src;
176 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000177 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000178
Bob Wilson11ee4562010-10-29 22:03:05 +0000179 if (SrcIdx < 0)
180 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
181 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000182 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000183 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000184 SrcIdx -= LHSWidth;
185 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000186 }
Chris Lattner229907c2011-07-18 04:54:35 +0000187 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000188 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000189 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000190 SrcIdx, false));
191 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000192 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
193 // Canonicalize extractelement(cast) -> cast(extractelement)
194 // bitcasts can change the number of vector elements and they cost nothing
195 if (CI->hasOneUse() && EI.hasOneUse() &&
196 (CI->getOpcode() != Instruction::BitCast)) {
197 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
198 EI.getIndexOperand());
199 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
200 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000201 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000202 }
203 return 0;
204}
205
206/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000207/// elements from either LHS or RHS, return the shuffle mask and true.
Chris Lattnerec97a902010-01-05 05:36:20 +0000208/// Otherwise, return false.
209static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
210 std::vector<Constant*> &Mask) {
211 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
212 "Invalid CollectSingleShuffleElements");
213 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000214
Chris Lattnerec97a902010-01-05 05:36:20 +0000215 if (isa<UndefValue>(V)) {
216 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
217 return true;
218 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000219
Chris Lattnerec97a902010-01-05 05:36:20 +0000220 if (V == LHS) {
221 for (unsigned i = 0; i != NumElts; ++i)
222 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
223 return true;
224 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000225
Chris Lattnerec97a902010-01-05 05:36:20 +0000226 if (V == RHS) {
227 for (unsigned i = 0; i != NumElts; ++i)
228 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
229 i+NumElts));
230 return true;
231 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000232
Chris Lattnerec97a902010-01-05 05:36:20 +0000233 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
234 // If this is an insert of an extract from some other vector, include it.
235 Value *VecOp = IEI->getOperand(0);
236 Value *ScalarOp = IEI->getOperand(1);
237 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000238
Chris Lattnerec97a902010-01-05 05:36:20 +0000239 if (!isa<ConstantInt>(IdxOp))
240 return false;
241 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000242
Chris Lattnerec97a902010-01-05 05:36:20 +0000243 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
244 // Okay, we can handle this if the vector we are insertinting into is
245 // transitively ok.
246 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
247 // If so, update the mask to reflect the inserted undef.
248 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
249 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000250 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000251 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
252 if (isa<ConstantInt>(EI->getOperand(1)) &&
253 EI->getOperand(0)->getType() == V->getType()) {
254 unsigned ExtractedIdx =
255 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000256
Chris Lattnerec97a902010-01-05 05:36:20 +0000257 // This must be extracting from either LHS or RHS.
258 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
259 // Okay, we can handle this if the vector we are insertinting into is
260 // transitively ok.
261 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
262 // If so, update the mask to reflect the inserted value.
263 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000264 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000265 ConstantInt::get(Type::getInt32Ty(V->getContext()),
266 ExtractedIdx);
267 } else {
268 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000269 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000270 ConstantInt::get(Type::getInt32Ty(V->getContext()),
271 ExtractedIdx+NumElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000272 }
273 return true;
274 }
275 }
276 }
277 }
278 }
279 // TODO: Handle shufflevector here!
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000280
Chris Lattnerec97a902010-01-05 05:36:20 +0000281 return false;
282}
283
284/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
285/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
286/// that computes V and the LHS value of the shuffle.
287static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
288 Value *&RHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000289 assert(V->getType()->isVectorTy() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000290 (RHS == 0 || V->getType() == RHS->getType()) &&
291 "Invalid shuffle!");
292 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000293
Chris Lattnerec97a902010-01-05 05:36:20 +0000294 if (isa<UndefValue>(V)) {
295 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
296 return V;
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000297 }
298
299 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000300 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
301 return V;
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000302 }
303
304 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000305 // If this is an insert of an extract from some other vector, include it.
306 Value *VecOp = IEI->getOperand(0);
307 Value *ScalarOp = IEI->getOperand(1);
308 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000309
Chris Lattnerec97a902010-01-05 05:36:20 +0000310 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
311 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
312 EI->getOperand(0)->getType() == V->getType()) {
313 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000314 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000315 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000316
Chris Lattnerec97a902010-01-05 05:36:20 +0000317 // Either the extracted from or inserted into vector must be RHSVec,
318 // otherwise we'd end up with a shuffle of three inputs.
319 if (EI->getOperand(0) == RHS || RHS == 0) {
320 RHS = EI->getOperand(0);
321 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000322 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000323 ConstantInt::get(Type::getInt32Ty(V->getContext()),
324 NumElts+ExtractedIdx);
Chris Lattnerec97a902010-01-05 05:36:20 +0000325 return V;
326 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000327
Chris Lattnerec97a902010-01-05 05:36:20 +0000328 if (VecOp == RHS) {
329 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
330 // Everything but the extracted element is replaced with the RHS.
331 for (unsigned i = 0; i != NumElts; ++i) {
332 if (i != InsertedIdx)
333 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
334 NumElts+i);
335 }
336 return V;
337 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000338
Chris Lattnerec97a902010-01-05 05:36:20 +0000339 // If this insertelement is a chain that comes from exactly these two
340 // vectors, return the vector and the effective shuffle.
341 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
342 return EI->getOperand(0);
343 }
344 }
345 }
346 // TODO: Handle shufflevector here!
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000347
Chris Lattnerec97a902010-01-05 05:36:20 +0000348 // Otherwise, can't do anything fancy. Return an identity vector.
349 for (unsigned i = 0; i != NumElts; ++i)
350 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
351 return V;
352}
353
354Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
355 Value *VecOp = IE.getOperand(0);
356 Value *ScalarOp = IE.getOperand(1);
357 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000358
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 // Inserting an undef or into an undefined place, remove this.
360 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
361 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000362
363 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000364 // indexes are constant, try to turn this into a shufflevector operation.
365 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
366 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
367 EI->getOperand(0)->getType() == IE.getType()) {
368 unsigned NumVectorElts = IE.getType()->getNumElements();
369 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000370 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000371 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000372
Chris Lattnerec97a902010-01-05 05:36:20 +0000373 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
374 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000375
Chris Lattnerec97a902010-01-05 05:36:20 +0000376 if (InsertedIdx >= NumVectorElts) // Out of range insert.
377 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000378
Chris Lattnerec97a902010-01-05 05:36:20 +0000379 // If we are extracting a value from a vector, then inserting it right
380 // back into the same place, just use the input vector.
381 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000382 return ReplaceInstUsesWith(IE, VecOp);
383
Chris Lattnerec97a902010-01-05 05:36:20 +0000384 // If this insertelement isn't used by some other insertelement, turn it
385 // (and any insertelements it points to), into one big shuffle.
386 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
387 std::vector<Constant*> Mask;
388 Value *RHS = 0;
389 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
390 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
391 // We now have a shuffle of LHS, RHS, Mask.
Bob Wilson67a6f322010-10-29 22:20:45 +0000392 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerec97a902010-01-05 05:36:20 +0000393 }
394 }
395 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000396
Chris Lattnerec97a902010-01-05 05:36:20 +0000397 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
398 APInt UndefElts(VWidth, 0);
399 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000400 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
401 if (V != &IE)
402 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000403 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000404 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000405
Chris Lattnerec97a902010-01-05 05:36:20 +0000406 return 0;
407}
408
409
410Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
411 Value *LHS = SVI.getOperand(0);
412 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000413 SmallVector<int, 16> Mask = SVI.getShuffleMask();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000414
Chris Lattnerec97a902010-01-05 05:36:20 +0000415 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000416
Chris Lattnerec97a902010-01-05 05:36:20 +0000417 // Undefined shuffle mask -> undefined value.
418 if (isa<UndefValue>(SVI.getOperand(2)))
419 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000420
Eric Christopher51edc7b2010-08-17 22:55:27 +0000421 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000422
Chris Lattnerec97a902010-01-05 05:36:20 +0000423 APInt UndefElts(VWidth, 0);
424 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000425 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
426 if (V != &SVI)
427 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000428 LHS = SVI.getOperand(0);
429 RHS = SVI.getOperand(1);
430 MadeChange = true;
431 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000432
Eli Friedmance818272011-10-21 19:06:29 +0000433 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
434
Chris Lattnerec97a902010-01-05 05:36:20 +0000435 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
436 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
437 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000438 if (isa<UndefValue>(LHS) && LHS == RHS) {
439 // shuffle(undef,undef,mask) -> undef.
Eli Friedmance818272011-10-21 19:06:29 +0000440 Value* result = (VWidth == LHSWidth)
441 ? LHS : UndefValue::get(SVI.getType());
442 return ReplaceInstUsesWith(SVI, result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000443 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000444
Chris Lattnerec97a902010-01-05 05:36:20 +0000445 // Remap any references to RHS to use LHS.
446 std::vector<Constant*> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000447 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Bob Wilson11ee4562010-10-29 22:03:05 +0000448 if (Mask[i] < 0)
Chris Lattnerec97a902010-01-05 05:36:20 +0000449 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
450 else {
Bob Wilson11ee4562010-10-29 22:03:05 +0000451 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
452 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
453 Mask[i] = -1; // Turn into undef.
Chris Lattnerec97a902010-01-05 05:36:20 +0000454 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
455 } else {
456 Mask[i] = Mask[i] % e; // Force to LHS.
457 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
458 Mask[i]));
459 }
460 }
461 }
462 SVI.setOperand(0, SVI.getOperand(1));
463 SVI.setOperand(1, UndefValue::get(RHS->getType()));
464 SVI.setOperand(2, ConstantVector::get(Elts));
465 LHS = SVI.getOperand(0);
466 RHS = SVI.getOperand(1);
467 MadeChange = true;
468 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000469
Eli Friedmance818272011-10-21 19:06:29 +0000470 if (VWidth == LHSWidth) {
471 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
472 bool isLHSID = true, isRHSID = true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000473
Eli Friedmance818272011-10-21 19:06:29 +0000474 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
475 if (Mask[i] < 0) continue; // Ignore undef values.
476 // Is this an identity shuffle of the LHS value?
477 isLHSID &= (Mask[i] == (int)i);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000478
Eli Friedmance818272011-10-21 19:06:29 +0000479 // Is this an identity shuffle of the RHS value?
480 isRHSID &= (Mask[i]-e == i);
481 }
482
483 // Eliminate identity shuffles.
484 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
485 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000486 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000487
Eric Christopher51edc7b2010-08-17 22:55:27 +0000488 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +0000489 // one without producing an unusual shuffle.
490 // Cases that might be simplified:
491 // 1.
492 // x1=shuffle(v1,v2,mask1)
493 // x=shuffle(x1,undef,mask)
494 // ==>
495 // x=shuffle(v1,undef,newMask)
496 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
497 // 2.
498 // x1=shuffle(v1,undef,mask1)
499 // x=shuffle(x1,x2,mask)
500 // where v1.size() == mask1.size()
501 // ==>
502 // x=shuffle(v1,x2,newMask)
503 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
504 // 3.
505 // x2=shuffle(v2,undef,mask2)
506 // x=shuffle(x1,x2,mask)
507 // where v2.size() == mask2.size()
508 // ==>
509 // x=shuffle(x1,v2,newMask)
510 // newMask[i] = (mask[i] < x1.size())
511 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
512 // 4.
513 // x1=shuffle(v1,undef,mask1)
514 // x2=shuffle(v2,undef,mask2)
515 // x=shuffle(x1,x2,mask)
516 // where v1.size() == v2.size()
517 // ==>
518 // x=shuffle(v1,v2,newMask)
519 // newMask[i] = (mask[i] < x1.size())
520 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
521 //
522 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +0000523 // we are absolutely afraid of producing a shuffle mask not in the input
524 // program, because the code gen may not be smart enough to turn a merged
525 // shuffle into two specific shuffles: it may produce worse code. As such,
Bob Wilsoncb11b482010-10-29 22:02:50 +0000526 // we only merge two shuffles if the result is either a splat or one of the
Eli Friedmance818272011-10-21 19:06:29 +0000527 // input shuffle masks. In this case, merging the shuffles just removes
Bob Wilsoncb11b482010-10-29 22:02:50 +0000528 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +0000529 // turning: (splat(splat)) -> splat, or
530 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
531 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
532 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
533 if (LHSShuffle)
534 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
535 LHSShuffle = NULL;
536 if (RHSShuffle)
537 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
538 RHSShuffle = NULL;
539 if (!LHSShuffle && !RHSShuffle)
540 return MadeChange ? &SVI : 0;
541
542 Value* LHSOp0 = NULL;
543 Value* LHSOp1 = NULL;
544 Value* RHSOp0 = NULL;
545 unsigned LHSOp0Width = 0;
546 unsigned RHSOp0Width = 0;
547 if (LHSShuffle) {
548 LHSOp0 = LHSShuffle->getOperand(0);
549 LHSOp1 = LHSShuffle->getOperand(1);
550 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
551 }
552 if (RHSShuffle) {
553 RHSOp0 = RHSShuffle->getOperand(0);
554 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
555 }
556 Value* newLHS = LHS;
557 Value* newRHS = RHS;
558 if (LHSShuffle) {
559 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +0000560 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +0000561 newLHS = LHSOp0;
562 newRHS = LHSOp1;
563 }
564 // case 2 or 4
565 else if (LHSOp0Width == LHSWidth) {
566 newLHS = LHSOp0;
567 }
568 }
569 // case 3 or 4
570 if (RHSShuffle && RHSOp0Width == LHSWidth) {
571 newRHS = RHSOp0;
572 }
573 // case 4
574 if (LHSOp0 == RHSOp0) {
575 newLHS = LHSOp0;
576 newRHS = NULL;
577 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000578
Eli Friedmance818272011-10-21 19:06:29 +0000579 if (newLHS == LHS && newRHS == RHS)
580 return MadeChange ? &SVI : 0;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000581
Eli Friedmance818272011-10-21 19:06:29 +0000582 SmallVector<int, 16> LHSMask;
583 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +0000584 if (newLHS != LHS)
585 LHSMask = LHSShuffle->getShuffleMask();
586 if (RHSShuffle && newRHS != RHS)
587 RHSMask = RHSShuffle->getShuffleMask();
588
Eli Friedmance818272011-10-21 19:06:29 +0000589 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
590 SmallVector<int, 16> newMask;
591 bool isSplat = true;
592 int SplatElt = -1;
593 // Create a new mask for the new ShuffleVectorInst so that the new
594 // ShuffleVectorInst is equivalent to the original one.
595 for (unsigned i = 0; i < VWidth; ++i) {
596 int eltMask;
597 if (Mask[i] == -1) {
598 // This element is an undef value.
599 eltMask = -1;
600 } else if (Mask[i] < (int)LHSWidth) {
601 // This element is from left hand side vector operand.
602 //
603 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
604 // new mask value for the element.
605 if (newLHS != LHS) {
606 eltMask = LHSMask[Mask[i]];
607 // If the value selected is an undef value, explicitly specify it
608 // with a -1 mask value.
609 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
610 eltMask = -1;
611 }
612 else
613 eltMask = Mask[i];
614 } else {
615 // This element is from right hand side vector operand
616 //
617 // If the value selected is an undef value, explicitly specify it
618 // with a -1 mask value. (case 1)
619 if (isa<UndefValue>(RHS))
620 eltMask = -1;
621 // If RHS is going to be replaced (case 3 or 4), calculate the
622 // new mask value for the element.
623 else if (newRHS != RHS) {
624 eltMask = RHSMask[Mask[i]-LHSWidth];
625 // If the value selected is an undef value, explicitly specify it
626 // with a -1 mask value.
627 if (eltMask >= (int)RHSOp0Width) {
628 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
629 && "should have been check above");
630 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000631 }
632 }
Eli Friedmance818272011-10-21 19:06:29 +0000633 else
634 eltMask = Mask[i]-LHSWidth;
635
636 // If LHS's width is changed, shift the mask value accordingly.
637 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
638 // references to RHSOp0 to LHSOp0, so we don't need to shift the mask.
639 if (eltMask >= 0 && newRHS != NULL)
640 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000641 }
Eli Friedmance818272011-10-21 19:06:29 +0000642
643 // Check if this could still be a splat.
644 if (eltMask >= 0) {
645 if (SplatElt >= 0 && SplatElt != eltMask)
646 isSplat = false;
647 SplatElt = eltMask;
648 }
649
650 newMask.push_back(eltMask);
651 }
652
653 // If the result mask is equal to one of the original shuffle masks,
654 // or is a splat, do the replacement.
655 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
656 SmallVector<Constant*, 16> Elts;
657 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
658 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
659 if (newMask[i] < 0) {
660 Elts.push_back(UndefValue::get(Int32Ty));
661 } else {
662 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
663 }
664 }
665 if (newRHS == NULL)
666 newRHS = UndefValue::get(newLHS->getType());
667 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000668 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000669
Chris Lattnerec97a902010-01-05 05:36:20 +0000670 return MadeChange ? &SVI : 0;
671}