54a9fbdbe82eec48f47225028431fa865895a93d
[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 "InstCombineInternal.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/VectorUtils.h"
19 #include "llvm/IR/PatternMatch.h"
20 using namespace llvm;
21 using namespace PatternMatch;
22
23 #define DEBUG_TYPE "instcombine"
24
25 /// Return true if the value is cheaper to scalarize than it is to leave as a
26 /// vector operation. isConstant indicates whether we're extracting one known
27 /// element. If false we're extracting a variable index.
28 static bool cheapToScalarize(Value *V, bool isConstant) {
29   if (Constant *C = dyn_cast<Constant>(V)) {
30     if (isConstant) return true;
31
32     // If all elts are the same, we can extract it and use any of the values.
33     if (Constant *Op0 = C->getAggregateElement(0U)) {
34       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
35            ++i)
36         if (C->getAggregateElement(i) != Op0)
37           return false;
38       return true;
39     }
40   }
41   Instruction *I = dyn_cast<Instruction>(V);
42   if (!I) return false;
43
44   // Insert element gets simplified to the inserted element or is deleted if
45   // this is constant idx extract element and its a constant idx insertelt.
46   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
47       isa<ConstantInt>(I->getOperand(2)))
48     return true;
49   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
50     return true;
51   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
52     if (BO->hasOneUse() &&
53         (cheapToScalarize(BO->getOperand(0), isConstant) ||
54          cheapToScalarize(BO->getOperand(1), isConstant)))
55       return true;
56   if (CmpInst *CI = dyn_cast<CmpInst>(I))
57     if (CI->hasOneUse() &&
58         (cheapToScalarize(CI->getOperand(0), isConstant) ||
59          cheapToScalarize(CI->getOperand(1), isConstant)))
60       return true;
61
62   return false;
63 }
64
65 // If we have a PHI node with a vector type that has only 2 uses: feed
66 // itself and be an operand of extractelement at a constant location,
67 // try to replace the PHI of the vector type with a PHI of a scalar type.
68 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
69   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
70   if (!PN->hasNUses(2))
71     return nullptr;
72
73   // If so, it's known at this point that one operand is PHI and the other is
74   // an extractelement node. Find the PHI user that is not the extractelement
75   // node.
76   auto iu = PN->user_begin();
77   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
78   if (PHIUser == cast<Instruction>(&EI))
79     PHIUser = cast<Instruction>(*(++iu));
80
81   // Verify that this PHI user has one use, which is the PHI itself,
82   // and that it is a binary operation which is cheap to scalarize.
83   // otherwise return NULL.
84   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
85       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
86     return nullptr;
87
88   // Create a scalar PHI node that will replace the vector PHI node
89   // just before the current PHI node.
90   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
91       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
92   // Scalarize each PHI operand.
93   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
94     Value *PHIInVal = PN->getIncomingValue(i);
95     BasicBlock *inBB = PN->getIncomingBlock(i);
96     Value *Elt = EI.getIndexOperand();
97     // If the operand is the PHI induction variable:
98     if (PHIInVal == PHIUser) {
99       // Scalarize the binary operation. Its first operand is the
100       // scalar PHI, and the second operand is extracted from the other
101       // vector operand.
102       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
103       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
104       Value *Op = InsertNewInstWith(
105           ExtractElementInst::Create(B0->getOperand(opId), Elt,
106                                      B0->getOperand(opId)->getName() + ".Elt"),
107           *B0);
108       Value *newPHIUser = InsertNewInstWith(
109           BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
110       scalarPHI->addIncoming(newPHIUser, inBB);
111     } else {
112       // Scalarize PHI input:
113       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
114       // Insert the new instruction into the predecessor basic block.
115       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
116       BasicBlock::iterator InsertPos;
117       if (pos && !isa<PHINode>(pos)) {
118         InsertPos = ++pos->getIterator();
119       } else {
120         InsertPos = inBB->getFirstInsertionPt();
121       }
122
123       InsertNewInstWith(newEI, *InsertPos);
124
125       scalarPHI->addIncoming(newEI, inBB);
126     }
127   }
128   return ReplaceInstUsesWith(EI, scalarPHI);
129 }
130
131 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
132   if (Value *V = SimplifyExtractElementInst(
133           EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
134     return ReplaceInstUsesWith(EI, V);
135
136   // If vector val is constant with all elements the same, replace EI with
137   // that element.  We handle a known element # below.
138   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
139     if (cheapToScalarize(C, false))
140       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
141
142   // If extracting a specified index from the vector, see if we can recursively
143   // find a previously computed scalar that was inserted into the vector.
144   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
145     unsigned IndexVal = IdxC->getZExtValue();
146     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
147
148     // InstSimplify handles cases where the index is invalid.
149     assert(IndexVal < VectorWidth);
150
151     // This instruction only demands the single element from the input vector.
152     // If the input vector has a single use, simplify it based on this use
153     // property.
154     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
155       APInt UndefElts(VectorWidth, 0);
156       APInt DemandedMask(VectorWidth, 0);
157       DemandedMask.setBit(IndexVal);
158       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
159                                                 UndefElts)) {
160         EI.setOperand(0, V);
161         return &EI;
162       }
163     }
164
165     // If this extractelement is directly using a bitcast from a vector of
166     // the same number of elements, see if we can find the source element from
167     // it.  In this case, we will end up needing to bitcast the scalars.
168     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
169       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
170         if (VT->getNumElements() == VectorWidth)
171           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
172             return new BitCastInst(Elt, EI.getType());
173     }
174
175     // If there's a vector PHI feeding a scalar use through this extractelement
176     // instruction, try to scalarize the PHI.
177     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
178       Instruction *scalarPHI = scalarizePHI(EI, PN);
179       if (scalarPHI)
180         return scalarPHI;
181     }
182   }
183
184   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
185     // Push extractelement into predecessor operation if legal and
186     // profitable to do so.
187     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
188       if (I->hasOneUse() &&
189           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
190         Value *newEI0 =
191           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
192                                         EI.getName()+".lhs");
193         Value *newEI1 =
194           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
195                                         EI.getName()+".rhs");
196         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
197       }
198     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
199       // Extracting the inserted element?
200       if (IE->getOperand(2) == EI.getOperand(1))
201         return ReplaceInstUsesWith(EI, IE->getOperand(1));
202       // If the inserted and extracted elements are constants, they must not
203       // be the same value, extract from the pre-inserted value instead.
204       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
205         Worklist.AddValue(EI.getOperand(0));
206         EI.setOperand(0, IE->getOperand(0));
207         return &EI;
208       }
209     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
210       // If this is extracting an element from a shufflevector, figure out where
211       // it came from and extract from the appropriate input element instead.
212       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
213         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
214         Value *Src;
215         unsigned LHSWidth =
216           SVI->getOperand(0)->getType()->getVectorNumElements();
217
218         if (SrcIdx < 0)
219           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
220         if (SrcIdx < (int)LHSWidth)
221           Src = SVI->getOperand(0);
222         else {
223           SrcIdx -= LHSWidth;
224           Src = SVI->getOperand(1);
225         }
226         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
227         return ExtractElementInst::Create(Src,
228                                           ConstantInt::get(Int32Ty,
229                                                            SrcIdx, false));
230       }
231     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
232       // Canonicalize extractelement(cast) -> cast(extractelement).
233       // Bitcasts can change the number of vector elements, and they cost
234       // nothing.
235       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
236         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
237                                                   EI.getIndexOperand());
238         Worklist.AddValue(EE);
239         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
240       }
241     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
242       if (SI->hasOneUse()) {
243         // TODO: For a select on vectors, it might be useful to do this if it
244         // has multiple extractelement uses. For vector select, that seems to
245         // fight the vectorizer.
246
247         // If we are extracting an element from a vector select or a select on
248         // vectors, create a select on the scalars extracted from the vector
249         // arguments.
250         Value *TrueVal = SI->getTrueValue();
251         Value *FalseVal = SI->getFalseValue();
252
253         Value *Cond = SI->getCondition();
254         if (Cond->getType()->isVectorTy()) {
255           Cond = Builder->CreateExtractElement(Cond,
256                                                EI.getIndexOperand(),
257                                                Cond->getName() + ".elt");
258         }
259
260         Value *V1Elem
261           = Builder->CreateExtractElement(TrueVal,
262                                           EI.getIndexOperand(),
263                                           TrueVal->getName() + ".elt");
264
265         Value *V2Elem
266           = Builder->CreateExtractElement(FalseVal,
267                                           EI.getIndexOperand(),
268                                           FalseVal->getName() + ".elt");
269         return SelectInst::Create(Cond,
270                                   V1Elem,
271                                   V2Elem,
272                                   SI->getName() + ".elt");
273       }
274     }
275   }
276   return nullptr;
277 }
278
279 /// If V is a shuffle of values that ONLY returns elements from either LHS or
280 /// RHS, return the shuffle mask and true. Otherwise, return false.
281 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
282                                          SmallVectorImpl<Constant*> &Mask) {
283   assert(LHS->getType() == RHS->getType() &&
284          "Invalid CollectSingleShuffleElements");
285   unsigned NumElts = V->getType()->getVectorNumElements();
286
287   if (isa<UndefValue>(V)) {
288     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
289     return true;
290   }
291
292   if (V == LHS) {
293     for (unsigned i = 0; i != NumElts; ++i)
294       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
295     return true;
296   }
297
298   if (V == RHS) {
299     for (unsigned i = 0; i != NumElts; ++i)
300       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
301                                       i+NumElts));
302     return true;
303   }
304
305   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
306     // If this is an insert of an extract from some other vector, include it.
307     Value *VecOp    = IEI->getOperand(0);
308     Value *ScalarOp = IEI->getOperand(1);
309     Value *IdxOp    = IEI->getOperand(2);
310
311     if (!isa<ConstantInt>(IdxOp))
312       return false;
313     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
314
315     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
316       // We can handle this if the vector we are inserting into is
317       // transitively ok.
318       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
319         // If so, update the mask to reflect the inserted undef.
320         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
321         return true;
322       }
323     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
324       if (isa<ConstantInt>(EI->getOperand(1))) {
325         unsigned ExtractedIdx =
326         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
327         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
328
329         // This must be extracting from either LHS or RHS.
330         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
331           // We can handle this if the vector we are inserting into is
332           // transitively ok.
333           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
334             // If so, update the mask to reflect the inserted value.
335             if (EI->getOperand(0) == LHS) {
336               Mask[InsertedIdx % NumElts] =
337               ConstantInt::get(Type::getInt32Ty(V->getContext()),
338                                ExtractedIdx);
339             } else {
340               assert(EI->getOperand(0) == RHS);
341               Mask[InsertedIdx % NumElts] =
342               ConstantInt::get(Type::getInt32Ty(V->getContext()),
343                                ExtractedIdx + NumLHSElts);
344             }
345             return true;
346           }
347         }
348       }
349     }
350   }
351
352   return false;
353 }
354
355 /// If we have insertion into a vector that is wider than the vector that we
356 /// are extracting from, try to widen the source vector to allow a single
357 /// shufflevector to replace one or more insert/extract pairs.
358 static void replaceExtractElements(InsertElementInst *InsElt,
359                                    ExtractElementInst *ExtElt,
360                                    InstCombiner &IC) {
361   VectorType *InsVecType = InsElt->getType();
362   VectorType *ExtVecType = ExtElt->getVectorOperandType();
363   unsigned NumInsElts = InsVecType->getVectorNumElements();
364   unsigned NumExtElts = ExtVecType->getVectorNumElements();
365
366   // The inserted-to vector must be wider than the extracted-from vector.
367   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
368       NumExtElts >= NumInsElts)
369     return;
370
371   // Create a shuffle mask to widen the extended-from vector using undefined
372   // values. The mask selects all of the values of the original vector followed
373   // by as many undefined values as needed to create a vector of the same length
374   // as the inserted-to vector.
375   SmallVector<Constant *, 16> ExtendMask;
376   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
377   for (unsigned i = 0; i < NumExtElts; ++i)
378     ExtendMask.push_back(ConstantInt::get(IntType, i));
379   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
380     ExtendMask.push_back(UndefValue::get(IntType));
381
382   Value *ExtVecOp = ExtElt->getVectorOperand();
383   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
384                                         ConstantVector::get(ExtendMask));
385
386   // Insert the new shuffle after the vector operand of the extract is defined
387   // or at the start of the basic block, so any subsequent extracts can use it.
388   bool ReplaceAllExtUsers;
389   if (auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp)) {
390     WideVec->insertAfter(ExtVecOpInst);
391     ReplaceAllExtUsers = true;
392   } else {
393     // TODO: Insert at start of function, so it's always safe to replace all?
394     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
395     ReplaceAllExtUsers = false;
396   }
397
398   // Replace extracts from the original narrow vector with extracts from the new
399   // wide vector.
400   for (User *U : ExtVecOp->users()) {
401     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
402     if (!OldExt ||
403         (!ReplaceAllExtUsers && OldExt->getParent() != WideVec->getParent()))
404       continue;
405     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
406     NewExt->insertAfter(WideVec);
407     IC.ReplaceInstUsesWith(*OldExt, NewExt);
408   }
409 }
410
411 /// We are building a shuffle to create V, which is a sequence of insertelement,
412 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
413 /// not rely on the second vector source. Return a std::pair containing the
414 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
415 /// parameter as required.
416 ///
417 /// Note: we intentionally don't try to fold earlier shuffles since they have
418 /// often been chosen carefully to be efficiently implementable on the target.
419 typedef std::pair<Value *, Value *> ShuffleOps;
420
421 static ShuffleOps collectShuffleElements(Value *V,
422                                          SmallVectorImpl<Constant *> &Mask,
423                                          Value *PermittedRHS,
424                                          InstCombiner &IC) {
425   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
426   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
427
428   if (isa<UndefValue>(V)) {
429     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
430     return std::make_pair(
431         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
432   }
433
434   if (isa<ConstantAggregateZero>(V)) {
435     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
436     return std::make_pair(V, nullptr);
437   }
438
439   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
440     // If this is an insert of an extract from some other vector, include it.
441     Value *VecOp    = IEI->getOperand(0);
442     Value *ScalarOp = IEI->getOperand(1);
443     Value *IdxOp    = IEI->getOperand(2);
444
445     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
446       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
447         unsigned ExtractedIdx =
448           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
449         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
450
451         // Either the extracted from or inserted into vector must be RHSVec,
452         // otherwise we'd end up with a shuffle of three inputs.
453         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
454           Value *RHS = EI->getOperand(0);
455           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
456           assert(LR.second == nullptr || LR.second == RHS);
457
458           if (LR.first->getType() != RHS->getType()) {
459             // Although we are giving up for now, see if we can create extracts
460             // that match the inserts for another round of combining.
461             replaceExtractElements(IEI, EI, IC);
462
463             // We tried our best, but we can't find anything compatible with RHS
464             // further up the chain. Return a trivial shuffle.
465             for (unsigned i = 0; i < NumElts; ++i)
466               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
467             return std::make_pair(V, nullptr);
468           }
469
470           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
471           Mask[InsertedIdx % NumElts] =
472             ConstantInt::get(Type::getInt32Ty(V->getContext()),
473                              NumLHSElts+ExtractedIdx);
474           return std::make_pair(LR.first, RHS);
475         }
476
477         if (VecOp == PermittedRHS) {
478           // We've gone as far as we can: anything on the other side of the
479           // extractelement will already have been converted into a shuffle.
480           unsigned NumLHSElts =
481               EI->getOperand(0)->getType()->getVectorNumElements();
482           for (unsigned i = 0; i != NumElts; ++i)
483             Mask.push_back(ConstantInt::get(
484                 Type::getInt32Ty(V->getContext()),
485                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
486           return std::make_pair(EI->getOperand(0), PermittedRHS);
487         }
488
489         // If this insertelement is a chain that comes from exactly these two
490         // vectors, return the vector and the effective shuffle.
491         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
492             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
493                                          Mask))
494           return std::make_pair(EI->getOperand(0), PermittedRHS);
495       }
496     }
497   }
498
499   // Otherwise, we can't do anything fancy. Return an identity vector.
500   for (unsigned i = 0; i != NumElts; ++i)
501     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
502   return std::make_pair(V, nullptr);
503 }
504
505 /// Try to find redundant insertvalue instructions, like the following ones:
506 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
507 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
508 /// Here the second instruction inserts values at the same indices, as the
509 /// first one, making the first one redundant.
510 /// It should be transformed to:
511 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
512 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
513   bool IsRedundant = false;
514   ArrayRef<unsigned int> FirstIndices = I.getIndices();
515
516   // If there is a chain of insertvalue instructions (each of them except the
517   // last one has only one use and it's another insertvalue insn from this
518   // chain), check if any of the 'children' uses the same indices as the first
519   // instruction. In this case, the first one is redundant.
520   Value *V = &I;
521   unsigned Depth = 0;
522   while (V->hasOneUse() && Depth < 10) {
523     User *U = V->user_back();
524     auto UserInsInst = dyn_cast<InsertValueInst>(U);
525     if (!UserInsInst || U->getOperand(0) != V)
526       break;
527     if (UserInsInst->getIndices() == FirstIndices) {
528       IsRedundant = true;
529       break;
530     }
531     V = UserInsInst;
532     Depth++;
533   }
534
535   if (IsRedundant)
536     return ReplaceInstUsesWith(I, I.getOperand(0));
537   return nullptr;
538 }
539
540 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
541   Value *VecOp    = IE.getOperand(0);
542   Value *ScalarOp = IE.getOperand(1);
543   Value *IdxOp    = IE.getOperand(2);
544
545   // Inserting an undef or into an undefined place, remove this.
546   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
547     ReplaceInstUsesWith(IE, VecOp);
548
549   // If the inserted element was extracted from some other vector, and if the
550   // indexes are constant, try to turn this into a shufflevector operation.
551   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
552     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
553       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
554       unsigned NumExtractVectorElts =
555           EI->getOperand(0)->getType()->getVectorNumElements();
556       unsigned ExtractedIdx =
557         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
558       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
559
560       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
561         return ReplaceInstUsesWith(IE, VecOp);
562
563       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
564         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
565
566       // If we are extracting a value from a vector, then inserting it right
567       // back into the same place, just use the input vector.
568       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
569         return ReplaceInstUsesWith(IE, VecOp);
570
571       // If this insertelement isn't used by some other insertelement, turn it
572       // (and any insertelements it points to), into one big shuffle.
573       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
574         SmallVector<Constant*, 16> Mask;
575         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
576
577         // The proposed shuffle may be trivial, in which case we shouldn't
578         // perform the combine.
579         if (LR.first != &IE && LR.second != &IE) {
580           // We now have a shuffle of LHS, RHS, Mask.
581           if (LR.second == nullptr)
582             LR.second = UndefValue::get(LR.first->getType());
583           return new ShuffleVectorInst(LR.first, LR.second,
584                                        ConstantVector::get(Mask));
585         }
586       }
587     }
588   }
589
590   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
591   APInt UndefElts(VWidth, 0);
592   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
593   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
594     if (V != &IE)
595       return ReplaceInstUsesWith(IE, V);
596     return &IE;
597   }
598
599   return nullptr;
600 }
601
602 /// Return true if we can evaluate the specified expression tree if the vector
603 /// elements were shuffled in a different order.
604 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
605                                 unsigned Depth = 5) {
606   // We can always reorder the elements of a constant.
607   if (isa<Constant>(V))
608     return true;
609
610   // We won't reorder vector arguments. No IPO here.
611   Instruction *I = dyn_cast<Instruction>(V);
612   if (!I) return false;
613
614   // Two users may expect different orders of the elements. Don't try it.
615   if (!I->hasOneUse())
616     return false;
617
618   if (Depth == 0) return false;
619
620   switch (I->getOpcode()) {
621     case Instruction::Add:
622     case Instruction::FAdd:
623     case Instruction::Sub:
624     case Instruction::FSub:
625     case Instruction::Mul:
626     case Instruction::FMul:
627     case Instruction::UDiv:
628     case Instruction::SDiv:
629     case Instruction::FDiv:
630     case Instruction::URem:
631     case Instruction::SRem:
632     case Instruction::FRem:
633     case Instruction::Shl:
634     case Instruction::LShr:
635     case Instruction::AShr:
636     case Instruction::And:
637     case Instruction::Or:
638     case Instruction::Xor:
639     case Instruction::ICmp:
640     case Instruction::FCmp:
641     case Instruction::Trunc:
642     case Instruction::ZExt:
643     case Instruction::SExt:
644     case Instruction::FPToUI:
645     case Instruction::FPToSI:
646     case Instruction::UIToFP:
647     case Instruction::SIToFP:
648     case Instruction::FPTrunc:
649     case Instruction::FPExt:
650     case Instruction::GetElementPtr: {
651       for (Value *Operand : I->operands()) {
652         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
653           return false;
654       }
655       return true;
656     }
657     case Instruction::InsertElement: {
658       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
659       if (!CI) return false;
660       int ElementNumber = CI->getLimitedValue();
661
662       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
663       // can't put an element into multiple indices.
664       bool SeenOnce = false;
665       for (int i = 0, e = Mask.size(); i != e; ++i) {
666         if (Mask[i] == ElementNumber) {
667           if (SeenOnce)
668             return false;
669           SeenOnce = true;
670         }
671       }
672       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
673     }
674   }
675   return false;
676 }
677
678 /// Rebuild a new instruction just like 'I' but with the new operands given.
679 /// In the event of type mismatch, the type of the operands is correct.
680 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
681   // We don't want to use the IRBuilder here because we want the replacement
682   // instructions to appear next to 'I', not the builder's insertion point.
683   switch (I->getOpcode()) {
684     case Instruction::Add:
685     case Instruction::FAdd:
686     case Instruction::Sub:
687     case Instruction::FSub:
688     case Instruction::Mul:
689     case Instruction::FMul:
690     case Instruction::UDiv:
691     case Instruction::SDiv:
692     case Instruction::FDiv:
693     case Instruction::URem:
694     case Instruction::SRem:
695     case Instruction::FRem:
696     case Instruction::Shl:
697     case Instruction::LShr:
698     case Instruction::AShr:
699     case Instruction::And:
700     case Instruction::Or:
701     case Instruction::Xor: {
702       BinaryOperator *BO = cast<BinaryOperator>(I);
703       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
704       BinaryOperator *New =
705           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
706                                  NewOps[0], NewOps[1], "", BO);
707       if (isa<OverflowingBinaryOperator>(BO)) {
708         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
709         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
710       }
711       if (isa<PossiblyExactOperator>(BO)) {
712         New->setIsExact(BO->isExact());
713       }
714       if (isa<FPMathOperator>(BO))
715         New->copyFastMathFlags(I);
716       return New;
717     }
718     case Instruction::ICmp:
719       assert(NewOps.size() == 2 && "icmp with #ops != 2");
720       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
721                           NewOps[0], NewOps[1]);
722     case Instruction::FCmp:
723       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
724       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
725                           NewOps[0], NewOps[1]);
726     case Instruction::Trunc:
727     case Instruction::ZExt:
728     case Instruction::SExt:
729     case Instruction::FPToUI:
730     case Instruction::FPToSI:
731     case Instruction::UIToFP:
732     case Instruction::SIToFP:
733     case Instruction::FPTrunc:
734     case Instruction::FPExt: {
735       // It's possible that the mask has a different number of elements from
736       // the original cast. We recompute the destination type to match the mask.
737       Type *DestTy =
738           VectorType::get(I->getType()->getScalarType(),
739                           NewOps[0]->getType()->getVectorNumElements());
740       assert(NewOps.size() == 1 && "cast with #ops != 1");
741       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
742                               "", I);
743     }
744     case Instruction::GetElementPtr: {
745       Value *Ptr = NewOps[0];
746       ArrayRef<Value*> Idx = NewOps.slice(1);
747       GetElementPtrInst *GEP = GetElementPtrInst::Create(
748           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
749       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
750       return GEP;
751     }
752   }
753   llvm_unreachable("failed to rebuild vector instructions");
754 }
755
756 Value *
757 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
758   // Mask.size() does not need to be equal to the number of vector elements.
759
760   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
761   if (isa<UndefValue>(V)) {
762     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
763                                            Mask.size()));
764   }
765   if (isa<ConstantAggregateZero>(V)) {
766     return ConstantAggregateZero::get(
767                VectorType::get(V->getType()->getScalarType(),
768                                Mask.size()));
769   }
770   if (Constant *C = dyn_cast<Constant>(V)) {
771     SmallVector<Constant *, 16> MaskValues;
772     for (int i = 0, e = Mask.size(); i != e; ++i) {
773       if (Mask[i] == -1)
774         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
775       else
776         MaskValues.push_back(Builder->getInt32(Mask[i]));
777     }
778     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
779                                           ConstantVector::get(MaskValues));
780   }
781
782   Instruction *I = cast<Instruction>(V);
783   switch (I->getOpcode()) {
784     case Instruction::Add:
785     case Instruction::FAdd:
786     case Instruction::Sub:
787     case Instruction::FSub:
788     case Instruction::Mul:
789     case Instruction::FMul:
790     case Instruction::UDiv:
791     case Instruction::SDiv:
792     case Instruction::FDiv:
793     case Instruction::URem:
794     case Instruction::SRem:
795     case Instruction::FRem:
796     case Instruction::Shl:
797     case Instruction::LShr:
798     case Instruction::AShr:
799     case Instruction::And:
800     case Instruction::Or:
801     case Instruction::Xor:
802     case Instruction::ICmp:
803     case Instruction::FCmp:
804     case Instruction::Trunc:
805     case Instruction::ZExt:
806     case Instruction::SExt:
807     case Instruction::FPToUI:
808     case Instruction::FPToSI:
809     case Instruction::UIToFP:
810     case Instruction::SIToFP:
811     case Instruction::FPTrunc:
812     case Instruction::FPExt:
813     case Instruction::Select:
814     case Instruction::GetElementPtr: {
815       SmallVector<Value*, 8> NewOps;
816       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
817       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
818         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
819         NewOps.push_back(V);
820         NeedsRebuild |= (V != I->getOperand(i));
821       }
822       if (NeedsRebuild) {
823         return buildNew(I, NewOps);
824       }
825       return I;
826     }
827     case Instruction::InsertElement: {
828       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
829
830       // The insertelement was inserting at Element. Figure out which element
831       // that becomes after shuffling. The answer is guaranteed to be unique
832       // by CanEvaluateShuffled.
833       bool Found = false;
834       int Index = 0;
835       for (int e = Mask.size(); Index != e; ++Index) {
836         if (Mask[Index] == Element) {
837           Found = true;
838           break;
839         }
840       }
841
842       // If element is not in Mask, no need to handle the operand 1 (element to
843       // be inserted). Just evaluate values in operand 0 according to Mask.
844       if (!Found)
845         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
846
847       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
848       return InsertElementInst::Create(V, I->getOperand(1),
849                                        Builder->getInt32(Index), "", I);
850     }
851   }
852   llvm_unreachable("failed to reorder elements of vector instruction!");
853 }
854
855 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
856                                   bool &isLHSID, bool &isRHSID) {
857   isLHSID = isRHSID = true;
858
859   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
860     if (Mask[i] < 0) continue;  // Ignore undef values.
861     // Is this an identity shuffle of the LHS value?
862     isLHSID &= (Mask[i] == (int)i);
863
864     // Is this an identity shuffle of the RHS value?
865     isRHSID &= (Mask[i]-e == i);
866   }
867 }
868
869 // Returns true if the shuffle is extracting a contiguous range of values from
870 // LHS, for example:
871 //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
872 //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
873 //   Shuffles to:  |EE|FF|GG|HH|
874 //                 +--+--+--+--+
875 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
876                                        SmallVector<int, 16> &Mask) {
877   unsigned LHSElems =
878       cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
879   unsigned MaskElems = Mask.size();
880   unsigned BegIdx = Mask.front();
881   unsigned EndIdx = Mask.back();
882   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
883     return false;
884   for (unsigned I = 0; I != MaskElems; ++I)
885     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
886       return false;
887   return true;
888 }
889
890 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
891   Value *LHS = SVI.getOperand(0);
892   Value *RHS = SVI.getOperand(1);
893   SmallVector<int, 16> Mask = SVI.getShuffleMask();
894   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
895
896   bool MadeChange = false;
897
898   // Undefined shuffle mask -> undefined value.
899   if (isa<UndefValue>(SVI.getOperand(2)))
900     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
901
902   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
903
904   APInt UndefElts(VWidth, 0);
905   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
906   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
907     if (V != &SVI)
908       return ReplaceInstUsesWith(SVI, V);
909     LHS = SVI.getOperand(0);
910     RHS = SVI.getOperand(1);
911     MadeChange = true;
912   }
913
914   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
915
916   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
917   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
918   if (LHS == RHS || isa<UndefValue>(LHS)) {
919     if (isa<UndefValue>(LHS) && LHS == RHS) {
920       // shuffle(undef,undef,mask) -> undef.
921       Value *Result = (VWidth == LHSWidth)
922                       ? LHS : UndefValue::get(SVI.getType());
923       return ReplaceInstUsesWith(SVI, Result);
924     }
925
926     // Remap any references to RHS to use LHS.
927     SmallVector<Constant*, 16> Elts;
928     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
929       if (Mask[i] < 0) {
930         Elts.push_back(UndefValue::get(Int32Ty));
931         continue;
932       }
933
934       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
935           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
936         Mask[i] = -1;     // Turn into undef.
937         Elts.push_back(UndefValue::get(Int32Ty));
938       } else {
939         Mask[i] = Mask[i] % e;  // Force to LHS.
940         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
941       }
942     }
943     SVI.setOperand(0, SVI.getOperand(1));
944     SVI.setOperand(1, UndefValue::get(RHS->getType()));
945     SVI.setOperand(2, ConstantVector::get(Elts));
946     LHS = SVI.getOperand(0);
947     RHS = SVI.getOperand(1);
948     MadeChange = true;
949   }
950
951   if (VWidth == LHSWidth) {
952     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
953     bool isLHSID, isRHSID;
954     recognizeIdentityMask(Mask, isLHSID, isRHSID);
955
956     // Eliminate identity shuffles.
957     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
958     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
959   }
960
961   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
962     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
963     return ReplaceInstUsesWith(SVI, V);
964   }
965
966   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
967   // a non-vector type. We can instead bitcast the original vector followed by
968   // an extract of the desired element:
969   //
970   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
971   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
972   //   %1 = bitcast <4 x i8> %sroa to i32
973   // Becomes:
974   //   %bc = bitcast <16 x i8> %in to <4 x i32>
975   //   %ext = extractelement <4 x i32> %bc, i32 0
976   //
977   // If the shuffle is extracting a contiguous range of values from the input
978   // vector then each use which is a bitcast of the extracted size can be
979   // replaced. This will work if the vector types are compatible, and the begin
980   // index is aligned to a value in the casted vector type. If the begin index
981   // isn't aligned then we can shuffle the original vector (keeping the same
982   // vector type) before extracting.
983   //
984   // This code will bail out if the target type is fundamentally incompatible
985   // with vectors of the source type.
986   //
987   // Example of <16 x i8>, target type i32:
988   // Index range [4,8):         v-----------v Will work.
989   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
990   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
991   //     <4 x i32>: |           |           |           |           |
992   //                +-----------+-----------+-----------+-----------+
993   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
994   // Target type i40:           ^--------------^ Won't work, bail.
995   if (isShuffleExtractingFromLHS(SVI, Mask)) {
996     Value *V = LHS;
997     unsigned MaskElems = Mask.size();
998     unsigned BegIdx = Mask.front();
999     VectorType *SrcTy = cast<VectorType>(V->getType());
1000     unsigned VecBitWidth = SrcTy->getBitWidth();
1001     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1002     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1003     unsigned SrcNumElems = SrcTy->getNumElements();
1004     SmallVector<BitCastInst *, 8> BCs;
1005     DenseMap<Type *, Value *> NewBCs;
1006     for (User *U : SVI.users())
1007       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1008         if (!BC->use_empty())
1009           // Only visit bitcasts that weren't previously handled.
1010           BCs.push_back(BC);
1011     for (BitCastInst *BC : BCs) {
1012       Type *TgtTy = BC->getDestTy();
1013       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1014       if (!TgtElemBitWidth)
1015         continue;
1016       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1017       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1018       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1019       if (!VecBitWidthsEqual)
1020         continue;
1021       if (!VectorType::isValidElementType(TgtTy))
1022         continue;
1023       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1024       if (!BegIsAligned) {
1025         // Shuffle the input so [0,NumElements) contains the output, and
1026         // [NumElems,SrcNumElems) is undef.
1027         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1028                                                 UndefValue::get(Int32Ty));
1029         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1030           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1031         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1032                                          ConstantVector::get(ShuffleMask),
1033                                          SVI.getName() + ".extract");
1034         BegIdx = 0;
1035       }
1036       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1037       assert(SrcElemsPerTgtElem);
1038       BegIdx /= SrcElemsPerTgtElem;
1039       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1040       auto *NewBC =
1041           BCAlreadyExists
1042               ? NewBCs[CastSrcTy]
1043               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1044       if (!BCAlreadyExists)
1045         NewBCs[CastSrcTy] = NewBC;
1046       auto *Ext = Builder->CreateExtractElement(
1047           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1048       // The shufflevector isn't being replaced: the bitcast that used it
1049       // is. InstCombine will visit the newly-created instructions.
1050       ReplaceInstUsesWith(*BC, Ext);
1051       MadeChange = true;
1052     }
1053   }
1054
1055   // If the LHS is a shufflevector itself, see if we can combine it with this
1056   // one without producing an unusual shuffle.
1057   // Cases that might be simplified:
1058   // 1.
1059   // x1=shuffle(v1,v2,mask1)
1060   //  x=shuffle(x1,undef,mask)
1061   //        ==>
1062   //  x=shuffle(v1,undef,newMask)
1063   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1064   // 2.
1065   // x1=shuffle(v1,undef,mask1)
1066   //  x=shuffle(x1,x2,mask)
1067   // where v1.size() == mask1.size()
1068   //        ==>
1069   //  x=shuffle(v1,x2,newMask)
1070   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1071   // 3.
1072   // x2=shuffle(v2,undef,mask2)
1073   //  x=shuffle(x1,x2,mask)
1074   // where v2.size() == mask2.size()
1075   //        ==>
1076   //  x=shuffle(x1,v2,newMask)
1077   // newMask[i] = (mask[i] < x1.size())
1078   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1079   // 4.
1080   // x1=shuffle(v1,undef,mask1)
1081   // x2=shuffle(v2,undef,mask2)
1082   //  x=shuffle(x1,x2,mask)
1083   // where v1.size() == v2.size()
1084   //        ==>
1085   //  x=shuffle(v1,v2,newMask)
1086   // newMask[i] = (mask[i] < x1.size())
1087   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1088   //
1089   // Here we are really conservative:
1090   // we are absolutely afraid of producing a shuffle mask not in the input
1091   // program, because the code gen may not be smart enough to turn a merged
1092   // shuffle into two specific shuffles: it may produce worse code.  As such,
1093   // we only merge two shuffles if the result is either a splat or one of the
1094   // input shuffle masks.  In this case, merging the shuffles just removes
1095   // one instruction, which we know is safe.  This is good for things like
1096   // turning: (splat(splat)) -> splat, or
1097   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1098   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1099   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1100   if (LHSShuffle)
1101     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
1102       LHSShuffle = nullptr;
1103   if (RHSShuffle)
1104     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
1105       RHSShuffle = nullptr;
1106   if (!LHSShuffle && !RHSShuffle)
1107     return MadeChange ? &SVI : nullptr;
1108
1109   Value* LHSOp0 = nullptr;
1110   Value* LHSOp1 = nullptr;
1111   Value* RHSOp0 = nullptr;
1112   unsigned LHSOp0Width = 0;
1113   unsigned RHSOp0Width = 0;
1114   if (LHSShuffle) {
1115     LHSOp0 = LHSShuffle->getOperand(0);
1116     LHSOp1 = LHSShuffle->getOperand(1);
1117     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1118   }
1119   if (RHSShuffle) {
1120     RHSOp0 = RHSShuffle->getOperand(0);
1121     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1122   }
1123   Value* newLHS = LHS;
1124   Value* newRHS = RHS;
1125   if (LHSShuffle) {
1126     // case 1
1127     if (isa<UndefValue>(RHS)) {
1128       newLHS = LHSOp0;
1129       newRHS = LHSOp1;
1130     }
1131     // case 2 or 4
1132     else if (LHSOp0Width == LHSWidth) {
1133       newLHS = LHSOp0;
1134     }
1135   }
1136   // case 3 or 4
1137   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1138     newRHS = RHSOp0;
1139   }
1140   // case 4
1141   if (LHSOp0 == RHSOp0) {
1142     newLHS = LHSOp0;
1143     newRHS = nullptr;
1144   }
1145
1146   if (newLHS == LHS && newRHS == RHS)
1147     return MadeChange ? &SVI : nullptr;
1148
1149   SmallVector<int, 16> LHSMask;
1150   SmallVector<int, 16> RHSMask;
1151   if (newLHS != LHS)
1152     LHSMask = LHSShuffle->getShuffleMask();
1153   if (RHSShuffle && newRHS != RHS)
1154     RHSMask = RHSShuffle->getShuffleMask();
1155
1156   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1157   SmallVector<int, 16> newMask;
1158   bool isSplat = true;
1159   int SplatElt = -1;
1160   // Create a new mask for the new ShuffleVectorInst so that the new
1161   // ShuffleVectorInst is equivalent to the original one.
1162   for (unsigned i = 0; i < VWidth; ++i) {
1163     int eltMask;
1164     if (Mask[i] < 0) {
1165       // This element is an undef value.
1166       eltMask = -1;
1167     } else if (Mask[i] < (int)LHSWidth) {
1168       // This element is from left hand side vector operand.
1169       //
1170       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1171       // new mask value for the element.
1172       if (newLHS != LHS) {
1173         eltMask = LHSMask[Mask[i]];
1174         // If the value selected is an undef value, explicitly specify it
1175         // with a -1 mask value.
1176         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1177           eltMask = -1;
1178       } else
1179         eltMask = Mask[i];
1180     } else {
1181       // This element is from right hand side vector operand
1182       //
1183       // If the value selected is an undef value, explicitly specify it
1184       // with a -1 mask value. (case 1)
1185       if (isa<UndefValue>(RHS))
1186         eltMask = -1;
1187       // If RHS is going to be replaced (case 3 or 4), calculate the
1188       // new mask value for the element.
1189       else if (newRHS != RHS) {
1190         eltMask = RHSMask[Mask[i]-LHSWidth];
1191         // If the value selected is an undef value, explicitly specify it
1192         // with a -1 mask value.
1193         if (eltMask >= (int)RHSOp0Width) {
1194           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1195                  && "should have been check above");
1196           eltMask = -1;
1197         }
1198       } else
1199         eltMask = Mask[i]-LHSWidth;
1200
1201       // If LHS's width is changed, shift the mask value accordingly.
1202       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1203       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1204       // If newRHS == newLHS, we want to remap any references from newRHS to
1205       // newLHS so that we can properly identify splats that may occur due to
1206       // obfuscation across the two vectors.
1207       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1208         eltMask += newLHSWidth;
1209     }
1210
1211     // Check if this could still be a splat.
1212     if (eltMask >= 0) {
1213       if (SplatElt >= 0 && SplatElt != eltMask)
1214         isSplat = false;
1215       SplatElt = eltMask;
1216     }
1217
1218     newMask.push_back(eltMask);
1219   }
1220
1221   // If the result mask is equal to one of the original shuffle masks,
1222   // or is a splat, do the replacement.
1223   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1224     SmallVector<Constant*, 16> Elts;
1225     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1226       if (newMask[i] < 0) {
1227         Elts.push_back(UndefValue::get(Int32Ty));
1228       } else {
1229         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1230       }
1231     }
1232     if (!newRHS)
1233       newRHS = UndefValue::get(newLHS->getType());
1234     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1235   }
1236
1237   // If the result mask is an identity, replace uses of this instruction with
1238   // corresponding argument.
1239   bool isLHSID, isRHSID;
1240   recognizeIdentityMask(newMask, isLHSID, isRHSID);
1241   if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1242   if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
1243
1244   return MadeChange ? &SVI : nullptr;
1245 }