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