1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements instcombine for ExtractElement, InsertElement and
10 // ShuffleVector.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/VectorUtils.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Transforms/InstCombine/InstCombiner.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <iterator>
42 #include <utility>
43 
44 #define DEBUG_TYPE "instcombine"
45 
46 using namespace llvm;
47 using namespace PatternMatch;
48 
49 STATISTIC(NumAggregateReconstructionsSimplified,
50           "Number of aggregate reconstructions turned into reuse of the "
51           "original aggregate");
52 
53 /// Return true if the value is cheaper to scalarize than it is to leave as a
54 /// vector operation. If the extract index \p EI is a constant integer then
55 /// some operations may be cheap to scalarize.
56 ///
57 /// FIXME: It's possible to create more instructions than previously existed.
58 static bool cheapToScalarize(Value *V, Value *EI) {
59   ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
60 
61   // If we can pick a scalar constant value out of a vector, that is free.
62   if (auto *C = dyn_cast<Constant>(V))
63     return CEI || C->getSplatValue();
64 
65   if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
66     ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
67     // Index needs to be lower than the minimum size of the vector, because
68     // for scalable vector, the vector size is known at run time.
69     return CEI->getValue().ult(EC.getKnownMinValue());
70   }
71 
72   // An insertelement to the same constant index as our extract will simplify
73   // to the scalar inserted element. An insertelement to a different constant
74   // index is irrelevant to our extract.
75   if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
76     return CEI;
77 
78   if (match(V, m_OneUse(m_Load(m_Value()))))
79     return true;
80 
81   if (match(V, m_OneUse(m_UnOp())))
82     return true;
83 
84   Value *V0, *V1;
85   if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
86     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
87       return true;
88 
89   CmpInst::Predicate UnusedPred;
90   if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
91     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
92       return true;
93 
94   return false;
95 }
96 
97 // If we have a PHI node with a vector type that is only used to feed
98 // itself and be an operand of extractelement at a constant location,
99 // try to replace the PHI of the vector type with a PHI of a scalar type.
100 Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
101                                             PHINode *PN) {
102   SmallVector<Instruction *, 2> Extracts;
103   // The users we want the PHI to have are:
104   // 1) The EI ExtractElement (we already know this)
105   // 2) Possibly more ExtractElements with the same index.
106   // 3) Another operand, which will feed back into the PHI.
107   Instruction *PHIUser = nullptr;
108   for (auto U : PN->users()) {
109     if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
110       if (EI.getIndexOperand() == EU->getIndexOperand())
111         Extracts.push_back(EU);
112       else
113         return nullptr;
114     } else if (!PHIUser) {
115       PHIUser = cast<Instruction>(U);
116     } else {
117       return nullptr;
118     }
119   }
120 
121   if (!PHIUser)
122     return nullptr;
123 
124   // Verify that this PHI user has one use, which is the PHI itself,
125   // and that it is a binary operation which is cheap to scalarize.
126   // otherwise return nullptr.
127   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
128       !(isa<BinaryOperator>(PHIUser)) ||
129       !cheapToScalarize(PHIUser, EI.getIndexOperand()))
130     return nullptr;
131 
132   // Create a scalar PHI node that will replace the vector PHI node
133   // just before the current PHI node.
134   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
135       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
136   // Scalarize each PHI operand.
137   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
138     Value *PHIInVal = PN->getIncomingValue(i);
139     BasicBlock *inBB = PN->getIncomingBlock(i);
140     Value *Elt = EI.getIndexOperand();
141     // If the operand is the PHI induction variable:
142     if (PHIInVal == PHIUser) {
143       // Scalarize the binary operation. Its first operand is the
144       // scalar PHI, and the second operand is extracted from the other
145       // vector operand.
146       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
147       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
148       Value *Op = InsertNewInstWith(
149           ExtractElementInst::Create(B0->getOperand(opId), Elt,
150                                      B0->getOperand(opId)->getName() + ".Elt"),
151           *B0);
152       Value *newPHIUser = InsertNewInstWith(
153           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
154                                                 scalarPHI, Op, B0), *B0);
155       scalarPHI->addIncoming(newPHIUser, inBB);
156     } else {
157       // Scalarize PHI input:
158       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
159       // Insert the new instruction into the predecessor basic block.
160       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
161       BasicBlock::iterator InsertPos;
162       if (pos && !isa<PHINode>(pos)) {
163         InsertPos = ++pos->getIterator();
164       } else {
165         InsertPos = inBB->getFirstInsertionPt();
166       }
167 
168       InsertNewInstWith(newEI, *InsertPos);
169 
170       scalarPHI->addIncoming(newEI, inBB);
171     }
172   }
173 
174   for (auto E : Extracts)
175     replaceInstUsesWith(*E, scalarPHI);
176 
177   return &EI;
178 }
179 
180 Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
181   Value *X;
182   uint64_t ExtIndexC;
183   if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
184       !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
185     return nullptr;
186 
187   ElementCount NumElts =
188       cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
189   Type *DestTy = Ext.getType();
190   bool IsBigEndian = DL.isBigEndian();
191 
192   // If we are casting an integer to vector and extracting a portion, that is
193   // a shift-right and truncate.
194   // TODO: Allow FP dest type by casting the trunc to FP?
195   if (X->getType()->isIntegerTy() && DestTy->isIntegerTy() &&
196       isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) {
197     assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
198            "Expected fixed vector type for bitcast from scalar integer");
199 
200     // Big endian requires adjusting the extract index since MSB is at index 0.
201     // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
202     // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
203     if (IsBigEndian)
204       ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
205     unsigned ShiftAmountC = ExtIndexC * DestTy->getPrimitiveSizeInBits();
206     if (!ShiftAmountC || Ext.getVectorOperand()->hasOneUse()) {
207       Value *Lshr = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
208       return new TruncInst(Lshr, DestTy);
209     }
210   }
211 
212   if (!X->getType()->isVectorTy())
213     return nullptr;
214 
215   // If this extractelement is using a bitcast from a vector of the same number
216   // of elements, see if we can find the source element from the source vector:
217   // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
218   auto *SrcTy = cast<VectorType>(X->getType());
219   ElementCount NumSrcElts = SrcTy->getElementCount();
220   if (NumSrcElts == NumElts)
221     if (Value *Elt = findScalarElement(X, ExtIndexC))
222       return new BitCastInst(Elt, DestTy);
223 
224   assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
225          "Src and Dst must be the same sort of vector type");
226 
227   // If the source elements are wider than the destination, try to shift and
228   // truncate a subset of scalar bits of an insert op.
229   if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
230     Value *Scalar;
231     Value *Vec;
232     uint64_t InsIndexC;
233     if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
234                               m_ConstantInt(InsIndexC))))
235       return nullptr;
236 
237     // The extract must be from the subset of vector elements that we inserted
238     // into. Example: if we inserted element 1 of a <2 x i64> and we are
239     // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
240     // of elements 4-7 of the bitcasted vector.
241     unsigned NarrowingRatio =
242         NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
243 
244     if (ExtIndexC / NarrowingRatio != InsIndexC) {
245       // Remove insertelement, if we don't use the inserted element.
246       // extractelement (bitcast (insertelement (Vec, b)), a) ->
247       // extractelement (bitcast (Vec), a)
248       // FIXME: this should be removed to SimplifyDemandedVectorElts,
249       // once scale vectors are supported.
250       if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
251         Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
252         return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
253       }
254       return nullptr;
255     }
256 
257     // We are extracting part of the original scalar. How that scalar is
258     // inserted into the vector depends on the endian-ness. Example:
259     //              Vector Byte Elt Index:    0  1  2  3  4  5  6  7
260     //                                       +--+--+--+--+--+--+--+--+
261     // inselt <2 x i32> V, <i32> S, 1:       |V0|V1|V2|V3|S0|S1|S2|S3|
262     // extelt <4 x i16> V', 3:               |                 |S2|S3|
263     //                                       +--+--+--+--+--+--+--+--+
264     // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
265     // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
266     // In this example, we must right-shift little-endian. Big-endian is just a
267     // truncate.
268     unsigned Chunk = ExtIndexC % NarrowingRatio;
269     if (IsBigEndian)
270       Chunk = NarrowingRatio - 1 - Chunk;
271 
272     // Bail out if this is an FP vector to FP vector sequence. That would take
273     // more instructions than we started with unless there is no shift, and it
274     // may not be handled as well in the backend.
275     bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
276     bool NeedDestBitcast = DestTy->isFloatingPointTy();
277     if (NeedSrcBitcast && NeedDestBitcast)
278       return nullptr;
279 
280     unsigned SrcWidth = SrcTy->getScalarSizeInBits();
281     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
282     unsigned ShAmt = Chunk * DestWidth;
283 
284     // TODO: This limitation is more strict than necessary. We could sum the
285     // number of new instructions and subtract the number eliminated to know if
286     // we can proceed.
287     if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
288       if (NeedSrcBitcast || NeedDestBitcast)
289         return nullptr;
290 
291     if (NeedSrcBitcast) {
292       Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
293       Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
294     }
295 
296     if (ShAmt) {
297       // Bail out if we could end with more instructions than we started with.
298       if (!Ext.getVectorOperand()->hasOneUse())
299         return nullptr;
300       Scalar = Builder.CreateLShr(Scalar, ShAmt);
301     }
302 
303     if (NeedDestBitcast) {
304       Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
305       return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
306     }
307     return new TruncInst(Scalar, DestTy);
308   }
309 
310   return nullptr;
311 }
312 
313 /// Find elements of V demanded by UserInstr.
314 static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
315   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
316 
317   // Conservatively assume that all elements are needed.
318   APInt UsedElts(APInt::getAllOnes(VWidth));
319 
320   switch (UserInstr->getOpcode()) {
321   case Instruction::ExtractElement: {
322     ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
323     assert(EEI->getVectorOperand() == V);
324     ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
325     if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
326       UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
327     }
328     break;
329   }
330   case Instruction::ShuffleVector: {
331     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
332     unsigned MaskNumElts =
333         cast<FixedVectorType>(UserInstr->getType())->getNumElements();
334 
335     UsedElts = APInt(VWidth, 0);
336     for (unsigned i = 0; i < MaskNumElts; i++) {
337       unsigned MaskVal = Shuffle->getMaskValue(i);
338       if (MaskVal == -1u || MaskVal >= 2 * VWidth)
339         continue;
340       if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
341         UsedElts.setBit(MaskVal);
342       if (Shuffle->getOperand(1) == V &&
343           ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
344         UsedElts.setBit(MaskVal - VWidth);
345     }
346     break;
347   }
348   default:
349     break;
350   }
351   return UsedElts;
352 }
353 
354 /// Find union of elements of V demanded by all its users.
355 /// If it is known by querying findDemandedEltsBySingleUser that
356 /// no user demands an element of V, then the corresponding bit
357 /// remains unset in the returned value.
358 static APInt findDemandedEltsByAllUsers(Value *V) {
359   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
360 
361   APInt UnionUsedElts(VWidth, 0);
362   for (const Use &U : V->uses()) {
363     if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
364       UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
365     } else {
366       UnionUsedElts = APInt::getAllOnes(VWidth);
367       break;
368     }
369 
370     if (UnionUsedElts.isAllOnes())
371       break;
372   }
373 
374   return UnionUsedElts;
375 }
376 
377 /// Given a constant index for a extractelement or insertelement instruction,
378 /// return it with the canonical type if it isn't already canonical.  We
379 /// arbitrarily pick 64 bit as our canonical type.  The actual bitwidth doesn't
380 /// matter, we just want a consistent type to simplify CSE.
381 ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
382   const unsigned IndexBW = IndexC->getType()->getBitWidth();
383   if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
384     return nullptr;
385   return ConstantInt::get(IndexC->getContext(),
386                           IndexC->getValue().zextOrTrunc(64));
387 }
388 
389 Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
390   Value *SrcVec = EI.getVectorOperand();
391   Value *Index = EI.getIndexOperand();
392   if (Value *V = simplifyExtractElementInst(SrcVec, Index,
393                                             SQ.getWithInstruction(&EI)))
394     return replaceInstUsesWith(EI, V);
395 
396   // If extracting a specified index from the vector, see if we can recursively
397   // find a previously computed scalar that was inserted into the vector.
398   auto *IndexC = dyn_cast<ConstantInt>(Index);
399   if (IndexC) {
400     // Canonicalize type of constant indices to i64 to simplify CSE
401     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
402       return replaceOperand(EI, 1, NewIdx);
403 
404     ElementCount EC = EI.getVectorOperandType()->getElementCount();
405     unsigned NumElts = EC.getKnownMinValue();
406 
407     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
408       Intrinsic::ID IID = II->getIntrinsicID();
409       // Index needs to be lower than the minimum size of the vector, because
410       // for scalable vector, the vector size is known at run time.
411       if (IID == Intrinsic::experimental_stepvector &&
412           IndexC->getValue().ult(NumElts)) {
413         Type *Ty = EI.getType();
414         unsigned BitWidth = Ty->getIntegerBitWidth();
415         Value *Idx;
416         // Return index when its value does not exceed the allowed limit
417         // for the element type of the vector, otherwise return undefined.
418         if (IndexC->getValue().getActiveBits() <= BitWidth)
419           Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
420         else
421           Idx = UndefValue::get(Ty);
422         return replaceInstUsesWith(EI, Idx);
423       }
424     }
425 
426     // InstSimplify should handle cases where the index is invalid.
427     // For fixed-length vector, it's invalid to extract out-of-range element.
428     if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
429       return nullptr;
430 
431     if (Instruction *I = foldBitcastExtElt(EI))
432       return I;
433 
434     // If there's a vector PHI feeding a scalar use through this extractelement
435     // instruction, try to scalarize the PHI.
436     if (auto *Phi = dyn_cast<PHINode>(SrcVec))
437       if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
438         return ScalarPHI;
439   }
440 
441   // TODO come up with a n-ary matcher that subsumes both unary and
442   // binary matchers.
443   UnaryOperator *UO;
444   if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
445     // extelt (unop X), Index --> unop (extelt X, Index)
446     Value *X = UO->getOperand(0);
447     Value *E = Builder.CreateExtractElement(X, Index);
448     return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
449   }
450 
451   BinaryOperator *BO;
452   if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
453     // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
454     Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
455     Value *E0 = Builder.CreateExtractElement(X, Index);
456     Value *E1 = Builder.CreateExtractElement(Y, Index);
457     return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
458   }
459 
460   Value *X, *Y;
461   CmpInst::Predicate Pred;
462   if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
463       cheapToScalarize(SrcVec, Index)) {
464     // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
465     Value *E0 = Builder.CreateExtractElement(X, Index);
466     Value *E1 = Builder.CreateExtractElement(Y, Index);
467     return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
468   }
469 
470   if (auto *I = dyn_cast<Instruction>(SrcVec)) {
471     if (auto *IE = dyn_cast<InsertElementInst>(I)) {
472       // instsimplify already handled the case where the indices are constants
473       // and equal by value, if both are constants, they must not be the same
474       // value, extract from the pre-inserted value instead.
475       if (isa<Constant>(IE->getOperand(2)) && IndexC)
476         return replaceOperand(EI, 0, IE->getOperand(0));
477     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
478       auto *VecType = cast<VectorType>(GEP->getType());
479       ElementCount EC = VecType->getElementCount();
480       uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
481       if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
482         // Find out why we have a vector result - these are a few examples:
483         //  1. We have a scalar pointer and a vector of indices, or
484         //  2. We have a vector of pointers and a scalar index, or
485         //  3. We have a vector of pointers and a vector of indices, etc.
486         // Here we only consider combining when there is exactly one vector
487         // operand, since the optimization is less obviously a win due to
488         // needing more than one extractelements.
489 
490         unsigned VectorOps =
491             llvm::count_if(GEP->operands(), [](const Value *V) {
492               return isa<VectorType>(V->getType());
493             });
494         if (VectorOps == 1) {
495           Value *NewPtr = GEP->getPointerOperand();
496           if (isa<VectorType>(NewPtr->getType()))
497             NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
498 
499           SmallVector<Value *> NewOps;
500           for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
501             Value *Op = GEP->getOperand(I);
502             if (isa<VectorType>(Op->getType()))
503               NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
504             else
505               NewOps.push_back(Op);
506           }
507 
508           GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
509               GEP->getSourceElementType(), NewPtr, NewOps);
510           NewGEP->setIsInBounds(GEP->isInBounds());
511           return NewGEP;
512         }
513       }
514     } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
515       // If this is extracting an element from a shufflevector, figure out where
516       // it came from and extract from the appropriate input element instead.
517       // Restrict the following transformation to fixed-length vector.
518       if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
519         int SrcIdx =
520             SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
521         Value *Src;
522         unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
523                                 ->getNumElements();
524 
525         if (SrcIdx < 0)
526           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
527         if (SrcIdx < (int)LHSWidth)
528           Src = SVI->getOperand(0);
529         else {
530           SrcIdx -= LHSWidth;
531           Src = SVI->getOperand(1);
532         }
533         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
534         return ExtractElementInst::Create(
535             Src, ConstantInt::get(Int32Ty, SrcIdx, false));
536       }
537     } else if (auto *CI = dyn_cast<CastInst>(I)) {
538       // Canonicalize extractelement(cast) -> cast(extractelement).
539       // Bitcasts can change the number of vector elements, and they cost
540       // nothing.
541       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
542         Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
543         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
544       }
545     }
546   }
547 
548   // Run demanded elements after other transforms as this can drop flags on
549   // binops.  If there's two paths to the same final result, we prefer the
550   // one which doesn't force us to drop flags.
551   if (IndexC) {
552     ElementCount EC = EI.getVectorOperandType()->getElementCount();
553     unsigned NumElts = EC.getKnownMinValue();
554     // This instruction only demands the single element from the input vector.
555     // Skip for scalable type, the number of elements is unknown at
556     // compile-time.
557     if (!EC.isScalable() && NumElts != 1) {
558       // If the input vector has a single use, simplify it based on this use
559       // property.
560       if (SrcVec->hasOneUse()) {
561         APInt UndefElts(NumElts, 0);
562         APInt DemandedElts(NumElts, 0);
563         DemandedElts.setBit(IndexC->getZExtValue());
564         if (Value *V =
565                 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
566           return replaceOperand(EI, 0, V);
567       } else {
568         // If the input vector has multiple uses, simplify it based on a union
569         // of all elements used.
570         APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
571         if (!DemandedElts.isAllOnes()) {
572           APInt UndefElts(NumElts, 0);
573           if (Value *V = SimplifyDemandedVectorElts(
574                   SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
575                   true /* AllowMultipleUsers */)) {
576             if (V != SrcVec) {
577               SrcVec->replaceAllUsesWith(V);
578               return &EI;
579             }
580           }
581         }
582       }
583     }
584   }
585   return nullptr;
586 }
587 
588 /// If V is a shuffle of values that ONLY returns elements from either LHS or
589 /// RHS, return the shuffle mask and true. Otherwise, return false.
590 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
591                                          SmallVectorImpl<int> &Mask) {
592   assert(LHS->getType() == RHS->getType() &&
593          "Invalid CollectSingleShuffleElements");
594   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
595 
596   if (match(V, m_Undef())) {
597     Mask.assign(NumElts, -1);
598     return true;
599   }
600 
601   if (V == LHS) {
602     for (unsigned i = 0; i != NumElts; ++i)
603       Mask.push_back(i);
604     return true;
605   }
606 
607   if (V == RHS) {
608     for (unsigned i = 0; i != NumElts; ++i)
609       Mask.push_back(i + NumElts);
610     return true;
611   }
612 
613   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
614     // If this is an insert of an extract from some other vector, include it.
615     Value *VecOp    = IEI->getOperand(0);
616     Value *ScalarOp = IEI->getOperand(1);
617     Value *IdxOp    = IEI->getOperand(2);
618 
619     if (!isa<ConstantInt>(IdxOp))
620       return false;
621     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
622 
623     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
624       // We can handle this if the vector we are inserting into is
625       // transitively ok.
626       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
627         // If so, update the mask to reflect the inserted undef.
628         Mask[InsertedIdx] = -1;
629         return true;
630       }
631     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
632       if (isa<ConstantInt>(EI->getOperand(1))) {
633         unsigned ExtractedIdx =
634         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
635         unsigned NumLHSElts =
636             cast<FixedVectorType>(LHS->getType())->getNumElements();
637 
638         // This must be extracting from either LHS or RHS.
639         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
640           // We can handle this if the vector we are inserting into is
641           // transitively ok.
642           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
643             // If so, update the mask to reflect the inserted value.
644             if (EI->getOperand(0) == LHS) {
645               Mask[InsertedIdx % NumElts] = ExtractedIdx;
646             } else {
647               assert(EI->getOperand(0) == RHS);
648               Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
649             }
650             return true;
651           }
652         }
653       }
654     }
655   }
656 
657   return false;
658 }
659 
660 /// If we have insertion into a vector that is wider than the vector that we
661 /// are extracting from, try to widen the source vector to allow a single
662 /// shufflevector to replace one or more insert/extract pairs.
663 static void replaceExtractElements(InsertElementInst *InsElt,
664                                    ExtractElementInst *ExtElt,
665                                    InstCombinerImpl &IC) {
666   auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
667   auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
668   unsigned NumInsElts = InsVecType->getNumElements();
669   unsigned NumExtElts = ExtVecType->getNumElements();
670 
671   // The inserted-to vector must be wider than the extracted-from vector.
672   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
673       NumExtElts >= NumInsElts)
674     return;
675 
676   // Create a shuffle mask to widen the extended-from vector using poison
677   // values. The mask selects all of the values of the original vector followed
678   // by as many poison values as needed to create a vector of the same length
679   // as the inserted-to vector.
680   SmallVector<int, 16> ExtendMask;
681   for (unsigned i = 0; i < NumExtElts; ++i)
682     ExtendMask.push_back(i);
683   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
684     ExtendMask.push_back(-1);
685 
686   Value *ExtVecOp = ExtElt->getVectorOperand();
687   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
688   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
689                                    ? ExtVecOpInst->getParent()
690                                    : ExtElt->getParent();
691 
692   // TODO: This restriction matches the basic block check below when creating
693   // new extractelement instructions. If that limitation is removed, this one
694   // could also be removed. But for now, we just bail out to ensure that we
695   // will replace the extractelement instruction that is feeding our
696   // insertelement instruction. This allows the insertelement to then be
697   // replaced by a shufflevector. If the insertelement is not replaced, we can
698   // induce infinite looping because there's an optimization for extractelement
699   // that will delete our widening shuffle. This would trigger another attempt
700   // here to create that shuffle, and we spin forever.
701   if (InsertionBlock != InsElt->getParent())
702     return;
703 
704   // TODO: This restriction matches the check in visitInsertElementInst() and
705   // prevents an infinite loop caused by not turning the extract/insert pair
706   // into a shuffle. We really should not need either check, but we're lacking
707   // folds for shufflevectors because we're afraid to generate shuffle masks
708   // that the backend can't handle.
709   if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
710     return;
711 
712   auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
713 
714   // Insert the new shuffle after the vector operand of the extract is defined
715   // (as long as it's not a PHI) or at the start of the basic block of the
716   // extract, so any subsequent extracts in the same basic block can use it.
717   // TODO: Insert before the earliest ExtractElementInst that is replaced.
718   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
719     WideVec->insertAfter(ExtVecOpInst);
720   else
721     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
722 
723   // Replace extracts from the original narrow vector with extracts from the new
724   // wide vector.
725   for (User *U : ExtVecOp->users()) {
726     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
727     if (!OldExt || OldExt->getParent() != WideVec->getParent())
728       continue;
729     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
730     NewExt->insertAfter(OldExt);
731     IC.replaceInstUsesWith(*OldExt, NewExt);
732   }
733 }
734 
735 /// We are building a shuffle to create V, which is a sequence of insertelement,
736 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
737 /// not rely on the second vector source. Return a std::pair containing the
738 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
739 /// parameter as required.
740 ///
741 /// Note: we intentionally don't try to fold earlier shuffles since they have
742 /// often been chosen carefully to be efficiently implementable on the target.
743 using ShuffleOps = std::pair<Value *, Value *>;
744 
745 static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
746                                          Value *PermittedRHS,
747                                          InstCombinerImpl &IC) {
748   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
749   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
750 
751   if (match(V, m_Undef())) {
752     Mask.assign(NumElts, -1);
753     return std::make_pair(
754         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
755   }
756 
757   if (isa<ConstantAggregateZero>(V)) {
758     Mask.assign(NumElts, 0);
759     return std::make_pair(V, nullptr);
760   }
761 
762   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
763     // If this is an insert of an extract from some other vector, include it.
764     Value *VecOp    = IEI->getOperand(0);
765     Value *ScalarOp = IEI->getOperand(1);
766     Value *IdxOp    = IEI->getOperand(2);
767 
768     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
769       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
770         unsigned ExtractedIdx =
771           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
772         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
773 
774         // Either the extracted from or inserted into vector must be RHSVec,
775         // otherwise we'd end up with a shuffle of three inputs.
776         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
777           Value *RHS = EI->getOperand(0);
778           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
779           assert(LR.second == nullptr || LR.second == RHS);
780 
781           if (LR.first->getType() != RHS->getType()) {
782             // Although we are giving up for now, see if we can create extracts
783             // that match the inserts for another round of combining.
784             replaceExtractElements(IEI, EI, IC);
785 
786             // We tried our best, but we can't find anything compatible with RHS
787             // further up the chain. Return a trivial shuffle.
788             for (unsigned i = 0; i < NumElts; ++i)
789               Mask[i] = i;
790             return std::make_pair(V, nullptr);
791           }
792 
793           unsigned NumLHSElts =
794               cast<FixedVectorType>(RHS->getType())->getNumElements();
795           Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
796           return std::make_pair(LR.first, RHS);
797         }
798 
799         if (VecOp == PermittedRHS) {
800           // We've gone as far as we can: anything on the other side of the
801           // extractelement will already have been converted into a shuffle.
802           unsigned NumLHSElts =
803               cast<FixedVectorType>(EI->getOperand(0)->getType())
804                   ->getNumElements();
805           for (unsigned i = 0; i != NumElts; ++i)
806             Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
807           return std::make_pair(EI->getOperand(0), PermittedRHS);
808         }
809 
810         // If this insertelement is a chain that comes from exactly these two
811         // vectors, return the vector and the effective shuffle.
812         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
813             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
814                                          Mask))
815           return std::make_pair(EI->getOperand(0), PermittedRHS);
816       }
817     }
818   }
819 
820   // Otherwise, we can't do anything fancy. Return an identity vector.
821   for (unsigned i = 0; i != NumElts; ++i)
822     Mask.push_back(i);
823   return std::make_pair(V, nullptr);
824 }
825 
826 /// Look for chain of insertvalue's that fully define an aggregate, and trace
827 /// back the values inserted, see if they are all were extractvalue'd from
828 /// the same source aggregate from the exact same element indexes.
829 /// If they were, just reuse the source aggregate.
830 /// This potentially deals with PHI indirections.
831 Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
832     InsertValueInst &OrigIVI) {
833   Type *AggTy = OrigIVI.getType();
834   unsigned NumAggElts;
835   switch (AggTy->getTypeID()) {
836   case Type::StructTyID:
837     NumAggElts = AggTy->getStructNumElements();
838     break;
839   case Type::ArrayTyID:
840     NumAggElts = AggTy->getArrayNumElements();
841     break;
842   default:
843     llvm_unreachable("Unhandled aggregate type?");
844   }
845 
846   // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
847   // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
848   // FIXME: any interesting patterns to be caught with larger limit?
849   assert(NumAggElts > 0 && "Aggregate should have elements.");
850   if (NumAggElts > 2)
851     return nullptr;
852 
853   static constexpr auto NotFound = None;
854   static constexpr auto FoundMismatch = nullptr;
855 
856   // Try to find a value of each element of an aggregate.
857   // FIXME: deal with more complex, not one-dimensional, aggregate types
858   SmallVector<Optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
859 
860   // Do we know values for each element of the aggregate?
861   auto KnowAllElts = [&AggElts]() {
862     return all_of(AggElts,
863                   [](Optional<Instruction *> Elt) { return Elt != NotFound; });
864   };
865 
866   int Depth = 0;
867 
868   // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
869   // every element being overwritten twice, which should never happen.
870   static const int DepthLimit = 2 * NumAggElts;
871 
872   // Recurse up the chain of `insertvalue` aggregate operands until either we've
873   // reconstructed full initializer or can't visit any more `insertvalue`'s.
874   for (InsertValueInst *CurrIVI = &OrigIVI;
875        Depth < DepthLimit && CurrIVI && !KnowAllElts();
876        CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
877                        ++Depth) {
878     auto *InsertedValue =
879         dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
880     if (!InsertedValue)
881       return nullptr; // Inserted value must be produced by an instruction.
882 
883     ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
884 
885     // Don't bother with more than single-level aggregates.
886     if (Indices.size() != 1)
887       return nullptr; // FIXME: deal with more complex aggregates?
888 
889     // Now, we may have already previously recorded the value for this element
890     // of an aggregate. If we did, that means the CurrIVI will later be
891     // overwritten with the already-recorded value. But if not, let's record it!
892     Optional<Instruction *> &Elt = AggElts[Indices.front()];
893     Elt = Elt.value_or(InsertedValue);
894 
895     // FIXME: should we handle chain-terminating undef base operand?
896   }
897 
898   // Was that sufficient to deduce the full initializer for the aggregate?
899   if (!KnowAllElts())
900     return nullptr; // Give up then.
901 
902   // We now want to find the source[s] of the aggregate elements we've found.
903   // And with "source" we mean the original aggregate[s] from which
904   // the inserted elements were extracted. This may require PHI translation.
905 
906   enum class AggregateDescription {
907     /// When analyzing the value that was inserted into an aggregate, we did
908     /// not manage to find defining `extractvalue` instruction to analyze.
909     NotFound,
910     /// When analyzing the value that was inserted into an aggregate, we did
911     /// manage to find defining `extractvalue` instruction[s], and everything
912     /// matched perfectly - aggregate type, element insertion/extraction index.
913     Found,
914     /// When analyzing the value that was inserted into an aggregate, we did
915     /// manage to find defining `extractvalue` instruction, but there was
916     /// a mismatch: either the source type from which the extraction was didn't
917     /// match the aggregate type into which the insertion was,
918     /// or the extraction/insertion channels mismatched,
919     /// or different elements had different source aggregates.
920     FoundMismatch
921   };
922   auto Describe = [](Optional<Value *> SourceAggregate) {
923     if (SourceAggregate == NotFound)
924       return AggregateDescription::NotFound;
925     if (*SourceAggregate == FoundMismatch)
926       return AggregateDescription::FoundMismatch;
927     return AggregateDescription::Found;
928   };
929 
930   // Given the value \p Elt that was being inserted into element \p EltIdx of an
931   // aggregate AggTy, see if \p Elt was originally defined by an
932   // appropriate extractvalue (same element index, same aggregate type).
933   // If found, return the source aggregate from which the extraction was.
934   // If \p PredBB is provided, does PHI translation of an \p Elt first.
935   auto FindSourceAggregate =
936       [&](Instruction *Elt, unsigned EltIdx, Optional<BasicBlock *> UseBB,
937           Optional<BasicBlock *> PredBB) -> Optional<Value *> {
938     // For now(?), only deal with, at most, a single level of PHI indirection.
939     if (UseBB && PredBB)
940       Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
941     // FIXME: deal with multiple levels of PHI indirection?
942 
943     // Did we find an extraction?
944     auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
945     if (!EVI)
946       return NotFound;
947 
948     Value *SourceAggregate = EVI->getAggregateOperand();
949 
950     // Is the extraction from the same type into which the insertion was?
951     if (SourceAggregate->getType() != AggTy)
952       return FoundMismatch;
953     // And the element index doesn't change between extraction and insertion?
954     if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
955       return FoundMismatch;
956 
957     return SourceAggregate; // AggregateDescription::Found
958   };
959 
960   // Given elements AggElts that were constructing an aggregate OrigIVI,
961   // see if we can find appropriate source aggregate for each of the elements,
962   // and see it's the same aggregate for each element. If so, return it.
963   auto FindCommonSourceAggregate =
964       [&](Optional<BasicBlock *> UseBB,
965           Optional<BasicBlock *> PredBB) -> Optional<Value *> {
966     Optional<Value *> SourceAggregate;
967 
968     for (auto I : enumerate(AggElts)) {
969       assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
970              "We don't store nullptr in SourceAggregate!");
971       assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
972                  (I.index() != 0) &&
973              "SourceAggregate should be valid after the first element,");
974 
975       // For this element, is there a plausible source aggregate?
976       // FIXME: we could special-case undef element, IFF we know that in the
977       //        source aggregate said element isn't poison.
978       Optional<Value *> SourceAggregateForElement =
979           FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
980 
981       // Okay, what have we found? Does that correlate with previous findings?
982 
983       // Regardless of whether or not we have previously found source
984       // aggregate for previous elements (if any), if we didn't find one for
985       // this element, passthrough whatever we have just found.
986       if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
987         return SourceAggregateForElement;
988 
989       // Okay, we have found source aggregate for this element.
990       // Let's see what we already know from previous elements, if any.
991       switch (Describe(SourceAggregate)) {
992       case AggregateDescription::NotFound:
993         // This is apparently the first element that we have examined.
994         SourceAggregate = SourceAggregateForElement; // Record the aggregate!
995         continue; // Great, now look at next element.
996       case AggregateDescription::Found:
997         // We have previously already successfully examined other elements.
998         // Is this the same source aggregate we've found for other elements?
999         if (*SourceAggregateForElement != *SourceAggregate)
1000           return FoundMismatch;
1001         continue; // Still the same aggregate, look at next element.
1002       case AggregateDescription::FoundMismatch:
1003         llvm_unreachable("Can't happen. We would have early-exited then.");
1004       };
1005     }
1006 
1007     assert(Describe(SourceAggregate) == AggregateDescription::Found &&
1008            "Must be a valid Value");
1009     return *SourceAggregate;
1010   };
1011 
1012   Optional<Value *> SourceAggregate;
1013 
1014   // Can we find the source aggregate without looking at predecessors?
1015   SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/None, /*PredBB=*/None);
1016   if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1017     if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1018       return nullptr; // Conflicting source aggregates!
1019     ++NumAggregateReconstructionsSimplified;
1020     return replaceInstUsesWith(OrigIVI, *SourceAggregate);
1021   }
1022 
1023   // Okay, apparently we need to look at predecessors.
1024 
1025   // We should be smart about picking the "use" basic block, which will be the
1026   // merge point for aggregate, where we'll insert the final PHI that will be
1027   // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
1028   // We should look in which blocks each of the AggElts is being defined,
1029   // they all should be defined in the same basic block.
1030   BasicBlock *UseBB = nullptr;
1031 
1032   for (const Optional<Instruction *> &I : AggElts) {
1033     BasicBlock *BB = (*I)->getParent();
1034     // If it's the first instruction we've encountered, record the basic block.
1035     if (!UseBB) {
1036       UseBB = BB;
1037       continue;
1038     }
1039     // Otherwise, this must be the same basic block we've seen previously.
1040     if (UseBB != BB)
1041       return nullptr;
1042   }
1043 
1044   // If *all* of the elements are basic-block-independent, meaning they are
1045   // either function arguments, or constant expressions, then if we didn't
1046   // handle them without predecessor-aware handling, we won't handle them now.
1047   if (!UseBB)
1048     return nullptr;
1049 
1050   // If we didn't manage to find source aggregate without looking at
1051   // predecessors, and there are no predecessors to look at, then we're done.
1052   if (pred_empty(UseBB))
1053     return nullptr;
1054 
1055   // Arbitrary predecessor count limit.
1056   static const int PredCountLimit = 64;
1057 
1058   // Cache the (non-uniqified!) list of predecessors in a vector,
1059   // checking the limit at the same time for efficiency.
1060   SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
1061   for (BasicBlock *Pred : predecessors(UseBB)) {
1062     // Don't bother if there are too many predecessors.
1063     if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
1064       return nullptr;
1065     Preds.emplace_back(Pred);
1066   }
1067 
1068   // For each predecessor, what is the source aggregate,
1069   // from which all the elements were originally extracted from?
1070   // Note that we want for the map to have stable iteration order!
1071   SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
1072   for (BasicBlock *Pred : Preds) {
1073     std::pair<decltype(SourceAggregates)::iterator, bool> IV =
1074         SourceAggregates.insert({Pred, nullptr});
1075     // Did we already evaluate this predecessor?
1076     if (!IV.second)
1077       continue;
1078 
1079     // Let's hope that when coming from predecessor Pred, all elements of the
1080     // aggregate produced by OrigIVI must have been originally extracted from
1081     // the same aggregate. Is that so? Can we find said original aggregate?
1082     SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1083     if (Describe(SourceAggregate) != AggregateDescription::Found)
1084       return nullptr; // Give up.
1085     IV.first->second = *SourceAggregate;
1086   }
1087 
1088   // All good! Now we just need to thread the source aggregates here.
1089   // Note that we have to insert the new PHI here, ourselves, because we can't
1090   // rely on InstCombinerImpl::run() inserting it into the right basic block.
1091   // Note that the same block can be a predecessor more than once,
1092   // and we need to preserve that invariant for the PHI node.
1093   BuilderTy::InsertPointGuard Guard(Builder);
1094   Builder.SetInsertPoint(UseBB->getFirstNonPHI());
1095   auto *PHI =
1096       Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
1097   for (BasicBlock *Pred : Preds)
1098     PHI->addIncoming(SourceAggregates[Pred], Pred);
1099 
1100   ++NumAggregateReconstructionsSimplified;
1101   return replaceInstUsesWith(OrigIVI, PHI);
1102 }
1103 
1104 /// Try to find redundant insertvalue instructions, like the following ones:
1105 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
1106 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
1107 /// Here the second instruction inserts values at the same indices, as the
1108 /// first one, making the first one redundant.
1109 /// It should be transformed to:
1110 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
1111 Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
1112   bool IsRedundant = false;
1113   ArrayRef<unsigned int> FirstIndices = I.getIndices();
1114 
1115   // If there is a chain of insertvalue instructions (each of them except the
1116   // last one has only one use and it's another insertvalue insn from this
1117   // chain), check if any of the 'children' uses the same indices as the first
1118   // instruction. In this case, the first one is redundant.
1119   Value *V = &I;
1120   unsigned Depth = 0;
1121   while (V->hasOneUse() && Depth < 10) {
1122     User *U = V->user_back();
1123     auto UserInsInst = dyn_cast<InsertValueInst>(U);
1124     if (!UserInsInst || U->getOperand(0) != V)
1125       break;
1126     if (UserInsInst->getIndices() == FirstIndices) {
1127       IsRedundant = true;
1128       break;
1129     }
1130     V = UserInsInst;
1131     Depth++;
1132   }
1133 
1134   if (IsRedundant)
1135     return replaceInstUsesWith(I, I.getOperand(0));
1136 
1137   if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
1138     return NewI;
1139 
1140   return nullptr;
1141 }
1142 
1143 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
1144   // Can not analyze scalable type, the number of elements is not a compile-time
1145   // constant.
1146   if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
1147     return false;
1148 
1149   int MaskSize = Shuf.getShuffleMask().size();
1150   int VecSize =
1151       cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
1152 
1153   // A vector select does not change the size of the operands.
1154   if (MaskSize != VecSize)
1155     return false;
1156 
1157   // Each mask element must be undefined or choose a vector element from one of
1158   // the source operands without crossing vector lanes.
1159   for (int i = 0; i != MaskSize; ++i) {
1160     int Elt = Shuf.getMaskValue(i);
1161     if (Elt != -1 && Elt != i && Elt != i + VecSize)
1162       return false;
1163   }
1164 
1165   return true;
1166 }
1167 
1168 /// Turn a chain of inserts that splats a value into an insert + shuffle:
1169 /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
1170 /// shufflevector(insertelt(X, %k, 0), poison, zero)
1171 static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
1172   // We are interested in the last insert in a chain. So if this insert has a
1173   // single user and that user is an insert, bail.
1174   if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
1175     return nullptr;
1176 
1177   VectorType *VecTy = InsElt.getType();
1178   // Can not handle scalable type, the number of elements is not a compile-time
1179   // constant.
1180   if (isa<ScalableVectorType>(VecTy))
1181     return nullptr;
1182   unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1183 
1184   // Do not try to do this for a one-element vector, since that's a nop,
1185   // and will cause an inf-loop.
1186   if (NumElements == 1)
1187     return nullptr;
1188 
1189   Value *SplatVal = InsElt.getOperand(1);
1190   InsertElementInst *CurrIE = &InsElt;
1191   SmallBitVector ElementPresent(NumElements, false);
1192   InsertElementInst *FirstIE = nullptr;
1193 
1194   // Walk the chain backwards, keeping track of which indices we inserted into,
1195   // until we hit something that isn't an insert of the splatted value.
1196   while (CurrIE) {
1197     auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
1198     if (!Idx || CurrIE->getOperand(1) != SplatVal)
1199       return nullptr;
1200 
1201     auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
1202     // Check none of the intermediate steps have any additional uses, except
1203     // for the root insertelement instruction, which can be re-used, if it
1204     // inserts at position 0.
1205     if (CurrIE != &InsElt &&
1206         (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
1207       return nullptr;
1208 
1209     ElementPresent[Idx->getZExtValue()] = true;
1210     FirstIE = CurrIE;
1211     CurrIE = NextIE;
1212   }
1213 
1214   // If this is just a single insertelement (not a sequence), we are done.
1215   if (FirstIE == &InsElt)
1216     return nullptr;
1217 
1218   // If we are not inserting into an undef vector, make sure we've seen an
1219   // insert into every element.
1220   // TODO: If the base vector is not undef, it might be better to create a splat
1221   //       and then a select-shuffle (blend) with the base vector.
1222   if (!match(FirstIE->getOperand(0), m_Undef()))
1223     if (!ElementPresent.all())
1224       return nullptr;
1225 
1226   // Create the insert + shuffle.
1227   Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
1228   PoisonValue *PoisonVec = PoisonValue::get(VecTy);
1229   Constant *Zero = ConstantInt::get(Int32Ty, 0);
1230   if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
1231     FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
1232 
1233   // Splat from element 0, but replace absent elements with undef in the mask.
1234   SmallVector<int, 16> Mask(NumElements, 0);
1235   for (unsigned i = 0; i != NumElements; ++i)
1236     if (!ElementPresent[i])
1237       Mask[i] = -1;
1238 
1239   return new ShuffleVectorInst(FirstIE, Mask);
1240 }
1241 
1242 /// Try to fold an insert element into an existing splat shuffle by changing
1243 /// the shuffle's mask to include the index of this insert element.
1244 static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
1245   // Check if the vector operand of this insert is a canonical splat shuffle.
1246   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1247   if (!Shuf || !Shuf->isZeroEltSplat())
1248     return nullptr;
1249 
1250   // Bail out early if shuffle is scalable type. The number of elements in
1251   // shuffle mask is unknown at compile-time.
1252   if (isa<ScalableVectorType>(Shuf->getType()))
1253     return nullptr;
1254 
1255   // Check for a constant insertion index.
1256   uint64_t IdxC;
1257   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1258     return nullptr;
1259 
1260   // Check if the splat shuffle's input is the same as this insert's scalar op.
1261   Value *X = InsElt.getOperand(1);
1262   Value *Op0 = Shuf->getOperand(0);
1263   if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
1264     return nullptr;
1265 
1266   // Replace the shuffle mask element at the index of this insert with a zero.
1267   // For example:
1268   // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1269   //   --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
1270   unsigned NumMaskElts =
1271       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1272   SmallVector<int, 16> NewMask(NumMaskElts);
1273   for (unsigned i = 0; i != NumMaskElts; ++i)
1274     NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1275 
1276   return new ShuffleVectorInst(Op0, NewMask);
1277 }
1278 
1279 /// Try to fold an extract+insert element into an existing identity shuffle by
1280 /// changing the shuffle's mask to include the index of this insert element.
1281 static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
1282   // Check if the vector operand of this insert is an identity shuffle.
1283   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1284   if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
1285       !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1286     return nullptr;
1287 
1288   // Bail out early if shuffle is scalable type. The number of elements in
1289   // shuffle mask is unknown at compile-time.
1290   if (isa<ScalableVectorType>(Shuf->getType()))
1291     return nullptr;
1292 
1293   // Check for a constant insertion index.
1294   uint64_t IdxC;
1295   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1296     return nullptr;
1297 
1298   // Check if this insert's scalar op is extracted from the identity shuffle's
1299   // input vector.
1300   Value *Scalar = InsElt.getOperand(1);
1301   Value *X = Shuf->getOperand(0);
1302   if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
1303     return nullptr;
1304 
1305   // Replace the shuffle mask element at the index of this extract+insert with
1306   // that same index value.
1307   // For example:
1308   // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
1309   unsigned NumMaskElts =
1310       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1311   SmallVector<int, 16> NewMask(NumMaskElts);
1312   ArrayRef<int> OldMask = Shuf->getShuffleMask();
1313   for (unsigned i = 0; i != NumMaskElts; ++i) {
1314     if (i != IdxC) {
1315       // All mask elements besides the inserted element remain the same.
1316       NewMask[i] = OldMask[i];
1317     } else if (OldMask[i] == (int)IdxC) {
1318       // If the mask element was already set, there's nothing to do
1319       // (demanded elements analysis may unset it later).
1320       return nullptr;
1321     } else {
1322       assert(OldMask[i] == UndefMaskElem &&
1323              "Unexpected shuffle mask element for identity shuffle");
1324       NewMask[i] = IdxC;
1325     }
1326   }
1327 
1328   return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
1329 }
1330 
1331 /// If we have an insertelement instruction feeding into another insertelement
1332 /// and the 2nd is inserting a constant into the vector, canonicalize that
1333 /// constant insertion before the insertion of a variable:
1334 ///
1335 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
1336 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
1337 ///
1338 /// This has the potential of eliminating the 2nd insertelement instruction
1339 /// via constant folding of the scalar constant into a vector constant.
1340 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
1341                                      InstCombiner::BuilderTy &Builder) {
1342   auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
1343   if (!InsElt1 || !InsElt1->hasOneUse())
1344     return nullptr;
1345 
1346   Value *X, *Y;
1347   Constant *ScalarC;
1348   ConstantInt *IdxC1, *IdxC2;
1349   if (match(InsElt1->getOperand(0), m_Value(X)) &&
1350       match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
1351       match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
1352       match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
1353       match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
1354     Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
1355     return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
1356   }
1357 
1358   return nullptr;
1359 }
1360 
1361 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
1362 /// --> shufflevector X, CVec', Mask'
1363 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
1364   auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
1365   // Bail out if the parent has more than one use. In that case, we'd be
1366   // replacing the insertelt with a shuffle, and that's not a clear win.
1367   if (!Inst || !Inst->hasOneUse())
1368     return nullptr;
1369   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
1370     // The shuffle must have a constant vector operand. The insertelt must have
1371     // a constant scalar being inserted at a constant position in the vector.
1372     Constant *ShufConstVec, *InsEltScalar;
1373     uint64_t InsEltIndex;
1374     if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
1375         !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
1376         !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
1377       return nullptr;
1378 
1379     // Adding an element to an arbitrary shuffle could be expensive, but a
1380     // shuffle that selects elements from vectors without crossing lanes is
1381     // assumed cheap.
1382     // If we're just adding a constant into that shuffle, it will still be
1383     // cheap.
1384     if (!isShuffleEquivalentToSelect(*Shuf))
1385       return nullptr;
1386 
1387     // From the above 'select' check, we know that the mask has the same number
1388     // of elements as the vector input operands. We also know that each constant
1389     // input element is used in its lane and can not be used more than once by
1390     // the shuffle. Therefore, replace the constant in the shuffle's constant
1391     // vector with the insertelt constant. Replace the constant in the shuffle's
1392     // mask vector with the insertelt index plus the length of the vector
1393     // (because the constant vector operand of a shuffle is always the 2nd
1394     // operand).
1395     ArrayRef<int> Mask = Shuf->getShuffleMask();
1396     unsigned NumElts = Mask.size();
1397     SmallVector<Constant *, 16> NewShufElts(NumElts);
1398     SmallVector<int, 16> NewMaskElts(NumElts);
1399     for (unsigned I = 0; I != NumElts; ++I) {
1400       if (I == InsEltIndex) {
1401         NewShufElts[I] = InsEltScalar;
1402         NewMaskElts[I] = InsEltIndex + NumElts;
1403       } else {
1404         // Copy over the existing values.
1405         NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1406         NewMaskElts[I] = Mask[I];
1407       }
1408 
1409       // Bail if we failed to find an element.
1410       if (!NewShufElts[I])
1411         return nullptr;
1412     }
1413 
1414     // Create new operands for a shuffle that includes the constant of the
1415     // original insertelt. The old shuffle will be dead now.
1416     return new ShuffleVectorInst(Shuf->getOperand(0),
1417                                  ConstantVector::get(NewShufElts), NewMaskElts);
1418   } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
1419     // Transform sequences of insertelements ops with constant data/indexes into
1420     // a single shuffle op.
1421     // Can not handle scalable type, the number of elements needed to create
1422     // shuffle mask is not a compile-time constant.
1423     if (isa<ScalableVectorType>(InsElt.getType()))
1424       return nullptr;
1425     unsigned NumElts =
1426         cast<FixedVectorType>(InsElt.getType())->getNumElements();
1427 
1428     uint64_t InsertIdx[2];
1429     Constant *Val[2];
1430     if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
1431         !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
1432         !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
1433         !match(IEI->getOperand(1), m_Constant(Val[1])))
1434       return nullptr;
1435     SmallVector<Constant *, 16> Values(NumElts);
1436     SmallVector<int, 16> Mask(NumElts);
1437     auto ValI = std::begin(Val);
1438     // Generate new constant vector and mask.
1439     // We have 2 values/masks from the insertelements instructions. Insert them
1440     // into new value/mask vectors.
1441     for (uint64_t I : InsertIdx) {
1442       if (!Values[I]) {
1443         Values[I] = *ValI;
1444         Mask[I] = NumElts + I;
1445       }
1446       ++ValI;
1447     }
1448     // Remaining values are filled with 'undef' values.
1449     for (unsigned I = 0; I < NumElts; ++I) {
1450       if (!Values[I]) {
1451         Values[I] = UndefValue::get(InsElt.getType()->getElementType());
1452         Mask[I] = I;
1453       }
1454     }
1455     // Create new operands for a shuffle that includes the constant of the
1456     // original insertelt.
1457     return new ShuffleVectorInst(IEI->getOperand(0),
1458                                  ConstantVector::get(Values), Mask);
1459   }
1460   return nullptr;
1461 }
1462 
1463 /// If both the base vector and the inserted element are extended from the same
1464 /// type, do the insert element in the narrow source type followed by extend.
1465 /// TODO: This can be extended to include other cast opcodes, but particularly
1466 ///       if we create a wider insertelement, make sure codegen is not harmed.
1467 static Instruction *narrowInsElt(InsertElementInst &InsElt,
1468                                  InstCombiner::BuilderTy &Builder) {
1469   // We are creating a vector extend. If the original vector extend has another
1470   // use, that would mean we end up with 2 vector extends, so avoid that.
1471   // TODO: We could ease the use-clause to "if at least one op has one use"
1472   //       (assuming that the source types match - see next TODO comment).
1473   Value *Vec = InsElt.getOperand(0);
1474   if (!Vec->hasOneUse())
1475     return nullptr;
1476 
1477   Value *Scalar = InsElt.getOperand(1);
1478   Value *X, *Y;
1479   CastInst::CastOps CastOpcode;
1480   if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1481     CastOpcode = Instruction::FPExt;
1482   else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1483     CastOpcode = Instruction::SExt;
1484   else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1485     CastOpcode = Instruction::ZExt;
1486   else
1487     return nullptr;
1488 
1489   // TODO: We can allow mismatched types by creating an intermediate cast.
1490   if (X->getType()->getScalarType() != Y->getType())
1491     return nullptr;
1492 
1493   // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1494   Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1495   return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1496 }
1497 
1498 Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
1499   Value *VecOp    = IE.getOperand(0);
1500   Value *ScalarOp = IE.getOperand(1);
1501   Value *IdxOp    = IE.getOperand(2);
1502 
1503   if (auto *V = simplifyInsertElementInst(
1504           VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1505     return replaceInstUsesWith(IE, V);
1506 
1507   // Canonicalize type of constant indices to i64 to simplify CSE
1508   if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp))
1509     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1510       return replaceOperand(IE, 2, NewIdx);
1511 
1512   // If the scalar is bitcast and inserted into undef, do the insert in the
1513   // source type followed by bitcast.
1514   // TODO: Generalize for insert into any constant, not just undef?
1515   Value *ScalarSrc;
1516   if (match(VecOp, m_Undef()) &&
1517       match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1518       (ScalarSrc->getType()->isIntegerTy() ||
1519        ScalarSrc->getType()->isFloatingPointTy())) {
1520     // inselt undef, (bitcast ScalarSrc), IdxOp -->
1521     //   bitcast (inselt undef, ScalarSrc, IdxOp)
1522     Type *ScalarTy = ScalarSrc->getType();
1523     Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1524     UndefValue *NewUndef = UndefValue::get(VecTy);
1525     Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1526     return new BitCastInst(NewInsElt, IE.getType());
1527   }
1528 
1529   // If the vector and scalar are both bitcast from the same element type, do
1530   // the insert in that source type followed by bitcast.
1531   Value *VecSrc;
1532   if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1533       match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1534       (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1535       VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1536       cast<VectorType>(VecSrc->getType())->getElementType() ==
1537           ScalarSrc->getType()) {
1538     // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1539     //   bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1540     Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1541     return new BitCastInst(NewInsElt, IE.getType());
1542   }
1543 
1544   // If the inserted element was extracted from some other fixed-length vector
1545   // and both indexes are valid constants, try to turn this into a shuffle.
1546   // Can not handle scalable vector type, the number of elements needed to
1547   // create shuffle mask is not a compile-time constant.
1548   uint64_t InsertedIdx, ExtractedIdx;
1549   Value *ExtVecOp;
1550   if (isa<FixedVectorType>(IE.getType()) &&
1551       match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1552       match(ScalarOp,
1553             m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1554       isa<FixedVectorType>(ExtVecOp->getType()) &&
1555       ExtractedIdx <
1556           cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
1557     // TODO: Looking at the user(s) to determine if this insert is a
1558     // fold-to-shuffle opportunity does not match the usual instcombine
1559     // constraints. We should decide if the transform is worthy based only
1560     // on this instruction and its operands, but that may not work currently.
1561     //
1562     // Here, we are trying to avoid creating shuffles before reaching
1563     // the end of a chain of extract-insert pairs. This is complicated because
1564     // we do not generally form arbitrary shuffle masks in instcombine
1565     // (because those may codegen poorly), but collectShuffleElements() does
1566     // exactly that.
1567     //
1568     // The rules for determining what is an acceptable target-independent
1569     // shuffle mask are fuzzy because they evolve based on the backend's
1570     // capabilities and real-world impact.
1571     auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1572       if (!Insert.hasOneUse())
1573         return true;
1574       auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1575       if (!InsertUser)
1576         return true;
1577       return false;
1578     };
1579 
1580     // Try to form a shuffle from a chain of extract-insert ops.
1581     if (isShuffleRootCandidate(IE)) {
1582       SmallVector<int, 16> Mask;
1583       ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
1584 
1585       // The proposed shuffle may be trivial, in which case we shouldn't
1586       // perform the combine.
1587       if (LR.first != &IE && LR.second != &IE) {
1588         // We now have a shuffle of LHS, RHS, Mask.
1589         if (LR.second == nullptr)
1590           LR.second = UndefValue::get(LR.first->getType());
1591         return new ShuffleVectorInst(LR.first, LR.second, Mask);
1592       }
1593     }
1594   }
1595 
1596   if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1597     unsigned VWidth = VecTy->getNumElements();
1598     APInt UndefElts(VWidth, 0);
1599     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1600     if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
1601       if (V != &IE)
1602         return replaceInstUsesWith(IE, V);
1603       return &IE;
1604     }
1605   }
1606 
1607   if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
1608     return Shuf;
1609 
1610   if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
1611     return NewInsElt;
1612 
1613   if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
1614     return Broadcast;
1615 
1616   if (Instruction *Splat = foldInsEltIntoSplat(IE))
1617     return Splat;
1618 
1619   if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1620     return IdentityShuf;
1621 
1622   if (Instruction *Ext = narrowInsElt(IE, Builder))
1623     return Ext;
1624 
1625   return nullptr;
1626 }
1627 
1628 /// Return true if we can evaluate the specified expression tree if the vector
1629 /// elements were shuffled in a different order.
1630 static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
1631                                 unsigned Depth = 5) {
1632   // We can always reorder the elements of a constant.
1633   if (isa<Constant>(V))
1634     return true;
1635 
1636   // We won't reorder vector arguments. No IPO here.
1637   Instruction *I = dyn_cast<Instruction>(V);
1638   if (!I) return false;
1639 
1640   // Two users may expect different orders of the elements. Don't try it.
1641   if (!I->hasOneUse())
1642     return false;
1643 
1644   if (Depth == 0) return false;
1645 
1646   switch (I->getOpcode()) {
1647     case Instruction::UDiv:
1648     case Instruction::SDiv:
1649     case Instruction::URem:
1650     case Instruction::SRem:
1651       // Propagating an undefined shuffle mask element to integer div/rem is not
1652       // allowed because those opcodes can create immediate undefined behavior
1653       // from an undefined element in an operand.
1654       if (llvm::is_contained(Mask, -1))
1655         return false;
1656       LLVM_FALLTHROUGH;
1657     case Instruction::Add:
1658     case Instruction::FAdd:
1659     case Instruction::Sub:
1660     case Instruction::FSub:
1661     case Instruction::Mul:
1662     case Instruction::FMul:
1663     case Instruction::FDiv:
1664     case Instruction::FRem:
1665     case Instruction::Shl:
1666     case Instruction::LShr:
1667     case Instruction::AShr:
1668     case Instruction::And:
1669     case Instruction::Or:
1670     case Instruction::Xor:
1671     case Instruction::ICmp:
1672     case Instruction::FCmp:
1673     case Instruction::Trunc:
1674     case Instruction::ZExt:
1675     case Instruction::SExt:
1676     case Instruction::FPToUI:
1677     case Instruction::FPToSI:
1678     case Instruction::UIToFP:
1679     case Instruction::SIToFP:
1680     case Instruction::FPTrunc:
1681     case Instruction::FPExt:
1682     case Instruction::GetElementPtr: {
1683       // Bail out if we would create longer vector ops. We could allow creating
1684       // longer vector ops, but that may result in more expensive codegen.
1685       Type *ITy = I->getType();
1686       if (ITy->isVectorTy() &&
1687           Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
1688         return false;
1689       for (Value *Operand : I->operands()) {
1690         if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
1691           return false;
1692       }
1693       return true;
1694     }
1695     case Instruction::InsertElement: {
1696       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1697       if (!CI) return false;
1698       int ElementNumber = CI->getLimitedValue();
1699 
1700       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1701       // can't put an element into multiple indices.
1702       bool SeenOnce = false;
1703       for (int i = 0, e = Mask.size(); i != e; ++i) {
1704         if (Mask[i] == ElementNumber) {
1705           if (SeenOnce)
1706             return false;
1707           SeenOnce = true;
1708         }
1709       }
1710       return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
1711     }
1712   }
1713   return false;
1714 }
1715 
1716 /// Rebuild a new instruction just like 'I' but with the new operands given.
1717 /// In the event of type mismatch, the type of the operands is correct.
1718 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
1719   // We don't want to use the IRBuilder here because we want the replacement
1720   // instructions to appear next to 'I', not the builder's insertion point.
1721   switch (I->getOpcode()) {
1722     case Instruction::Add:
1723     case Instruction::FAdd:
1724     case Instruction::Sub:
1725     case Instruction::FSub:
1726     case Instruction::Mul:
1727     case Instruction::FMul:
1728     case Instruction::UDiv:
1729     case Instruction::SDiv:
1730     case Instruction::FDiv:
1731     case Instruction::URem:
1732     case Instruction::SRem:
1733     case Instruction::FRem:
1734     case Instruction::Shl:
1735     case Instruction::LShr:
1736     case Instruction::AShr:
1737     case Instruction::And:
1738     case Instruction::Or:
1739     case Instruction::Xor: {
1740       BinaryOperator *BO = cast<BinaryOperator>(I);
1741       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1742       BinaryOperator *New =
1743           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1744                                  NewOps[0], NewOps[1], "", BO);
1745       if (isa<OverflowingBinaryOperator>(BO)) {
1746         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1747         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1748       }
1749       if (isa<PossiblyExactOperator>(BO)) {
1750         New->setIsExact(BO->isExact());
1751       }
1752       if (isa<FPMathOperator>(BO))
1753         New->copyFastMathFlags(I);
1754       return New;
1755     }
1756     case Instruction::ICmp:
1757       assert(NewOps.size() == 2 && "icmp with #ops != 2");
1758       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1759                           NewOps[0], NewOps[1]);
1760     case Instruction::FCmp:
1761       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1762       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1763                           NewOps[0], NewOps[1]);
1764     case Instruction::Trunc:
1765     case Instruction::ZExt:
1766     case Instruction::SExt:
1767     case Instruction::FPToUI:
1768     case Instruction::FPToSI:
1769     case Instruction::UIToFP:
1770     case Instruction::SIToFP:
1771     case Instruction::FPTrunc:
1772     case Instruction::FPExt: {
1773       // It's possible that the mask has a different number of elements from
1774       // the original cast. We recompute the destination type to match the mask.
1775       Type *DestTy = VectorType::get(
1776           I->getType()->getScalarType(),
1777           cast<VectorType>(NewOps[0]->getType())->getElementCount());
1778       assert(NewOps.size() == 1 && "cast with #ops != 1");
1779       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1780                               "", I);
1781     }
1782     case Instruction::GetElementPtr: {
1783       Value *Ptr = NewOps[0];
1784       ArrayRef<Value*> Idx = NewOps.slice(1);
1785       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1786           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
1787       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1788       return GEP;
1789     }
1790   }
1791   llvm_unreachable("failed to rebuild vector instructions");
1792 }
1793 
1794 static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1795   // Mask.size() does not need to be equal to the number of vector elements.
1796 
1797   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
1798   Type *EltTy = V->getType()->getScalarType();
1799   Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
1800   if (match(V, m_Undef()))
1801     return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
1802 
1803   if (isa<ConstantAggregateZero>(V))
1804     return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
1805 
1806   if (Constant *C = dyn_cast<Constant>(V))
1807     return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
1808                                           Mask);
1809 
1810   Instruction *I = cast<Instruction>(V);
1811   switch (I->getOpcode()) {
1812     case Instruction::Add:
1813     case Instruction::FAdd:
1814     case Instruction::Sub:
1815     case Instruction::FSub:
1816     case Instruction::Mul:
1817     case Instruction::FMul:
1818     case Instruction::UDiv:
1819     case Instruction::SDiv:
1820     case Instruction::FDiv:
1821     case Instruction::URem:
1822     case Instruction::SRem:
1823     case Instruction::FRem:
1824     case Instruction::Shl:
1825     case Instruction::LShr:
1826     case Instruction::AShr:
1827     case Instruction::And:
1828     case Instruction::Or:
1829     case Instruction::Xor:
1830     case Instruction::ICmp:
1831     case Instruction::FCmp:
1832     case Instruction::Trunc:
1833     case Instruction::ZExt:
1834     case Instruction::SExt:
1835     case Instruction::FPToUI:
1836     case Instruction::FPToSI:
1837     case Instruction::UIToFP:
1838     case Instruction::SIToFP:
1839     case Instruction::FPTrunc:
1840     case Instruction::FPExt:
1841     case Instruction::Select:
1842     case Instruction::GetElementPtr: {
1843       SmallVector<Value*, 8> NewOps;
1844       bool NeedsRebuild =
1845           (Mask.size() !=
1846            cast<FixedVectorType>(I->getType())->getNumElements());
1847       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1848         Value *V;
1849         // Recursively call evaluateInDifferentElementOrder on vector arguments
1850         // as well. E.g. GetElementPtr may have scalar operands even if the
1851         // return value is a vector, so we need to examine the operand type.
1852         if (I->getOperand(i)->getType()->isVectorTy())
1853           V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
1854         else
1855           V = I->getOperand(i);
1856         NewOps.push_back(V);
1857         NeedsRebuild |= (V != I->getOperand(i));
1858       }
1859       if (NeedsRebuild) {
1860         return buildNew(I, NewOps);
1861       }
1862       return I;
1863     }
1864     case Instruction::InsertElement: {
1865       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1866 
1867       // The insertelement was inserting at Element. Figure out which element
1868       // that becomes after shuffling. The answer is guaranteed to be unique
1869       // by CanEvaluateShuffled.
1870       bool Found = false;
1871       int Index = 0;
1872       for (int e = Mask.size(); Index != e; ++Index) {
1873         if (Mask[Index] == Element) {
1874           Found = true;
1875           break;
1876         }
1877       }
1878 
1879       // If element is not in Mask, no need to handle the operand 1 (element to
1880       // be inserted). Just evaluate values in operand 0 according to Mask.
1881       if (!Found)
1882         return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1883 
1884       Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1885       return InsertElementInst::Create(V, I->getOperand(1),
1886                                        ConstantInt::get(I32Ty, Index), "", I);
1887     }
1888   }
1889   llvm_unreachable("failed to reorder elements of vector instruction!");
1890 }
1891 
1892 // Returns true if the shuffle is extracting a contiguous range of values from
1893 // LHS, for example:
1894 //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1895 //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1896 //   Shuffles to:  |EE|FF|GG|HH|
1897 //                 +--+--+--+--+
1898 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1899                                        ArrayRef<int> Mask) {
1900   unsigned LHSElems =
1901       cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
1902   unsigned MaskElems = Mask.size();
1903   unsigned BegIdx = Mask.front();
1904   unsigned EndIdx = Mask.back();
1905   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1906     return false;
1907   for (unsigned I = 0; I != MaskElems; ++I)
1908     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1909       return false;
1910   return true;
1911 }
1912 
1913 /// These are the ingredients in an alternate form binary operator as described
1914 /// below.
1915 struct BinopElts {
1916   BinaryOperator::BinaryOps Opcode;
1917   Value *Op0;
1918   Value *Op1;
1919   BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
1920             Value *V0 = nullptr, Value *V1 = nullptr) :
1921       Opcode(Opc), Op0(V0), Op1(V1) {}
1922   operator bool() const { return Opcode != 0; }
1923 };
1924 
1925 /// Binops may be transformed into binops with different opcodes and operands.
1926 /// Reverse the usual canonicalization to enable folds with the non-canonical
1927 /// form of the binop. If a transform is possible, return the elements of the
1928 /// new binop. If not, return invalid elements.
1929 static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
1930   Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
1931   Type *Ty = BO->getType();
1932   switch (BO->getOpcode()) {
1933   case Instruction::Shl: {
1934     // shl X, C --> mul X, (1 << C)
1935     Constant *C;
1936     if (match(BO1, m_Constant(C))) {
1937       Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
1938       return {Instruction::Mul, BO0, ShlOne};
1939     }
1940     break;
1941   }
1942   case Instruction::Or: {
1943     // or X, C --> add X, C (when X and C have no common bits set)
1944     const APInt *C;
1945     if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
1946       return {Instruction::Add, BO0, BO1};
1947     break;
1948   }
1949   case Instruction::Sub:
1950     // sub 0, X --> mul X, -1
1951     if (match(BO0, m_ZeroInt()))
1952       return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
1953     break;
1954   default:
1955     break;
1956   }
1957   return {};
1958 }
1959 
1960 static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
1961   assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
1962 
1963   // Are we shuffling together some value and that same value after it has been
1964   // modified by a binop with a constant?
1965   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1966   Constant *C;
1967   bool Op0IsBinop;
1968   if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
1969     Op0IsBinop = true;
1970   else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
1971     Op0IsBinop = false;
1972   else
1973     return nullptr;
1974 
1975   // The identity constant for a binop leaves a variable operand unchanged. For
1976   // a vector, this is a splat of something like 0, -1, or 1.
1977   // If there's no identity constant for this binop, we're done.
1978   auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
1979   BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
1980   Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
1981   if (!IdC)
1982     return nullptr;
1983 
1984   // Shuffle identity constants into the lanes that return the original value.
1985   // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
1986   // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
1987   // The existing binop constant vector remains in the same operand position.
1988   ArrayRef<int> Mask = Shuf.getShuffleMask();
1989   Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
1990                                 ConstantExpr::getShuffleVector(IdC, C, Mask);
1991 
1992   bool MightCreatePoisonOrUB =
1993       is_contained(Mask, UndefMaskElem) &&
1994       (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
1995   if (MightCreatePoisonOrUB)
1996     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
1997 
1998   // shuf (bop X, C), X, M --> bop X, C'
1999   // shuf X, (bop X, C), M --> bop X, C'
2000   Value *X = Op0IsBinop ? Op1 : Op0;
2001   Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
2002   NewBO->copyIRFlags(BO);
2003 
2004   // An undef shuffle mask element may propagate as an undef constant element in
2005   // the new binop. That would produce poison where the original code might not.
2006   // If we already made a safe constant, then there's no danger.
2007   if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2008     NewBO->dropPoisonGeneratingFlags();
2009   return NewBO;
2010 }
2011 
2012 /// If we have an insert of a scalar to a non-zero element of an undefined
2013 /// vector and then shuffle that value, that's the same as inserting to the zero
2014 /// element and shuffling. Splatting from the zero element is recognized as the
2015 /// canonical form of splat.
2016 static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
2017                                             InstCombiner::BuilderTy &Builder) {
2018   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2019   ArrayRef<int> Mask = Shuf.getShuffleMask();
2020   Value *X;
2021   uint64_t IndexC;
2022 
2023   // Match a shuffle that is a splat to a non-zero element.
2024   if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
2025                                        m_ConstantInt(IndexC)))) ||
2026       !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
2027     return nullptr;
2028 
2029   // Insert into element 0 of an undef vector.
2030   UndefValue *UndefVec = UndefValue::get(Shuf.getType());
2031   Constant *Zero = Builder.getInt32(0);
2032   Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
2033 
2034   // Splat from element 0. Any mask element that is undefined remains undefined.
2035   // For example:
2036   // shuf (inselt undef, X, 2), _, <2,2,undef>
2037   //   --> shuf (inselt undef, X, 0), poison, <0,0,undef>
2038   unsigned NumMaskElts =
2039       cast<FixedVectorType>(Shuf.getType())->getNumElements();
2040   SmallVector<int, 16> NewMask(NumMaskElts, 0);
2041   for (unsigned i = 0; i != NumMaskElts; ++i)
2042     if (Mask[i] == UndefMaskElem)
2043       NewMask[i] = Mask[i];
2044 
2045   return new ShuffleVectorInst(NewIns, NewMask);
2046 }
2047 
2048 /// Try to fold shuffles that are the equivalent of a vector select.
2049 Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
2050   if (!Shuf.isSelect())
2051     return nullptr;
2052 
2053   // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
2054   // Commuting undef to operand 0 conflicts with another canonicalization.
2055   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2056   if (!match(Shuf.getOperand(1), m_Undef()) &&
2057       Shuf.getMaskValue(0) >= (int)NumElts) {
2058     // TODO: Can we assert that both operands of a shuffle-select are not undef
2059     // (otherwise, it would have been folded by instsimplify?
2060     Shuf.commute();
2061     return &Shuf;
2062   }
2063 
2064   if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
2065     return I;
2066 
2067   BinaryOperator *B0, *B1;
2068   if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
2069       !match(Shuf.getOperand(1), m_BinOp(B1)))
2070     return nullptr;
2071 
2072   // If one operand is "0 - X", allow that to be viewed as "X * -1"
2073   // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
2074   // with a multiply, we will exit because C0/C1 will not be set.
2075   Value *X, *Y;
2076   Constant *C0 = nullptr, *C1 = nullptr;
2077   bool ConstantsAreOp1;
2078   if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
2079       match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
2080     ConstantsAreOp1 = false;
2081   else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
2082                                  m_Neg(m_Value(X)))) &&
2083            match(B1, m_CombineOr(m_BinOp(m_Value(Y), m_Constant(C1)),
2084                                  m_Neg(m_Value(Y)))))
2085     ConstantsAreOp1 = true;
2086   else
2087     return nullptr;
2088 
2089   // We need matching binops to fold the lanes together.
2090   BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
2091   BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
2092   bool DropNSW = false;
2093   if (ConstantsAreOp1 && Opc0 != Opc1) {
2094     // TODO: We drop "nsw" if shift is converted into multiply because it may
2095     // not be correct when the shift amount is BitWidth - 1. We could examine
2096     // each vector element to determine if it is safe to keep that flag.
2097     if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2098       DropNSW = true;
2099     if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
2100       assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
2101       Opc0 = AltB0.Opcode;
2102       C0 = cast<Constant>(AltB0.Op1);
2103     } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
2104       assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
2105       Opc1 = AltB1.Opcode;
2106       C1 = cast<Constant>(AltB1.Op1);
2107     }
2108   }
2109 
2110   if (Opc0 != Opc1 || !C0 || !C1)
2111     return nullptr;
2112 
2113   // The opcodes must be the same. Use a new name to make that clear.
2114   BinaryOperator::BinaryOps BOpc = Opc0;
2115 
2116   // Select the constant elements needed for the single binop.
2117   ArrayRef<int> Mask = Shuf.getShuffleMask();
2118   Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
2119 
2120   // We are moving a binop after a shuffle. When a shuffle has an undefined
2121   // mask element, the result is undefined, but it is not poison or undefined
2122   // behavior. That is not necessarily true for div/rem/shift.
2123   bool MightCreatePoisonOrUB =
2124       is_contained(Mask, UndefMaskElem) &&
2125       (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
2126   if (MightCreatePoisonOrUB)
2127     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
2128                                                        ConstantsAreOp1);
2129 
2130   Value *V;
2131   if (X == Y) {
2132     // Remove a binop and the shuffle by rearranging the constant:
2133     // shuffle (op V, C0), (op V, C1), M --> op V, C'
2134     // shuffle (op C0, V), (op C1, V), M --> op C', V
2135     V = X;
2136   } else {
2137     // If there are 2 different variable operands, we must create a new shuffle
2138     // (select) first, so check uses to ensure that we don't end up with more
2139     // instructions than we started with.
2140     if (!B0->hasOneUse() && !B1->hasOneUse())
2141       return nullptr;
2142 
2143     // If we use the original shuffle mask and op1 is *variable*, we would be
2144     // putting an undef into operand 1 of div/rem/shift. This is either UB or
2145     // poison. We do not have to guard against UB when *constants* are op1
2146     // because safe constants guarantee that we do not overflow sdiv/srem (and
2147     // there's no danger for other opcodes).
2148     // TODO: To allow this case, create a new shuffle mask with no undefs.
2149     if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2150       return nullptr;
2151 
2152     // Note: In general, we do not create new shuffles in InstCombine because we
2153     // do not know if a target can lower an arbitrary shuffle optimally. In this
2154     // case, the shuffle uses the existing mask, so there is no additional risk.
2155 
2156     // Select the variable vectors first, then perform the binop:
2157     // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
2158     // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
2159     V = Builder.CreateShuffleVector(X, Y, Mask);
2160   }
2161 
2162   Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2163                                    Builder.CreateBinOp(BOpc, NewC, V);
2164 
2165   // Flags are intersected from the 2 source binops. But there are 2 exceptions:
2166   // 1. If we changed an opcode, poison conditions might have changed.
2167   // 2. If the shuffle had undef mask elements, the new binop might have undefs
2168   //    where the original code did not. But if we already made a safe constant,
2169   //    then there's no danger.
2170   if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2171     NewI->copyIRFlags(B0);
2172     NewI->andIRFlags(B1);
2173     if (DropNSW)
2174       NewI->setHasNoSignedWrap(false);
2175     if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2176       NewI->dropPoisonGeneratingFlags();
2177   }
2178   return replaceInstUsesWith(Shuf, NewBO);
2179 }
2180 
2181 /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2182 /// Example (little endian):
2183 /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
2184 static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
2185                                      bool IsBigEndian) {
2186   // This must be a bitcasted shuffle of 1 vector integer operand.
2187   Type *DestType = Shuf.getType();
2188   Value *X;
2189   if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2190       !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
2191     return nullptr;
2192 
2193   // The source type must have the same number of elements as the shuffle,
2194   // and the source element type must be larger than the shuffle element type.
2195   Type *SrcType = X->getType();
2196   if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2197       cast<FixedVectorType>(SrcType)->getNumElements() !=
2198           cast<FixedVectorType>(DestType)->getNumElements() ||
2199       SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2200     return nullptr;
2201 
2202   assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2203          "Expected a shuffle that decreases length");
2204 
2205   // Last, check that the mask chooses the correct low bits for each narrow
2206   // element in the result.
2207   uint64_t TruncRatio =
2208       SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2209   ArrayRef<int> Mask = Shuf.getShuffleMask();
2210   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2211     if (Mask[i] == UndefMaskElem)
2212       continue;
2213     uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2214     assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2215     if (Mask[i] != (int)LSBIndex)
2216       return nullptr;
2217   }
2218 
2219   return new TruncInst(X, DestType);
2220 }
2221 
2222 /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
2223 /// narrowing (concatenating with undef and extracting back to the original
2224 /// length). This allows replacing the wide select with a narrow select.
2225 static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
2226                                        InstCombiner::BuilderTy &Builder) {
2227   // This must be a narrowing identity shuffle. It extracts the 1st N elements
2228   // of the 1st vector operand of a shuffle.
2229   if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
2230     return nullptr;
2231 
2232   // The vector being shuffled must be a vector select that we can eliminate.
2233   // TODO: The one-use requirement could be eased if X and/or Y are constants.
2234   Value *Cond, *X, *Y;
2235   if (!match(Shuf.getOperand(0),
2236              m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
2237     return nullptr;
2238 
2239   // We need a narrow condition value. It must be extended with undef elements
2240   // and have the same number of elements as this shuffle.
2241   unsigned NarrowNumElts =
2242       cast<FixedVectorType>(Shuf.getType())->getNumElements();
2243   Value *NarrowCond;
2244   if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
2245       cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2246           NarrowNumElts ||
2247       !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
2248     return nullptr;
2249 
2250   // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
2251   // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
2252   Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2253   Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
2254   return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
2255 }
2256 
2257 /// Canonicalize FP negate after shuffle.
2258 static Instruction *foldFNegShuffle(ShuffleVectorInst &Shuf,
2259                                     InstCombiner::BuilderTy &Builder) {
2260   Instruction *FNeg0;
2261   Value *X;
2262   if (!match(Shuf.getOperand(0), m_CombineAnd(m_Instruction(FNeg0),
2263                                               m_FNeg(m_Value(X)))))
2264     return nullptr;
2265 
2266   // shuffle (fneg X), Mask --> fneg (shuffle X, Mask)
2267   if (FNeg0->hasOneUse() && match(Shuf.getOperand(1), m_Undef())) {
2268     Value *NewShuf = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2269     return UnaryOperator::CreateFNegFMF(NewShuf, FNeg0);
2270   }
2271 
2272   Instruction *FNeg1;
2273   Value *Y;
2274   if (!match(Shuf.getOperand(1), m_CombineAnd(m_Instruction(FNeg1),
2275                                               m_FNeg(m_Value(Y)))))
2276     return nullptr;
2277 
2278   // shuffle (fneg X), (fneg Y), Mask --> fneg (shuffle X, Y, Mask)
2279   if (FNeg0->hasOneUse() || FNeg1->hasOneUse()) {
2280     Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2281     Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewShuf);
2282     NewFNeg->copyIRFlags(FNeg0);
2283     NewFNeg->andIRFlags(FNeg1);
2284     return NewFNeg;
2285   }
2286 
2287   return nullptr;
2288 }
2289 
2290 /// Canonicalize casts after shuffle.
2291 static Instruction *foldCastShuffle(ShuffleVectorInst &Shuf,
2292                                     InstCombiner::BuilderTy &Builder) {
2293   // Do we have 2 matching cast operands?
2294   auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
2295   auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
2296   if (!Cast0 || !Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2297       Cast0->getSrcTy() != Cast1->getSrcTy())
2298     return nullptr;
2299 
2300   // TODO: Allow other opcodes? That would require easing the type restrictions
2301   //       below here.
2302   CastInst::CastOps CastOpcode = Cast0->getOpcode();
2303   switch (CastOpcode) {
2304   case Instruction::FPToSI:
2305   case Instruction::FPToUI:
2306   case Instruction::SIToFP:
2307   case Instruction::UIToFP:
2308     break;
2309   default:
2310     return nullptr;
2311   }
2312 
2313   VectorType *ShufTy = Shuf.getType();
2314   VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
2315   VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
2316 
2317   // TODO: Allow length-increasing shuffles?
2318   if (ShufTy->getElementCount().getKnownMinValue() >
2319       ShufOpTy->getElementCount().getKnownMinValue())
2320     return nullptr;
2321 
2322   // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
2323   assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
2324          "Expected fixed vector operands for casts and binary shuffle");
2325   if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2326     return nullptr;
2327 
2328   // At least one of the operands must have only one use (the shuffle).
2329   if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2330     return nullptr;
2331 
2332   // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
2333   Value *X = Cast0->getOperand(0);
2334   Value *Y = Cast1->getOperand(0);
2335   Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2336   return CastInst::Create(CastOpcode, NewShuf, ShufTy);
2337 }
2338 
2339 /// Try to fold an extract subvector operation.
2340 static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
2341   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2342   if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
2343     return nullptr;
2344 
2345   // Check if we are extracting all bits of an inserted scalar:
2346   // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
2347   Value *X;
2348   if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
2349       X->getType()->getPrimitiveSizeInBits() ==
2350           Shuf.getType()->getPrimitiveSizeInBits())
2351     return new BitCastInst(X, Shuf.getType());
2352 
2353   // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
2354   Value *Y;
2355   ArrayRef<int> Mask;
2356   if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
2357     return nullptr;
2358 
2359   // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
2360   // then combining may result in worse codegen.
2361   if (!Op0->hasOneUse())
2362     return nullptr;
2363 
2364   // We are extracting a subvector from a shuffle. Remove excess elements from
2365   // the 1st shuffle mask to eliminate the extract.
2366   //
2367   // This transform is conservatively limited to identity extracts because we do
2368   // not allow arbitrary shuffle mask creation as a target-independent transform
2369   // (because we can't guarantee that will lower efficiently).
2370   //
2371   // If the extracting shuffle has an undef mask element, it transfers to the
2372   // new shuffle mask. Otherwise, copy the original mask element. Example:
2373   //   shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
2374   //   shuf X, Y, <C0, undef, C2, undef>
2375   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2376   SmallVector<int, 16> NewMask(NumElts);
2377   assert(NumElts < Mask.size() &&
2378          "Identity with extract must have less elements than its inputs");
2379 
2380   for (unsigned i = 0; i != NumElts; ++i) {
2381     int ExtractMaskElt = Shuf.getMaskValue(i);
2382     int MaskElt = Mask[i];
2383     NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
2384   }
2385   return new ShuffleVectorInst(X, Y, NewMask);
2386 }
2387 
2388 /// Try to replace a shuffle with an insertelement or try to replace a shuffle
2389 /// operand with the operand of an insertelement.
2390 static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
2391                                           InstCombinerImpl &IC) {
2392   Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2393   SmallVector<int, 16> Mask;
2394   Shuf.getShuffleMask(Mask);
2395 
2396   int NumElts = Mask.size();
2397   int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
2398 
2399   // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
2400   // not be able to handle it there if the insertelement has >1 use.
2401   // If the shuffle has an insertelement operand but does not choose the
2402   // inserted scalar element from that value, then we can replace that shuffle
2403   // operand with the source vector of the insertelement.
2404   Value *X;
2405   uint64_t IdxC;
2406   if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2407     // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
2408     if (!is_contained(Mask, (int)IdxC))
2409       return IC.replaceOperand(Shuf, 0, X);
2410   }
2411   if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2412     // Offset the index constant by the vector width because we are checking for
2413     // accesses to the 2nd vector input of the shuffle.
2414     IdxC += InpNumElts;
2415     // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
2416     if (!is_contained(Mask, (int)IdxC))
2417       return IC.replaceOperand(Shuf, 1, X);
2418   }
2419   // For the rest of the transform, the shuffle must not change vector sizes.
2420   // TODO: This restriction could be removed if the insert has only one use
2421   //       (because the transform would require a new length-changing shuffle).
2422   if (NumElts != InpNumElts)
2423     return nullptr;
2424 
2425   // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
2426   auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
2427     // We need an insertelement with a constant index.
2428     if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
2429                                m_ConstantInt(IndexC))))
2430       return false;
2431 
2432     // Test the shuffle mask to see if it splices the inserted scalar into the
2433     // operand 1 vector of the shuffle.
2434     int NewInsIndex = -1;
2435     for (int i = 0; i != NumElts; ++i) {
2436       // Ignore undef mask elements.
2437       if (Mask[i] == -1)
2438         continue;
2439 
2440       // The shuffle takes elements of operand 1 without lane changes.
2441       if (Mask[i] == NumElts + i)
2442         continue;
2443 
2444       // The shuffle must choose the inserted scalar exactly once.
2445       if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2446         return false;
2447 
2448       // The shuffle is placing the inserted scalar into element i.
2449       NewInsIndex = i;
2450     }
2451 
2452     assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
2453 
2454     // Index is updated to the potentially translated insertion lane.
2455     IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
2456     return true;
2457   };
2458 
2459   // If the shuffle is unnecessary, insert the scalar operand directly into
2460   // operand 1 of the shuffle. Example:
2461   // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
2462   Value *Scalar;
2463   ConstantInt *IndexC;
2464   if (isShufflingScalarIntoOp1(Scalar, IndexC))
2465     return InsertElementInst::Create(V1, Scalar, IndexC);
2466 
2467   // Try again after commuting shuffle. Example:
2468   // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
2469   // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
2470   std::swap(V0, V1);
2471   ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
2472   if (isShufflingScalarIntoOp1(Scalar, IndexC))
2473     return InsertElementInst::Create(V1, Scalar, IndexC);
2474 
2475   return nullptr;
2476 }
2477 
2478 static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
2479   // Match the operands as identity with padding (also known as concatenation
2480   // with undef) shuffles of the same source type. The backend is expected to
2481   // recreate these concatenations from a shuffle of narrow operands.
2482   auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
2483   auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
2484   if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2485       !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2486     return nullptr;
2487 
2488   // We limit this transform to power-of-2 types because we expect that the
2489   // backend can convert the simplified IR patterns to identical nodes as the
2490   // original IR.
2491   // TODO: If we can verify the same behavior for arbitrary types, the
2492   //       power-of-2 checks can be removed.
2493   Value *X = Shuffle0->getOperand(0);
2494   Value *Y = Shuffle1->getOperand(0);
2495   if (X->getType() != Y->getType() ||
2496       !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
2497       !isPowerOf2_32(
2498           cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
2499       !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
2500       match(X, m_Undef()) || match(Y, m_Undef()))
2501     return nullptr;
2502   assert(match(Shuffle0->getOperand(1), m_Undef()) &&
2503          match(Shuffle1->getOperand(1), m_Undef()) &&
2504          "Unexpected operand for identity shuffle");
2505 
2506   // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
2507   // operands directly by adjusting the shuffle mask to account for the narrower
2508   // types:
2509   // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
2510   int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
2511   int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
2512   assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
2513 
2514   ArrayRef<int> Mask = Shuf.getShuffleMask();
2515   SmallVector<int, 16> NewMask(Mask.size(), -1);
2516   for (int i = 0, e = Mask.size(); i != e; ++i) {
2517     if (Mask[i] == -1)
2518       continue;
2519 
2520     // If this shuffle is choosing an undef element from 1 of the sources, that
2521     // element is undef.
2522     if (Mask[i] < WideElts) {
2523       if (Shuffle0->getMaskValue(Mask[i]) == -1)
2524         continue;
2525     } else {
2526       if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2527         continue;
2528     }
2529 
2530     // If this shuffle is choosing from the 1st narrow op, the mask element is
2531     // the same. If this shuffle is choosing from the 2nd narrow op, the mask
2532     // element is offset down to adjust for the narrow vector widths.
2533     if (Mask[i] < WideElts) {
2534       assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2535       NewMask[i] = Mask[i];
2536     } else {
2537       assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2538       NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2539     }
2540   }
2541   return new ShuffleVectorInst(X, Y, NewMask);
2542 }
2543 
2544 Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
2545   Value *LHS = SVI.getOperand(0);
2546   Value *RHS = SVI.getOperand(1);
2547   SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
2548   if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
2549                                           SVI.getType(), ShufQuery))
2550     return replaceInstUsesWith(SVI, V);
2551 
2552   // Bail out for scalable vectors
2553   if (isa<ScalableVectorType>(LHS->getType()))
2554     return nullptr;
2555 
2556   unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
2557   unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
2558 
2559   // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
2560   //
2561   // if X and Y are of the same (vector) type, and the element size is not
2562   // changed by the bitcasts, we can distribute the bitcasts through the
2563   // shuffle, hopefully reducing the number of instructions. We make sure that
2564   // at least one bitcast only has one use, so we don't *increase* the number of
2565   // instructions here.
2566   Value *X, *Y;
2567   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
2568       X->getType()->isVectorTy() && X->getType() == Y->getType() &&
2569       X->getType()->getScalarSizeInBits() ==
2570           SVI.getType()->getScalarSizeInBits() &&
2571       (LHS->hasOneUse() || RHS->hasOneUse())) {
2572     Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
2573                                            SVI.getName() + ".uncasted");
2574     return new BitCastInst(V, SVI.getType());
2575   }
2576 
2577   ArrayRef<int> Mask = SVI.getShuffleMask();
2578   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
2579 
2580   // Peek through a bitcasted shuffle operand by scaling the mask. If the
2581   // simulated shuffle can simplify, then this shuffle is unnecessary:
2582   // shuf (bitcast X), undef, Mask --> bitcast X'
2583   // TODO: This could be extended to allow length-changing shuffles.
2584   //       The transform might also be obsoleted if we allowed canonicalization
2585   //       of bitcasted shuffles.
2586   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
2587       X->getType()->isVectorTy() && VWidth == LHSWidth) {
2588     // Try to create a scaled mask constant.
2589     auto *XType = cast<FixedVectorType>(X->getType());
2590     unsigned XNumElts = XType->getNumElements();
2591     SmallVector<int, 16> ScaledMask;
2592     if (XNumElts >= VWidth) {
2593       assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
2594       narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
2595     } else {
2596       assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
2597       if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
2598         ScaledMask.clear();
2599     }
2600     if (!ScaledMask.empty()) {
2601       // If the shuffled source vector simplifies, cast that value to this
2602       // shuffle's type.
2603       if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
2604                                               ScaledMask, XType, ShufQuery))
2605         return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
2606     }
2607   }
2608 
2609   // shuffle x, x, mask --> shuffle x, undef, mask'
2610   if (LHS == RHS) {
2611     assert(!match(RHS, m_Undef()) &&
2612            "Shuffle with 2 undef ops not simplified?");
2613     return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
2614   }
2615 
2616   // shuffle undef, x, mask --> shuffle x, undef, mask'
2617   if (match(LHS, m_Undef())) {
2618     SVI.commute();
2619     return &SVI;
2620   }
2621 
2622   if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
2623     return I;
2624 
2625   if (Instruction *I = foldSelectShuffle(SVI))
2626     return I;
2627 
2628   if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
2629     return I;
2630 
2631   if (Instruction *I = narrowVectorSelect(SVI, Builder))
2632     return I;
2633 
2634   if (Instruction *I = foldFNegShuffle(SVI, Builder))
2635     return I;
2636 
2637   if (Instruction *I = foldCastShuffle(SVI, Builder))
2638     return I;
2639 
2640   APInt UndefElts(VWidth, 0);
2641   APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
2642   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
2643     if (V != &SVI)
2644       return replaceInstUsesWith(SVI, V);
2645     return &SVI;
2646   }
2647 
2648   if (Instruction *I = foldIdentityExtractShuffle(SVI))
2649     return I;
2650 
2651   // These transforms have the potential to lose undef knowledge, so they are
2652   // intentionally placed after SimplifyDemandedVectorElts().
2653   if (Instruction *I = foldShuffleWithInsert(SVI, *this))
2654     return I;
2655   if (Instruction *I = foldIdentityPaddedShuffles(SVI))
2656     return I;
2657 
2658   if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
2659     Value *V = evaluateInDifferentElementOrder(LHS, Mask);
2660     return replaceInstUsesWith(SVI, V);
2661   }
2662 
2663   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
2664   // a non-vector type. We can instead bitcast the original vector followed by
2665   // an extract of the desired element:
2666   //
2667   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
2668   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
2669   //   %1 = bitcast <4 x i8> %sroa to i32
2670   // Becomes:
2671   //   %bc = bitcast <16 x i8> %in to <4 x i32>
2672   //   %ext = extractelement <4 x i32> %bc, i32 0
2673   //
2674   // If the shuffle is extracting a contiguous range of values from the input
2675   // vector then each use which is a bitcast of the extracted size can be
2676   // replaced. This will work if the vector types are compatible, and the begin
2677   // index is aligned to a value in the casted vector type. If the begin index
2678   // isn't aligned then we can shuffle the original vector (keeping the same
2679   // vector type) before extracting.
2680   //
2681   // This code will bail out if the target type is fundamentally incompatible
2682   // with vectors of the source type.
2683   //
2684   // Example of <16 x i8>, target type i32:
2685   // Index range [4,8):         v-----------v Will work.
2686   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
2687   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
2688   //     <4 x i32>: |           |           |           |           |
2689   //                +-----------+-----------+-----------+-----------+
2690   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
2691   // Target type i40:           ^--------------^ Won't work, bail.
2692   bool MadeChange = false;
2693   if (isShuffleExtractingFromLHS(SVI, Mask)) {
2694     Value *V = LHS;
2695     unsigned MaskElems = Mask.size();
2696     auto *SrcTy = cast<FixedVectorType>(V->getType());
2697     unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedSize();
2698     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
2699     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
2700     unsigned SrcNumElems = SrcTy->getNumElements();
2701     SmallVector<BitCastInst *, 8> BCs;
2702     DenseMap<Type *, Value *> NewBCs;
2703     for (User *U : SVI.users())
2704       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
2705         if (!BC->use_empty())
2706           // Only visit bitcasts that weren't previously handled.
2707           BCs.push_back(BC);
2708     for (BitCastInst *BC : BCs) {
2709       unsigned BegIdx = Mask.front();
2710       Type *TgtTy = BC->getDestTy();
2711       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
2712       if (!TgtElemBitWidth)
2713         continue;
2714       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
2715       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
2716       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
2717       if (!VecBitWidthsEqual)
2718         continue;
2719       if (!VectorType::isValidElementType(TgtTy))
2720         continue;
2721       auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
2722       if (!BegIsAligned) {
2723         // Shuffle the input so [0,NumElements) contains the output, and
2724         // [NumElems,SrcNumElems) is undef.
2725         SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
2726         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
2727           ShuffleMask[I] = Idx;
2728         V = Builder.CreateShuffleVector(V, ShuffleMask,
2729                                         SVI.getName() + ".extract");
2730         BegIdx = 0;
2731       }
2732       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
2733       assert(SrcElemsPerTgtElem);
2734       BegIdx /= SrcElemsPerTgtElem;
2735       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
2736       auto *NewBC =
2737           BCAlreadyExists
2738               ? NewBCs[CastSrcTy]
2739               : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
2740       if (!BCAlreadyExists)
2741         NewBCs[CastSrcTy] = NewBC;
2742       auto *Ext = Builder.CreateExtractElement(
2743           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
2744       // The shufflevector isn't being replaced: the bitcast that used it
2745       // is. InstCombine will visit the newly-created instructions.
2746       replaceInstUsesWith(*BC, Ext);
2747       MadeChange = true;
2748     }
2749   }
2750 
2751   // If the LHS is a shufflevector itself, see if we can combine it with this
2752   // one without producing an unusual shuffle.
2753   // Cases that might be simplified:
2754   // 1.
2755   // x1=shuffle(v1,v2,mask1)
2756   //  x=shuffle(x1,undef,mask)
2757   //        ==>
2758   //  x=shuffle(v1,undef,newMask)
2759   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
2760   // 2.
2761   // x1=shuffle(v1,undef,mask1)
2762   //  x=shuffle(x1,x2,mask)
2763   // where v1.size() == mask1.size()
2764   //        ==>
2765   //  x=shuffle(v1,x2,newMask)
2766   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
2767   // 3.
2768   // x2=shuffle(v2,undef,mask2)
2769   //  x=shuffle(x1,x2,mask)
2770   // where v2.size() == mask2.size()
2771   //        ==>
2772   //  x=shuffle(x1,v2,newMask)
2773   // newMask[i] = (mask[i] < x1.size())
2774   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
2775   // 4.
2776   // x1=shuffle(v1,undef,mask1)
2777   // x2=shuffle(v2,undef,mask2)
2778   //  x=shuffle(x1,x2,mask)
2779   // where v1.size() == v2.size()
2780   //        ==>
2781   //  x=shuffle(v1,v2,newMask)
2782   // newMask[i] = (mask[i] < x1.size())
2783   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
2784   //
2785   // Here we are really conservative:
2786   // we are absolutely afraid of producing a shuffle mask not in the input
2787   // program, because the code gen may not be smart enough to turn a merged
2788   // shuffle into two specific shuffles: it may produce worse code.  As such,
2789   // we only merge two shuffles if the result is either a splat or one of the
2790   // input shuffle masks.  In this case, merging the shuffles just removes
2791   // one instruction, which we know is safe.  This is good for things like
2792   // turning: (splat(splat)) -> splat, or
2793   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
2794   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
2795   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
2796   if (LHSShuffle)
2797     if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
2798       LHSShuffle = nullptr;
2799   if (RHSShuffle)
2800     if (!match(RHSShuffle->getOperand(1), m_Undef()))
2801       RHSShuffle = nullptr;
2802   if (!LHSShuffle && !RHSShuffle)
2803     return MadeChange ? &SVI : nullptr;
2804 
2805   Value* LHSOp0 = nullptr;
2806   Value* LHSOp1 = nullptr;
2807   Value* RHSOp0 = nullptr;
2808   unsigned LHSOp0Width = 0;
2809   unsigned RHSOp0Width = 0;
2810   if (LHSShuffle) {
2811     LHSOp0 = LHSShuffle->getOperand(0);
2812     LHSOp1 = LHSShuffle->getOperand(1);
2813     LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
2814   }
2815   if (RHSShuffle) {
2816     RHSOp0 = RHSShuffle->getOperand(0);
2817     RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
2818   }
2819   Value* newLHS = LHS;
2820   Value* newRHS = RHS;
2821   if (LHSShuffle) {
2822     // case 1
2823     if (match(RHS, m_Undef())) {
2824       newLHS = LHSOp0;
2825       newRHS = LHSOp1;
2826     }
2827     // case 2 or 4
2828     else if (LHSOp0Width == LHSWidth) {
2829       newLHS = LHSOp0;
2830     }
2831   }
2832   // case 3 or 4
2833   if (RHSShuffle && RHSOp0Width == LHSWidth) {
2834     newRHS = RHSOp0;
2835   }
2836   // case 4
2837   if (LHSOp0 == RHSOp0) {
2838     newLHS = LHSOp0;
2839     newRHS = nullptr;
2840   }
2841 
2842   if (newLHS == LHS && newRHS == RHS)
2843     return MadeChange ? &SVI : nullptr;
2844 
2845   ArrayRef<int> LHSMask;
2846   ArrayRef<int> RHSMask;
2847   if (newLHS != LHS)
2848     LHSMask = LHSShuffle->getShuffleMask();
2849   if (RHSShuffle && newRHS != RHS)
2850     RHSMask = RHSShuffle->getShuffleMask();
2851 
2852   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
2853   SmallVector<int, 16> newMask;
2854   bool isSplat = true;
2855   int SplatElt = -1;
2856   // Create a new mask for the new ShuffleVectorInst so that the new
2857   // ShuffleVectorInst is equivalent to the original one.
2858   for (unsigned i = 0; i < VWidth; ++i) {
2859     int eltMask;
2860     if (Mask[i] < 0) {
2861       // This element is an undef value.
2862       eltMask = -1;
2863     } else if (Mask[i] < (int)LHSWidth) {
2864       // This element is from left hand side vector operand.
2865       //
2866       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
2867       // new mask value for the element.
2868       if (newLHS != LHS) {
2869         eltMask = LHSMask[Mask[i]];
2870         // If the value selected is an undef value, explicitly specify it
2871         // with a -1 mask value.
2872         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
2873           eltMask = -1;
2874       } else
2875         eltMask = Mask[i];
2876     } else {
2877       // This element is from right hand side vector operand
2878       //
2879       // If the value selected is an undef value, explicitly specify it
2880       // with a -1 mask value. (case 1)
2881       if (match(RHS, m_Undef()))
2882         eltMask = -1;
2883       // If RHS is going to be replaced (case 3 or 4), calculate the
2884       // new mask value for the element.
2885       else if (newRHS != RHS) {
2886         eltMask = RHSMask[Mask[i]-LHSWidth];
2887         // If the value selected is an undef value, explicitly specify it
2888         // with a -1 mask value.
2889         if (eltMask >= (int)RHSOp0Width) {
2890           assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
2891                  "should have been check above");
2892           eltMask = -1;
2893         }
2894       } else
2895         eltMask = Mask[i]-LHSWidth;
2896 
2897       // If LHS's width is changed, shift the mask value accordingly.
2898       // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
2899       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
2900       // If newRHS == newLHS, we want to remap any references from newRHS to
2901       // newLHS so that we can properly identify splats that may occur due to
2902       // obfuscation across the two vectors.
2903       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
2904         eltMask += newLHSWidth;
2905     }
2906 
2907     // Check if this could still be a splat.
2908     if (eltMask >= 0) {
2909       if (SplatElt >= 0 && SplatElt != eltMask)
2910         isSplat = false;
2911       SplatElt = eltMask;
2912     }
2913 
2914     newMask.push_back(eltMask);
2915   }
2916 
2917   // If the result mask is equal to one of the original shuffle masks,
2918   // or is a splat, do the replacement.
2919   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
2920     if (!newRHS)
2921       newRHS = UndefValue::get(newLHS->getType());
2922     return new ShuffleVectorInst(newLHS, newRHS, newMask);
2923   }
2924 
2925   return MadeChange ? &SVI : nullptr;
2926 }
2927