Fix for wrong instcombine on vector insert/extract
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineVectorOps.cpp
1 //===- 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"
16 #include "llvm/Support/PatternMatch.h"
17 using namespace llvm;
18 using namespace PatternMatch;
19
20 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
21 /// is to leave as a vector operation.  isConstant indicates whether we're
22 /// extracting one known element.  If false we're extracting a variable index.
23 static bool CheapToScalarize(Value *V, bool isConstant) {
24   if (Constant *C = dyn_cast<Constant>(V)) {
25     if (isConstant) return true;
26
27     // If all elts are the same, we can extract it and use any of the values.
28     Constant *Op0 = C->getAggregateElement(0U);
29     for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; ++i)
30       if (C->getAggregateElement(i) != Op0)
31         return false;
32     return true;
33   }
34   Instruction *I = dyn_cast<Instruction>(V);
35   if (!I) return false;
36
37   // Insert element gets simplified to the inserted element or is deleted if
38   // this is constant idx extract element and its a constant idx insertelt.
39   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
40       isa<ConstantInt>(I->getOperand(2)))
41     return true;
42   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
43     return true;
44   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
45     if (BO->hasOneUse() &&
46         (CheapToScalarize(BO->getOperand(0), isConstant) ||
47          CheapToScalarize(BO->getOperand(1), isConstant)))
48       return true;
49   if (CmpInst *CI = dyn_cast<CmpInst>(I))
50     if (CI->hasOneUse() &&
51         (CheapToScalarize(CI->getOperand(0), isConstant) ||
52          CheapToScalarize(CI->getOperand(1), isConstant)))
53       return true;
54
55   return false;
56 }
57
58 /// FindScalarElement - Given a vector and an element number, see if the scalar
59 /// value is already around as a register, for example if it were inserted then
60 /// extracted from the vector.
61 static Value *FindScalarElement(Value *V, unsigned EltNo) {
62   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
63   VectorType *VTy = cast<VectorType>(V->getType());
64   unsigned Width = VTy->getNumElements();
65   if (EltNo >= Width)  // Out of range access.
66     return UndefValue::get(VTy->getElementType());
67
68   if (Constant *C = dyn_cast<Constant>(V))
69     return C->getAggregateElement(EltNo);
70
71   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
72     // If this is an insert to a variable element, we don't know what it is.
73     if (!isa<ConstantInt>(III->getOperand(2)))
74       return 0;
75     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
76
77     // If this is an insert to the element we are looking for, return the
78     // inserted value.
79     if (EltNo == IIElt)
80       return III->getOperand(1);
81
82     // Otherwise, the insertelement doesn't modify the value, recurse on its
83     // vector input.
84     return FindScalarElement(III->getOperand(0), EltNo);
85   }
86
87   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
88     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
89     int InEl = SVI->getMaskValue(EltNo);
90     if (InEl < 0)
91       return UndefValue::get(VTy->getElementType());
92     if (InEl < (int)LHSWidth)
93       return FindScalarElement(SVI->getOperand(0), InEl);
94     return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
95   }
96
97   // Extract a value from a vector add operation with a constant zero.
98   Value *Val = 0; Constant *Con = 0;
99   if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
100     if (Con->getAggregateElement(EltNo)->isNullValue())
101       return FindScalarElement(Val, EltNo);
102   }
103
104   // Otherwise, we don't know.
105   return 0;
106 }
107
108 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
109   // If vector val is constant with all elements the same, replace EI with
110   // that element.  We handle a known element # below.
111   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
112     if (CheapToScalarize(C, false))
113       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
114
115   // If extracting a specified index from the vector, see if we can recursively
116   // find a previously computed scalar that was inserted into the vector.
117   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
118     unsigned IndexVal = IdxC->getZExtValue();
119     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
120
121     // If this is extracting an invalid index, turn this into undef, to avoid
122     // crashing the code below.
123     if (IndexVal >= VectorWidth)
124       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
125
126     // This instruction only demands the single element from the input vector.
127     // If the input vector has a single use, simplify it based on this use
128     // property.
129     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
130       APInt UndefElts(VectorWidth, 0);
131       APInt DemandedMask(VectorWidth, 0);
132       DemandedMask.setBit(IndexVal);
133       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
134                                                 DemandedMask, UndefElts)) {
135         EI.setOperand(0, V);
136         return &EI;
137       }
138     }
139
140     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
141       return ReplaceInstUsesWith(EI, Elt);
142
143     // If the this extractelement is directly using a bitcast from a vector of
144     // the same number of elements, see if we can find the source element from
145     // it.  In this case, we will end up needing to bitcast the scalars.
146     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
147       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
148         if (VT->getNumElements() == VectorWidth)
149           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
150             return new BitCastInst(Elt, EI.getType());
151     }
152   }
153
154   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
155     // Push extractelement into predecessor operation if legal and
156     // profitable to do so
157     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
158       if (I->hasOneUse() &&
159           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
160         Value *newEI0 =
161           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
162                                         EI.getName()+".lhs");
163         Value *newEI1 =
164           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
165                                         EI.getName()+".rhs");
166         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
167       }
168     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
169       // Extracting the inserted element?
170       if (IE->getOperand(2) == EI.getOperand(1))
171         return ReplaceInstUsesWith(EI, IE->getOperand(1));
172       // If the inserted and extracted elements are constants, they must not
173       // be the same value, extract from the pre-inserted value instead.
174       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
175         Worklist.AddValue(EI.getOperand(0));
176         EI.setOperand(0, IE->getOperand(0));
177         return &EI;
178       }
179     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
180       // If this is extracting an element from a shufflevector, figure out where
181       // it came from and extract from the appropriate input element instead.
182       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
183         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
184         Value *Src;
185         unsigned LHSWidth =
186           SVI->getOperand(0)->getType()->getVectorNumElements();
187
188         if (SrcIdx < 0)
189           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
190         if (SrcIdx < (int)LHSWidth)
191           Src = SVI->getOperand(0);
192         else {
193           SrcIdx -= LHSWidth;
194           Src = SVI->getOperand(1);
195         }
196         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
197         return ExtractElementInst::Create(Src,
198                                           ConstantInt::get(Int32Ty,
199                                                            SrcIdx, false));
200       }
201     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
202       // Canonicalize extractelement(cast) -> cast(extractelement)
203       // bitcasts can change the number of vector elements and they cost nothing
204       if (CI->hasOneUse() && EI.hasOneUse() &&
205           (CI->getOpcode() != Instruction::BitCast)) {
206         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
207                                                   EI.getIndexOperand());
208         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
209       }
210     }
211   }
212   return 0;
213 }
214
215 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
216 /// elements from either LHS or RHS, return the shuffle mask and true.
217 /// Otherwise, return false.
218 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
219                                          SmallVectorImpl<Constant*> &Mask) {
220   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
221          "Invalid CollectSingleShuffleElements");
222   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
223
224   if (isa<UndefValue>(V)) {
225     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
226     return true;
227   }
228
229   if (V == LHS) {
230     for (unsigned i = 0; i != NumElts; ++i)
231       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
232     return true;
233   }
234
235   if (V == RHS) {
236     for (unsigned i = 0; i != NumElts; ++i)
237       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
238                                       i+NumElts));
239     return true;
240   }
241
242   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
243     // If this is an insert of an extract from some other vector, include it.
244     Value *VecOp    = IEI->getOperand(0);
245     Value *ScalarOp = IEI->getOperand(1);
246     Value *IdxOp    = IEI->getOperand(2);
247
248     if (!isa<ConstantInt>(IdxOp))
249       return false;
250     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
251
252     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
253       // Okay, we can handle this if the vector we are insertinting into is
254       // transitively ok.
255       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
256         // If so, update the mask to reflect the inserted undef.
257         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
258         return true;
259       }
260     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
261       if (isa<ConstantInt>(EI->getOperand(1)) &&
262           EI->getOperand(0)->getType() == V->getType()) {
263         unsigned ExtractedIdx =
264         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
265
266         // This must be extracting from either LHS or RHS.
267         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
268           // Okay, we can handle this if the vector we are insertinting into is
269           // transitively ok.
270           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
271             // If so, update the mask to reflect the inserted value.
272             if (EI->getOperand(0) == LHS) {
273               Mask[InsertedIdx % NumElts] =
274               ConstantInt::get(Type::getInt32Ty(V->getContext()),
275                                ExtractedIdx);
276             } else {
277               assert(EI->getOperand(0) == RHS);
278               Mask[InsertedIdx % NumElts] =
279               ConstantInt::get(Type::getInt32Ty(V->getContext()),
280                                ExtractedIdx+NumElts);
281             }
282             return true;
283           }
284         }
285       }
286     }
287   }
288   // TODO: Handle shufflevector here!
289
290   return false;
291 }
292
293 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
294 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
295 /// that computes V and the LHS value of the shuffle.
296 static Value *CollectShuffleElements(Value *V, SmallVectorImpl<Constant*> &Mask,
297                                      Value *&RHS) {
298   assert(V->getType()->isVectorTy() &&
299          (RHS == 0 || V->getType() == RHS->getType()) &&
300          "Invalid shuffle!");
301   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
302
303   if (isa<UndefValue>(V)) {
304     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
305     return V;
306   }
307
308   if (isa<ConstantAggregateZero>(V)) {
309     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
310     return V;
311   }
312
313   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
314     // If this is an insert of an extract from some other vector, include it.
315     Value *VecOp    = IEI->getOperand(0);
316     Value *ScalarOp = IEI->getOperand(1);
317     Value *IdxOp    = IEI->getOperand(2);
318
319     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
320       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
321           EI->getOperand(0)->getType() == V->getType()) {
322         unsigned ExtractedIdx =
323           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
324         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
325
326         // Either the extracted from or inserted into vector must be RHSVec,
327         // otherwise we'd end up with a shuffle of three inputs.
328         if (EI->getOperand(0) == RHS || RHS == 0) {
329           RHS = EI->getOperand(0);
330           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
331           Mask[InsertedIdx % NumElts] =
332             ConstantInt::get(Type::getInt32Ty(V->getContext()),
333                              NumElts+ExtractedIdx);
334           return V;
335         }
336
337         if (VecOp == RHS) {
338           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
339           // Update Mask to reflect that `ScalarOp' has been inserted at
340           // position `InsertedIdx' within the vector returned by IEI.
341           Mask[InsertedIdx % NumElts] = Mask[ExtractedIdx];
342
343           // Everything but the extracted element is replaced with the RHS.
344           for (unsigned i = 0; i != NumElts; ++i) {
345             if (i != InsertedIdx)
346               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
347                                          NumElts+i);
348           }
349           return V;
350         }
351
352         // If this insertelement is a chain that comes from exactly these two
353         // vectors, return the vector and the effective shuffle.
354         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
355           return EI->getOperand(0);
356       }
357     }
358   }
359   // TODO: Handle shufflevector here!
360
361   // Otherwise, can't do anything fancy.  Return an identity vector.
362   for (unsigned i = 0; i != NumElts; ++i)
363     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
364   return V;
365 }
366
367 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
368   Value *VecOp    = IE.getOperand(0);
369   Value *ScalarOp = IE.getOperand(1);
370   Value *IdxOp    = IE.getOperand(2);
371
372   // Inserting an undef or into an undefined place, remove this.
373   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
374     ReplaceInstUsesWith(IE, VecOp);
375
376   // If the inserted element was extracted from some other vector, and if the
377   // indexes are constant, try to turn this into a shufflevector operation.
378   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
379     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
380         EI->getOperand(0)->getType() == IE.getType()) {
381       unsigned NumVectorElts = IE.getType()->getNumElements();
382       unsigned ExtractedIdx =
383         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
384       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
385
386       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
387         return ReplaceInstUsesWith(IE, VecOp);
388
389       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
390         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
391
392       // If we are extracting a value from a vector, then inserting it right
393       // back into the same place, just use the input vector.
394       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
395         return ReplaceInstUsesWith(IE, VecOp);
396
397       // If this insertelement isn't used by some other insertelement, turn it
398       // (and any insertelements it points to), into one big shuffle.
399       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
400         SmallVector<Constant*, 16> Mask;
401         Value *RHS = 0;
402         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
403         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
404         // We now have a shuffle of LHS, RHS, Mask.
405         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
406       }
407     }
408   }
409
410   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
411   APInt UndefElts(VWidth, 0);
412   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
413   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
414     if (V != &IE)
415       return ReplaceInstUsesWith(IE, V);
416     return &IE;
417   }
418
419   return 0;
420 }
421
422
423 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
424   Value *LHS = SVI.getOperand(0);
425   Value *RHS = SVI.getOperand(1);
426   SmallVector<int, 16> Mask = SVI.getShuffleMask();
427
428   bool MadeChange = false;
429
430   // Undefined shuffle mask -> undefined value.
431   if (isa<UndefValue>(SVI.getOperand(2)))
432     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
433
434   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
435
436   APInt UndefElts(VWidth, 0);
437   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
438   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
439     if (V != &SVI)
440       return ReplaceInstUsesWith(SVI, V);
441     LHS = SVI.getOperand(0);
442     RHS = SVI.getOperand(1);
443     MadeChange = true;
444   }
445
446   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
447
448   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
449   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
450   if (LHS == RHS || isa<UndefValue>(LHS)) {
451     if (isa<UndefValue>(LHS) && LHS == RHS) {
452       // shuffle(undef,undef,mask) -> undef.
453       Value* result = (VWidth == LHSWidth)
454                       ? LHS : UndefValue::get(SVI.getType());
455       return ReplaceInstUsesWith(SVI, result);
456     }
457
458     // Remap any references to RHS to use LHS.
459     SmallVector<Constant*, 16> Elts;
460     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
461       if (Mask[i] < 0) {
462         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
463         continue;
464       }
465
466       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
467           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
468         Mask[i] = -1;     // Turn into undef.
469         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
470       } else {
471         Mask[i] = Mask[i] % e;  // Force to LHS.
472         Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
473                                         Mask[i]));
474       }
475     }
476     SVI.setOperand(0, SVI.getOperand(1));
477     SVI.setOperand(1, UndefValue::get(RHS->getType()));
478     SVI.setOperand(2, ConstantVector::get(Elts));
479     LHS = SVI.getOperand(0);
480     RHS = SVI.getOperand(1);
481     MadeChange = true;
482   }
483
484   if (VWidth == LHSWidth) {
485     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
486     bool isLHSID = true, isRHSID = true;
487
488     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
489       if (Mask[i] < 0) continue;  // Ignore undef values.
490       // Is this an identity shuffle of the LHS value?
491       isLHSID &= (Mask[i] == (int)i);
492
493       // Is this an identity shuffle of the RHS value?
494       isRHSID &= (Mask[i]-e == i);
495     }
496
497     // Eliminate identity shuffles.
498     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
499     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
500   }
501
502   // If the LHS is a shufflevector itself, see if we can combine it with this
503   // one without producing an unusual shuffle.
504   // Cases that might be simplified:
505   // 1.
506   // x1=shuffle(v1,v2,mask1)
507   //  x=shuffle(x1,undef,mask)
508   //        ==>
509   //  x=shuffle(v1,undef,newMask)
510   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
511   // 2.
512   // x1=shuffle(v1,undef,mask1)
513   //  x=shuffle(x1,x2,mask)
514   // where v1.size() == mask1.size()
515   //        ==>
516   //  x=shuffle(v1,x2,newMask)
517   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
518   // 3.
519   // x2=shuffle(v2,undef,mask2)
520   //  x=shuffle(x1,x2,mask)
521   // where v2.size() == mask2.size()
522   //        ==>
523   //  x=shuffle(x1,v2,newMask)
524   // newMask[i] = (mask[i] < x1.size())
525   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
526   // 4.
527   // x1=shuffle(v1,undef,mask1)
528   // x2=shuffle(v2,undef,mask2)
529   //  x=shuffle(x1,x2,mask)
530   // where v1.size() == v2.size()
531   //        ==>
532   //  x=shuffle(v1,v2,newMask)
533   // newMask[i] = (mask[i] < x1.size())
534   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
535   //
536   // Here we are really conservative:
537   // we are absolutely afraid of producing a shuffle mask not in the input
538   // program, because the code gen may not be smart enough to turn a merged
539   // shuffle into two specific shuffles: it may produce worse code.  As such,
540   // we only merge two shuffles if the result is either a splat or one of the
541   // input shuffle masks.  In this case, merging the shuffles just removes
542   // one instruction, which we know is safe.  This is good for things like
543   // turning: (splat(splat)) -> splat, or
544   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
545   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
546   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
547   if (LHSShuffle)
548     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
549       LHSShuffle = NULL;
550   if (RHSShuffle)
551     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
552       RHSShuffle = NULL;
553   if (!LHSShuffle && !RHSShuffle)
554     return MadeChange ? &SVI : 0;
555
556   Value* LHSOp0 = NULL;
557   Value* LHSOp1 = NULL;
558   Value* RHSOp0 = NULL;
559   unsigned LHSOp0Width = 0;
560   unsigned RHSOp0Width = 0;
561   if (LHSShuffle) {
562     LHSOp0 = LHSShuffle->getOperand(0);
563     LHSOp1 = LHSShuffle->getOperand(1);
564     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
565   }
566   if (RHSShuffle) {
567     RHSOp0 = RHSShuffle->getOperand(0);
568     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
569   }
570   Value* newLHS = LHS;
571   Value* newRHS = RHS;
572   if (LHSShuffle) {
573     // case 1
574     if (isa<UndefValue>(RHS)) {
575       newLHS = LHSOp0;
576       newRHS = LHSOp1;
577     }
578     // case 2 or 4
579     else if (LHSOp0Width == LHSWidth) {
580       newLHS = LHSOp0;
581     }
582   }
583   // case 3 or 4
584   if (RHSShuffle && RHSOp0Width == LHSWidth) {
585     newRHS = RHSOp0;
586   }
587   // case 4
588   if (LHSOp0 == RHSOp0) {
589     newLHS = LHSOp0;
590     newRHS = NULL;
591   }
592
593   if (newLHS == LHS && newRHS == RHS)
594     return MadeChange ? &SVI : 0;
595
596   SmallVector<int, 16> LHSMask;
597   SmallVector<int, 16> RHSMask;
598   if (newLHS != LHS)
599     LHSMask = LHSShuffle->getShuffleMask();
600   if (RHSShuffle && newRHS != RHS)
601     RHSMask = RHSShuffle->getShuffleMask();
602
603   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
604   SmallVector<int, 16> newMask;
605   bool isSplat = true;
606   int SplatElt = -1;
607   // Create a new mask for the new ShuffleVectorInst so that the new
608   // ShuffleVectorInst is equivalent to the original one.
609   for (unsigned i = 0; i < VWidth; ++i) {
610     int eltMask;
611     if (Mask[i] < 0) {
612       // This element is an undef value.
613       eltMask = -1;
614     } else if (Mask[i] < (int)LHSWidth) {
615       // This element is from left hand side vector operand.
616       //
617       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
618       // new mask value for the element.
619       if (newLHS != LHS) {
620         eltMask = LHSMask[Mask[i]];
621         // If the value selected is an undef value, explicitly specify it
622         // with a -1 mask value.
623         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
624           eltMask = -1;
625       } else
626         eltMask = Mask[i];
627     } else {
628       // This element is from right hand side vector operand
629       //
630       // If the value selected is an undef value, explicitly specify it
631       // with a -1 mask value. (case 1)
632       if (isa<UndefValue>(RHS))
633         eltMask = -1;
634       // If RHS is going to be replaced (case 3 or 4), calculate the
635       // new mask value for the element.
636       else if (newRHS != RHS) {
637         eltMask = RHSMask[Mask[i]-LHSWidth];
638         // If the value selected is an undef value, explicitly specify it
639         // with a -1 mask value.
640         if (eltMask >= (int)RHSOp0Width) {
641           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
642                  && "should have been check above");
643           eltMask = -1;
644         }
645       } else
646         eltMask = Mask[i]-LHSWidth;
647
648       // If LHS's width is changed, shift the mask value accordingly.
649       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
650       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
651       // If newRHS == newLHS, we want to remap any references from newRHS to
652       // newLHS so that we can properly identify splats that may occur due to
653       // obfuscation accross the two vectors.
654       if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
655         eltMask += newLHSWidth;
656     }
657
658     // Check if this could still be a splat.
659     if (eltMask >= 0) {
660       if (SplatElt >= 0 && SplatElt != eltMask)
661         isSplat = false;
662       SplatElt = eltMask;
663     }
664
665     newMask.push_back(eltMask);
666   }
667
668   // If the result mask is equal to one of the original shuffle masks,
669   // or is a splat, do the replacement.
670   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
671     SmallVector<Constant*, 16> Elts;
672     Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
673     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
674       if (newMask[i] < 0) {
675         Elts.push_back(UndefValue::get(Int32Ty));
676       } else {
677         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
678       }
679     }
680     if (newRHS == NULL)
681       newRHS = UndefValue::get(newLHS->getType());
682     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
683   }
684
685   return MadeChange ? &SVI : 0;
686 }