1f22ef01cSRoman Divacky //===- InstCombineVectorOps.cpp -------------------------------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements instcombine for ExtractElement, InsertElement and
11f22ef01cSRoman Divacky // ShuffleVector.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15ff0cc061SDimitry Andric #include "InstCombineInternal.h"
16ff0cc061SDimitry Andric #include "llvm/ADT/DenseMap.h"
17875ed548SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
18875ed548SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
1991bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h"
20f22ef01cSRoman Divacky using namespace llvm;
21139f7f9bSDimitry Andric using namespace PatternMatch;
22f22ef01cSRoman Divacky 
2391bc56edSDimitry Andric #define DEBUG_TYPE "instcombine"
2491bc56edSDimitry Andric 
257d523365SDimitry Andric /// Return true if the value is cheaper to scalarize than it is to leave as a
267d523365SDimitry Andric /// vector operation. isConstant indicates whether we're extracting one known
277d523365SDimitry Andric /// element. If false we're extracting a variable index.
287d523365SDimitry Andric static bool cheapToScalarize(Value *V, bool isConstant) {
29dff0c46cSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
30f22ef01cSRoman Divacky     if (isConstant) return true;
31dff0c46cSDimitry Andric 
32dff0c46cSDimitry Andric     // If all elts are the same, we can extract it and use any of the values.
3385d60e68SDimitry Andric     if (Constant *Op0 = C->getAggregateElement(0U)) {
3485d60e68SDimitry Andric       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
3585d60e68SDimitry Andric            ++i)
36dff0c46cSDimitry Andric         if (C->getAggregateElement(i) != Op0)
37f22ef01cSRoman Divacky           return false;
38f22ef01cSRoman Divacky       return true;
39f22ef01cSRoman Divacky     }
4085d60e68SDimitry Andric   }
41f22ef01cSRoman Divacky   Instruction *I = dyn_cast<Instruction>(V);
42f22ef01cSRoman Divacky   if (!I) return false;
43f22ef01cSRoman Divacky 
44f22ef01cSRoman Divacky   // Insert element gets simplified to the inserted element or is deleted if
45f22ef01cSRoman Divacky   // this is constant idx extract element and its a constant idx insertelt.
46f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
47f22ef01cSRoman Divacky       isa<ConstantInt>(I->getOperand(2)))
48f22ef01cSRoman Divacky     return true;
49f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
50f22ef01cSRoman Divacky     return true;
51f22ef01cSRoman Divacky   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
52f22ef01cSRoman Divacky     if (BO->hasOneUse() &&
537d523365SDimitry Andric         (cheapToScalarize(BO->getOperand(0), isConstant) ||
547d523365SDimitry Andric          cheapToScalarize(BO->getOperand(1), isConstant)))
55f22ef01cSRoman Divacky       return true;
56f22ef01cSRoman Divacky   if (CmpInst *CI = dyn_cast<CmpInst>(I))
57f22ef01cSRoman Divacky     if (CI->hasOneUse() &&
587d523365SDimitry Andric         (cheapToScalarize(CI->getOperand(0), isConstant) ||
597d523365SDimitry Andric          cheapToScalarize(CI->getOperand(1), isConstant)))
60f22ef01cSRoman Divacky       return true;
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky   return false;
63f22ef01cSRoman Divacky }
64f22ef01cSRoman Divacky 
653ca95b02SDimitry Andric // If we have a PHI node with a vector type that is only used to feed
66f785676fSDimitry Andric // itself and be an operand of extractelement at a constant location,
67f785676fSDimitry Andric // try to replace the PHI of the vector type with a PHI of a scalar type.
68284c1978SDimitry Andric Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
693ca95b02SDimitry Andric   SmallVector<Instruction *, 2> Extracts;
703ca95b02SDimitry Andric   // The users we want the PHI to have are:
713ca95b02SDimitry Andric   // 1) The EI ExtractElement (we already know this)
723ca95b02SDimitry Andric   // 2) Possibly more ExtractElements with the same index.
733ca95b02SDimitry Andric   // 3) Another operand, which will feed back into the PHI.
743ca95b02SDimitry Andric   Instruction *PHIUser = nullptr;
753ca95b02SDimitry Andric   for (auto U : PN->users()) {
763ca95b02SDimitry Andric     if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
773ca95b02SDimitry Andric       if (EI.getIndexOperand() == EU->getIndexOperand())
783ca95b02SDimitry Andric         Extracts.push_back(EU);
793ca95b02SDimitry Andric       else
8091bc56edSDimitry Andric         return nullptr;
813ca95b02SDimitry Andric     } else if (!PHIUser) {
823ca95b02SDimitry Andric       PHIUser = cast<Instruction>(U);
833ca95b02SDimitry Andric     } else {
843ca95b02SDimitry Andric       return nullptr;
853ca95b02SDimitry Andric     }
863ca95b02SDimitry Andric   }
87284c1978SDimitry Andric 
883ca95b02SDimitry Andric   if (!PHIUser)
893ca95b02SDimitry Andric     return nullptr;
90284c1978SDimitry Andric 
91284c1978SDimitry Andric   // Verify that this PHI user has one use, which is the PHI itself,
92284c1978SDimitry Andric   // and that it is a binary operation which is cheap to scalarize.
93284c1978SDimitry Andric   // otherwise return NULL.
9491bc56edSDimitry Andric   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
957d523365SDimitry Andric       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
9691bc56edSDimitry Andric     return nullptr;
97284c1978SDimitry Andric 
98284c1978SDimitry Andric   // Create a scalar PHI node that will replace the vector PHI node
99284c1978SDimitry Andric   // just before the current PHI node.
100f785676fSDimitry Andric   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
101f785676fSDimitry Andric       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
102284c1978SDimitry Andric   // Scalarize each PHI operand.
103284c1978SDimitry Andric   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
104284c1978SDimitry Andric     Value *PHIInVal = PN->getIncomingValue(i);
105284c1978SDimitry Andric     BasicBlock *inBB = PN->getIncomingBlock(i);
106284c1978SDimitry Andric     Value *Elt = EI.getIndexOperand();
107284c1978SDimitry Andric     // If the operand is the PHI induction variable:
108284c1978SDimitry Andric     if (PHIInVal == PHIUser) {
109284c1978SDimitry Andric       // Scalarize the binary operation. Its first operand is the
11091bc56edSDimitry Andric       // scalar PHI, and the second operand is extracted from the other
111284c1978SDimitry Andric       // vector operand.
112284c1978SDimitry Andric       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
113284c1978SDimitry Andric       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
114f785676fSDimitry Andric       Value *Op = InsertNewInstWith(
115f785676fSDimitry Andric           ExtractElementInst::Create(B0->getOperand(opId), Elt,
116f785676fSDimitry Andric                                      B0->getOperand(opId)->getName() + ".Elt"),
117284c1978SDimitry Andric           *B0);
118f785676fSDimitry Andric       Value *newPHIUser = InsertNewInstWith(
1193ca95b02SDimitry Andric           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
1203ca95b02SDimitry Andric                                                 scalarPHI, Op, B0), *B0);
121284c1978SDimitry Andric       scalarPHI->addIncoming(newPHIUser, inBB);
122284c1978SDimitry Andric     } else {
123284c1978SDimitry Andric       // Scalarize PHI input:
124f785676fSDimitry Andric       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
125284c1978SDimitry Andric       // Insert the new instruction into the predecessor basic block.
126284c1978SDimitry Andric       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
127284c1978SDimitry Andric       BasicBlock::iterator InsertPos;
128284c1978SDimitry Andric       if (pos && !isa<PHINode>(pos)) {
1297d523365SDimitry Andric         InsertPos = ++pos->getIterator();
130284c1978SDimitry Andric       } else {
131284c1978SDimitry Andric         InsertPos = inBB->getFirstInsertionPt();
132284c1978SDimitry Andric       }
133284c1978SDimitry Andric 
134284c1978SDimitry Andric       InsertNewInstWith(newEI, *InsertPos);
135284c1978SDimitry Andric 
136284c1978SDimitry Andric       scalarPHI->addIncoming(newEI, inBB);
137284c1978SDimitry Andric     }
138284c1978SDimitry Andric   }
1393ca95b02SDimitry Andric 
1403ca95b02SDimitry Andric   for (auto E : Extracts)
1413ca95b02SDimitry Andric     replaceInstUsesWith(*E, scalarPHI);
1423ca95b02SDimitry Andric 
1433ca95b02SDimitry Andric   return &EI;
144284c1978SDimitry Andric }
145284c1978SDimitry Andric 
146f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
147875ed548SDimitry Andric   if (Value *V = SimplifyExtractElementInst(
148d88c1a5aSDimitry Andric           EI.getVectorOperand(), EI.getIndexOperand(), DL, &TLI, &DT, &AC))
1493ca95b02SDimitry Andric     return replaceInstUsesWith(EI, V);
150875ed548SDimitry Andric 
151f22ef01cSRoman Divacky   // If vector val is constant with all elements the same, replace EI with
152dff0c46cSDimitry Andric   // that element.  We handle a known element # below.
153dff0c46cSDimitry Andric   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
1547d523365SDimitry Andric     if (cheapToScalarize(C, false))
1553ca95b02SDimitry Andric       return replaceInstUsesWith(EI, C->getAggregateElement(0U));
156f22ef01cSRoman Divacky 
157f22ef01cSRoman Divacky   // If extracting a specified index from the vector, see if we can recursively
158f22ef01cSRoman Divacky   // find a previously computed scalar that was inserted into the vector.
159f22ef01cSRoman Divacky   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
160f22ef01cSRoman Divacky     unsigned IndexVal = IdxC->getZExtValue();
161f22ef01cSRoman Divacky     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
162f22ef01cSRoman Divacky 
163875ed548SDimitry Andric     // InstSimplify handles cases where the index is invalid.
164875ed548SDimitry Andric     assert(IndexVal < VectorWidth);
165f22ef01cSRoman Divacky 
166f22ef01cSRoman Divacky     // This instruction only demands the single element from the input vector.
167f22ef01cSRoman Divacky     // If the input vector has a single use, simplify it based on this use
168f22ef01cSRoman Divacky     // property.
169f22ef01cSRoman Divacky     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
170f22ef01cSRoman Divacky       APInt UndefElts(VectorWidth, 0);
171f22ef01cSRoman Divacky       APInt DemandedMask(VectorWidth, 0);
1722754fe60SDimitry Andric       DemandedMask.setBit(IndexVal);
173ff0cc061SDimitry Andric       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
174ff0cc061SDimitry Andric                                                 UndefElts)) {
175f22ef01cSRoman Divacky         EI.setOperand(0, V);
176f22ef01cSRoman Divacky         return &EI;
177f22ef01cSRoman Divacky       }
178f22ef01cSRoman Divacky     }
179f22ef01cSRoman Divacky 
1807d523365SDimitry Andric     // If this extractelement is directly using a bitcast from a vector of
181f22ef01cSRoman Divacky     // the same number of elements, see if we can find the source element from
182f22ef01cSRoman Divacky     // it.  In this case, we will end up needing to bitcast the scalars.
183f22ef01cSRoman Divacky     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
184dff0c46cSDimitry Andric       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
185f22ef01cSRoman Divacky         if (VT->getNumElements() == VectorWidth)
186875ed548SDimitry Andric           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
187f22ef01cSRoman Divacky             return new BitCastInst(Elt, EI.getType());
188f22ef01cSRoman Divacky     }
189284c1978SDimitry Andric 
190284c1978SDimitry Andric     // If there's a vector PHI feeding a scalar use through this extractelement
191284c1978SDimitry Andric     // instruction, try to scalarize the PHI.
192284c1978SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
193284c1978SDimitry Andric       Instruction *scalarPHI = scalarizePHI(EI, PN);
194284c1978SDimitry Andric       if (scalarPHI)
195f785676fSDimitry Andric         return scalarPHI;
196284c1978SDimitry Andric     }
197f22ef01cSRoman Divacky   }
198f22ef01cSRoman Divacky 
199f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
200f22ef01cSRoman Divacky     // Push extractelement into predecessor operation if legal and
2017d523365SDimitry Andric     // profitable to do so.
202f22ef01cSRoman Divacky     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
203f22ef01cSRoman Divacky       if (I->hasOneUse() &&
2047d523365SDimitry Andric           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
205f22ef01cSRoman Divacky         Value *newEI0 =
206f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
207f22ef01cSRoman Divacky                                         EI.getName()+".lhs");
208f22ef01cSRoman Divacky         Value *newEI1 =
209f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
210f22ef01cSRoman Divacky                                         EI.getName()+".rhs");
2113ca95b02SDimitry Andric         return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
2123ca95b02SDimitry Andric                                                      newEI0, newEI1, BO);
213f22ef01cSRoman Divacky       }
214f22ef01cSRoman Divacky     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
215f22ef01cSRoman Divacky       // Extracting the inserted element?
216f22ef01cSRoman Divacky       if (IE->getOperand(2) == EI.getOperand(1))
2173ca95b02SDimitry Andric         return replaceInstUsesWith(EI, IE->getOperand(1));
218f22ef01cSRoman Divacky       // If the inserted and extracted elements are constants, they must not
219f22ef01cSRoman Divacky       // be the same value, extract from the pre-inserted value instead.
220f22ef01cSRoman Divacky       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
221f22ef01cSRoman Divacky         Worklist.AddValue(EI.getOperand(0));
222f22ef01cSRoman Divacky         EI.setOperand(0, IE->getOperand(0));
223f22ef01cSRoman Divacky         return &EI;
224f22ef01cSRoman Divacky       }
225f22ef01cSRoman Divacky     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
226f22ef01cSRoman Divacky       // If this is extracting an element from a shufflevector, figure out where
227f22ef01cSRoman Divacky       // it came from and extract from the appropriate input element instead.
228f22ef01cSRoman Divacky       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
229dff0c46cSDimitry Andric         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
230f22ef01cSRoman Divacky         Value *Src;
231f22ef01cSRoman Divacky         unsigned LHSWidth =
232dff0c46cSDimitry Andric           SVI->getOperand(0)->getType()->getVectorNumElements();
233f22ef01cSRoman Divacky 
2342754fe60SDimitry Andric         if (SrcIdx < 0)
2353ca95b02SDimitry Andric           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
2362754fe60SDimitry Andric         if (SrcIdx < (int)LHSWidth)
237f22ef01cSRoman Divacky           Src = SVI->getOperand(0);
2382754fe60SDimitry Andric         else {
239f22ef01cSRoman Divacky           SrcIdx -= LHSWidth;
240f22ef01cSRoman Divacky           Src = SVI->getOperand(1);
241f22ef01cSRoman Divacky         }
2426122f3e6SDimitry Andric         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
243f22ef01cSRoman Divacky         return ExtractElementInst::Create(Src,
2442754fe60SDimitry Andric                                           ConstantInt::get(Int32Ty,
245f22ef01cSRoman Divacky                                                            SrcIdx, false));
246f22ef01cSRoman Divacky       }
2473b0f4066SDimitry Andric     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2487d523365SDimitry Andric       // Canonicalize extractelement(cast) -> cast(extractelement).
2497d523365SDimitry Andric       // Bitcasts can change the number of vector elements, and they cost
2507d523365SDimitry Andric       // nothing.
251284c1978SDimitry Andric       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
2523b0f4066SDimitry Andric         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
2533b0f4066SDimitry Andric                                                   EI.getIndexOperand());
254284c1978SDimitry Andric         Worklist.AddValue(EE);
2553b0f4066SDimitry Andric         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
256f22ef01cSRoman Divacky       }
257f785676fSDimitry Andric     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
258f785676fSDimitry Andric       if (SI->hasOneUse()) {
259f785676fSDimitry Andric         // TODO: For a select on vectors, it might be useful to do this if it
260f785676fSDimitry Andric         // has multiple extractelement uses. For vector select, that seems to
261f785676fSDimitry Andric         // fight the vectorizer.
262f785676fSDimitry Andric 
263f785676fSDimitry Andric         // If we are extracting an element from a vector select or a select on
2647d523365SDimitry Andric         // vectors, create a select on the scalars extracted from the vector
2657d523365SDimitry Andric         // arguments.
266f785676fSDimitry Andric         Value *TrueVal = SI->getTrueValue();
267f785676fSDimitry Andric         Value *FalseVal = SI->getFalseValue();
268f785676fSDimitry Andric 
269f785676fSDimitry Andric         Value *Cond = SI->getCondition();
270f785676fSDimitry Andric         if (Cond->getType()->isVectorTy()) {
271f785676fSDimitry Andric           Cond = Builder->CreateExtractElement(Cond,
272f785676fSDimitry Andric                                                EI.getIndexOperand(),
273f785676fSDimitry Andric                                                Cond->getName() + ".elt");
274f785676fSDimitry Andric         }
275f785676fSDimitry Andric 
276f785676fSDimitry Andric         Value *V1Elem
277f785676fSDimitry Andric           = Builder->CreateExtractElement(TrueVal,
278f785676fSDimitry Andric                                           EI.getIndexOperand(),
279f785676fSDimitry Andric                                           TrueVal->getName() + ".elt");
280f785676fSDimitry Andric 
281f785676fSDimitry Andric         Value *V2Elem
282f785676fSDimitry Andric           = Builder->CreateExtractElement(FalseVal,
283f785676fSDimitry Andric                                           EI.getIndexOperand(),
284f785676fSDimitry Andric                                           FalseVal->getName() + ".elt");
285f785676fSDimitry Andric         return SelectInst::Create(Cond,
286f785676fSDimitry Andric                                   V1Elem,
287f785676fSDimitry Andric                                   V2Elem,
288f785676fSDimitry Andric                                   SI->getName() + ".elt");
289f785676fSDimitry Andric       }
2903b0f4066SDimitry Andric     }
291f22ef01cSRoman Divacky   }
29291bc56edSDimitry Andric   return nullptr;
293f22ef01cSRoman Divacky }
294f22ef01cSRoman Divacky 
2957d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or
2967d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false.
2977d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
298dff0c46cSDimitry Andric                                          SmallVectorImpl<Constant*> &Mask) {
29991bc56edSDimitry Andric   assert(LHS->getType() == RHS->getType() &&
300f22ef01cSRoman Divacky          "Invalid CollectSingleShuffleElements");
301f785676fSDimitry Andric   unsigned NumElts = V->getType()->getVectorNumElements();
302f22ef01cSRoman Divacky 
303f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
304f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
305f22ef01cSRoman Divacky     return true;
306f22ef01cSRoman Divacky   }
307f22ef01cSRoman Divacky 
308f22ef01cSRoman Divacky   if (V == LHS) {
309f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
310f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
311f22ef01cSRoman Divacky     return true;
312f22ef01cSRoman Divacky   }
313f22ef01cSRoman Divacky 
314f22ef01cSRoman Divacky   if (V == RHS) {
315f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
316f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
317f22ef01cSRoman Divacky                                       i+NumElts));
318f22ef01cSRoman Divacky     return true;
319f22ef01cSRoman Divacky   }
320f22ef01cSRoman Divacky 
321f22ef01cSRoman Divacky   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
322f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
323f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
324f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
325f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
326f22ef01cSRoman Divacky 
327f22ef01cSRoman Divacky     if (!isa<ConstantInt>(IdxOp))
328f22ef01cSRoman Divacky       return false;
329f22ef01cSRoman Divacky     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
330f22ef01cSRoman Divacky 
331f22ef01cSRoman Divacky     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
33291bc56edSDimitry Andric       // We can handle this if the vector we are inserting into is
333f22ef01cSRoman Divacky       // transitively ok.
3347d523365SDimitry Andric       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
335f22ef01cSRoman Divacky         // If so, update the mask to reflect the inserted undef.
336f22ef01cSRoman Divacky         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
337f22ef01cSRoman Divacky         return true;
338f22ef01cSRoman Divacky       }
339f22ef01cSRoman Divacky     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
34091bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1))) {
341f22ef01cSRoman Divacky         unsigned ExtractedIdx =
342f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
34391bc56edSDimitry Andric         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
344f22ef01cSRoman Divacky 
345f22ef01cSRoman Divacky         // This must be extracting from either LHS or RHS.
346f22ef01cSRoman Divacky         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
34791bc56edSDimitry Andric           // We can handle this if the vector we are inserting into is
348f22ef01cSRoman Divacky           // transitively ok.
3497d523365SDimitry Andric           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
350f22ef01cSRoman Divacky             // If so, update the mask to reflect the inserted value.
351f22ef01cSRoman Divacky             if (EI->getOperand(0) == LHS) {
352f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
353f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
354f22ef01cSRoman Divacky                                ExtractedIdx);
355f22ef01cSRoman Divacky             } else {
356f22ef01cSRoman Divacky               assert(EI->getOperand(0) == RHS);
357f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
358f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
35991bc56edSDimitry Andric                                ExtractedIdx + NumLHSElts);
360f22ef01cSRoman Divacky             }
361f22ef01cSRoman Divacky             return true;
362f22ef01cSRoman Divacky           }
363f22ef01cSRoman Divacky         }
364f22ef01cSRoman Divacky       }
365f22ef01cSRoman Divacky     }
366f22ef01cSRoman Divacky   }
367f22ef01cSRoman Divacky 
368f22ef01cSRoman Divacky   return false;
369f22ef01cSRoman Divacky }
370f22ef01cSRoman Divacky 
3717d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we
3727d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single
3737d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs.
3747d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt,
3757d523365SDimitry Andric                                    ExtractElementInst *ExtElt,
3767d523365SDimitry Andric                                    InstCombiner &IC) {
3777d523365SDimitry Andric   VectorType *InsVecType = InsElt->getType();
3787d523365SDimitry Andric   VectorType *ExtVecType = ExtElt->getVectorOperandType();
3797d523365SDimitry Andric   unsigned NumInsElts = InsVecType->getVectorNumElements();
3807d523365SDimitry Andric   unsigned NumExtElts = ExtVecType->getVectorNumElements();
3817d523365SDimitry Andric 
3827d523365SDimitry Andric   // The inserted-to vector must be wider than the extracted-from vector.
3837d523365SDimitry Andric   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
3847d523365SDimitry Andric       NumExtElts >= NumInsElts)
3857d523365SDimitry Andric     return;
3867d523365SDimitry Andric 
3877d523365SDimitry Andric   // Create a shuffle mask to widen the extended-from vector using undefined
3887d523365SDimitry Andric   // values. The mask selects all of the values of the original vector followed
3897d523365SDimitry Andric   // by as many undefined values as needed to create a vector of the same length
3907d523365SDimitry Andric   // as the inserted-to vector.
3917d523365SDimitry Andric   SmallVector<Constant *, 16> ExtendMask;
3927d523365SDimitry Andric   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
3937d523365SDimitry Andric   for (unsigned i = 0; i < NumExtElts; ++i)
3947d523365SDimitry Andric     ExtendMask.push_back(ConstantInt::get(IntType, i));
3957d523365SDimitry Andric   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
3967d523365SDimitry Andric     ExtendMask.push_back(UndefValue::get(IntType));
3977d523365SDimitry Andric 
3987d523365SDimitry Andric   Value *ExtVecOp = ExtElt->getVectorOperand();
399a8bcc4d8SDimitry Andric   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
400a8bcc4d8SDimitry Andric   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
401a8bcc4d8SDimitry Andric                                    ? ExtVecOpInst->getParent()
402a8bcc4d8SDimitry Andric                                    : ExtElt->getParent();
403a8bcc4d8SDimitry Andric 
404a8bcc4d8SDimitry Andric   // TODO: This restriction matches the basic block check below when creating
405a8bcc4d8SDimitry Andric   // new extractelement instructions. If that limitation is removed, this one
406a8bcc4d8SDimitry Andric   // could also be removed. But for now, we just bail out to ensure that we
407a8bcc4d8SDimitry Andric   // will replace the extractelement instruction that is feeding our
408a8bcc4d8SDimitry Andric   // insertelement instruction. This allows the insertelement to then be
409a8bcc4d8SDimitry Andric   // replaced by a shufflevector. If the insertelement is not replaced, we can
410a8bcc4d8SDimitry Andric   // induce infinite looping because there's an optimization for extractelement
411a8bcc4d8SDimitry Andric   // that will delete our widening shuffle. This would trigger another attempt
412a8bcc4d8SDimitry Andric   // here to create that shuffle, and we spin forever.
413a8bcc4d8SDimitry Andric   if (InsertionBlock != InsElt->getParent())
414a8bcc4d8SDimitry Andric     return;
415a8bcc4d8SDimitry Andric 
416d88c1a5aSDimitry Andric   // TODO: This restriction matches the check in visitInsertElementInst() and
417d88c1a5aSDimitry Andric   // prevents an infinite loop caused by not turning the extract/insert pair
418d88c1a5aSDimitry Andric   // into a shuffle. We really should not need either check, but we're lacking
419d88c1a5aSDimitry Andric   // folds for shufflevectors because we're afraid to generate shuffle masks
420d88c1a5aSDimitry Andric   // that the backend can't handle.
421d88c1a5aSDimitry Andric   if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
422d88c1a5aSDimitry Andric     return;
423d88c1a5aSDimitry Andric 
4247d523365SDimitry Andric   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
4257d523365SDimitry Andric                                         ConstantVector::get(ExtendMask));
4267d523365SDimitry Andric 
4274d0b32cdSDimitry Andric   // Insert the new shuffle after the vector operand of the extract is defined
428444ed5c5SDimitry Andric   // (as long as it's not a PHI) or at the start of the basic block of the
429444ed5c5SDimitry Andric   // extract, so any subsequent extracts in the same basic block can use it.
430444ed5c5SDimitry Andric   // TODO: Insert before the earliest ExtractElementInst that is replaced.
431444ed5c5SDimitry Andric   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
4324d0b32cdSDimitry Andric     WideVec->insertAfter(ExtVecOpInst);
433444ed5c5SDimitry Andric   else
4344d0b32cdSDimitry Andric     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
4354d0b32cdSDimitry Andric 
4364d0b32cdSDimitry Andric   // Replace extracts from the original narrow vector with extracts from the new
4374d0b32cdSDimitry Andric   // wide vector.
4387d523365SDimitry Andric   for (User *U : ExtVecOp->users()) {
4394d0b32cdSDimitry Andric     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
440444ed5c5SDimitry Andric     if (!OldExt || OldExt->getParent() != WideVec->getParent())
4414d0b32cdSDimitry Andric       continue;
4427d523365SDimitry Andric     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
4437d523365SDimitry Andric     NewExt->insertAfter(WideVec);
4443ca95b02SDimitry Andric     IC.replaceInstUsesWith(*OldExt, NewExt);
4457d523365SDimitry Andric   }
4467d523365SDimitry Andric }
44791bc56edSDimitry Andric 
44891bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement,
44991bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or
45091bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the
45191bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask
45291bc56edSDimitry Andric /// parameter as required.
45391bc56edSDimitry Andric ///
45491bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have
45591bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target.
45691bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps;
45791bc56edSDimitry Andric 
4587d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V,
45991bc56edSDimitry Andric                                          SmallVectorImpl<Constant *> &Mask,
4607d523365SDimitry Andric                                          Value *PermittedRHS,
4617d523365SDimitry Andric                                          InstCombiner &IC) {
46291bc56edSDimitry Andric   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
463d88c1a5aSDimitry Andric   unsigned NumElts = V->getType()->getVectorNumElements();
464f22ef01cSRoman Divacky 
465f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
466f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
46791bc56edSDimitry Andric     return std::make_pair(
46891bc56edSDimitry Andric         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
469dff0c46cSDimitry Andric   }
470dff0c46cSDimitry Andric 
471dff0c46cSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
472f22ef01cSRoman Divacky     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
47391bc56edSDimitry Andric     return std::make_pair(V, nullptr);
474dff0c46cSDimitry Andric   }
475dff0c46cSDimitry Andric 
476dff0c46cSDimitry Andric   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
477f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
478f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
479f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
480f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
481f22ef01cSRoman Divacky 
482f22ef01cSRoman Divacky     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
48391bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
484f22ef01cSRoman Divacky         unsigned ExtractedIdx =
485f22ef01cSRoman Divacky           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
486f22ef01cSRoman Divacky         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
487f22ef01cSRoman Divacky 
488f22ef01cSRoman Divacky         // Either the extracted from or inserted into vector must be RHSVec,
489f22ef01cSRoman Divacky         // otherwise we'd end up with a shuffle of three inputs.
49091bc56edSDimitry Andric         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
49191bc56edSDimitry Andric           Value *RHS = EI->getOperand(0);
4927d523365SDimitry Andric           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
49391bc56edSDimitry Andric           assert(LR.second == nullptr || LR.second == RHS);
49491bc56edSDimitry Andric 
49591bc56edSDimitry Andric           if (LR.first->getType() != RHS->getType()) {
4967d523365SDimitry Andric             // Although we are giving up for now, see if we can create extracts
4977d523365SDimitry Andric             // that match the inserts for another round of combining.
4987d523365SDimitry Andric             replaceExtractElements(IEI, EI, IC);
4997d523365SDimitry Andric 
50091bc56edSDimitry Andric             // We tried our best, but we can't find anything compatible with RHS
50191bc56edSDimitry Andric             // further up the chain. Return a trivial shuffle.
50291bc56edSDimitry Andric             for (unsigned i = 0; i < NumElts; ++i)
50391bc56edSDimitry Andric               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
50491bc56edSDimitry Andric             return std::make_pair(V, nullptr);
50591bc56edSDimitry Andric           }
50691bc56edSDimitry Andric 
50791bc56edSDimitry Andric           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
508f22ef01cSRoman Divacky           Mask[InsertedIdx % NumElts] =
509f22ef01cSRoman Divacky             ConstantInt::get(Type::getInt32Ty(V->getContext()),
51091bc56edSDimitry Andric                              NumLHSElts+ExtractedIdx);
51191bc56edSDimitry Andric           return std::make_pair(LR.first, RHS);
512f22ef01cSRoman Divacky         }
513f22ef01cSRoman Divacky 
51491bc56edSDimitry Andric         if (VecOp == PermittedRHS) {
51591bc56edSDimitry Andric           // We've gone as far as we can: anything on the other side of the
51691bc56edSDimitry Andric           // extractelement will already have been converted into a shuffle.
51791bc56edSDimitry Andric           unsigned NumLHSElts =
51891bc56edSDimitry Andric               EI->getOperand(0)->getType()->getVectorNumElements();
51991bc56edSDimitry Andric           for (unsigned i = 0; i != NumElts; ++i)
52091bc56edSDimitry Andric             Mask.push_back(ConstantInt::get(
52191bc56edSDimitry Andric                 Type::getInt32Ty(V->getContext()),
52291bc56edSDimitry Andric                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
52391bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
524f22ef01cSRoman Divacky         }
525f22ef01cSRoman Divacky 
526f22ef01cSRoman Divacky         // If this insertelement is a chain that comes from exactly these two
527f22ef01cSRoman Divacky         // vectors, return the vector and the effective shuffle.
52891bc56edSDimitry Andric         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
5297d523365SDimitry Andric             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
53091bc56edSDimitry Andric                                          Mask))
53191bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
532f22ef01cSRoman Divacky       }
533f22ef01cSRoman Divacky     }
534f22ef01cSRoman Divacky   }
535f22ef01cSRoman Divacky 
5367d523365SDimitry Andric   // Otherwise, we can't do anything fancy. Return an identity vector.
537f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumElts; ++i)
538f22ef01cSRoman Divacky     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
53991bc56edSDimitry Andric   return std::make_pair(V, nullptr);
54091bc56edSDimitry Andric }
54191bc56edSDimitry Andric 
54291bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones:
54391bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
54491bc56edSDimitry Andric ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
54591bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the
54691bc56edSDimitry Andric /// first one, making the first one redundant.
54791bc56edSDimitry Andric /// It should be transformed to:
54891bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
54991bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
55091bc56edSDimitry Andric   bool IsRedundant = false;
55191bc56edSDimitry Andric   ArrayRef<unsigned int> FirstIndices = I.getIndices();
55291bc56edSDimitry Andric 
55391bc56edSDimitry Andric   // If there is a chain of insertvalue instructions (each of them except the
55491bc56edSDimitry Andric   // last one has only one use and it's another insertvalue insn from this
55591bc56edSDimitry Andric   // chain), check if any of the 'children' uses the same indices as the first
55691bc56edSDimitry Andric   // instruction. In this case, the first one is redundant.
55791bc56edSDimitry Andric   Value *V = &I;
55891bc56edSDimitry Andric   unsigned Depth = 0;
55991bc56edSDimitry Andric   while (V->hasOneUse() && Depth < 10) {
56091bc56edSDimitry Andric     User *U = V->user_back();
56191bc56edSDimitry Andric     auto UserInsInst = dyn_cast<InsertValueInst>(U);
56291bc56edSDimitry Andric     if (!UserInsInst || U->getOperand(0) != V)
56391bc56edSDimitry Andric       break;
56491bc56edSDimitry Andric     if (UserInsInst->getIndices() == FirstIndices) {
56591bc56edSDimitry Andric       IsRedundant = true;
56691bc56edSDimitry Andric       break;
56791bc56edSDimitry Andric     }
56891bc56edSDimitry Andric     V = UserInsInst;
56991bc56edSDimitry Andric     Depth++;
57091bc56edSDimitry Andric   }
57191bc56edSDimitry Andric 
57291bc56edSDimitry Andric   if (IsRedundant)
5733ca95b02SDimitry Andric     return replaceInstUsesWith(I, I.getOperand(0));
57491bc56edSDimitry Andric   return nullptr;
575f22ef01cSRoman Divacky }
576f22ef01cSRoman Divacky 
577d88c1a5aSDimitry Andric static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
578d88c1a5aSDimitry Andric   int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
579d88c1a5aSDimitry Andric   int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
580d88c1a5aSDimitry Andric 
581d88c1a5aSDimitry Andric   // A vector select does not change the size of the operands.
582d88c1a5aSDimitry Andric   if (MaskSize != VecSize)
583d88c1a5aSDimitry Andric     return false;
584d88c1a5aSDimitry Andric 
585d88c1a5aSDimitry Andric   // Each mask element must be undefined or choose a vector element from one of
586d88c1a5aSDimitry Andric   // the source operands without crossing vector lanes.
587d88c1a5aSDimitry Andric   for (int i = 0; i != MaskSize; ++i) {
588d88c1a5aSDimitry Andric     int Elt = Shuf.getMaskValue(i);
589d88c1a5aSDimitry Andric     if (Elt != -1 && Elt != i && Elt != i + VecSize)
590d88c1a5aSDimitry Andric       return false;
591d88c1a5aSDimitry Andric   }
592d88c1a5aSDimitry Andric 
593d88c1a5aSDimitry Andric   return true;
594d88c1a5aSDimitry Andric }
595d88c1a5aSDimitry Andric 
596d88c1a5aSDimitry Andric // Turn a chain of inserts that splats a value into a canonical insert + shuffle
597d88c1a5aSDimitry Andric // splat. That is:
598d88c1a5aSDimitry Andric // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
599d88c1a5aSDimitry Andric // shufflevector(insertelt(X, %k, 0), undef, zero)
600d88c1a5aSDimitry Andric static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
601d88c1a5aSDimitry Andric   // We are interested in the last insert in a chain. So, if this insert
602d88c1a5aSDimitry Andric   // has a single user, and that user is an insert, bail.
603d88c1a5aSDimitry Andric   if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
604d88c1a5aSDimitry Andric     return nullptr;
605d88c1a5aSDimitry Andric 
606d88c1a5aSDimitry Andric   VectorType *VT = cast<VectorType>(InsElt.getType());
607d88c1a5aSDimitry Andric   int NumElements = VT->getNumElements();
608d88c1a5aSDimitry Andric 
609d88c1a5aSDimitry Andric   // Do not try to do this for a one-element vector, since that's a nop,
610d88c1a5aSDimitry Andric   // and will cause an inf-loop.
611d88c1a5aSDimitry Andric   if (NumElements == 1)
612d88c1a5aSDimitry Andric     return nullptr;
613d88c1a5aSDimitry Andric 
614d88c1a5aSDimitry Andric   Value *SplatVal = InsElt.getOperand(1);
615d88c1a5aSDimitry Andric   InsertElementInst *CurrIE = &InsElt;
616d88c1a5aSDimitry Andric   SmallVector<bool, 16> ElementPresent(NumElements, false);
617d88c1a5aSDimitry Andric 
618d88c1a5aSDimitry Andric   // Walk the chain backwards, keeping track of which indices we inserted into,
619d88c1a5aSDimitry Andric   // until we hit something that isn't an insert of the splatted value.
620d88c1a5aSDimitry Andric   while (CurrIE) {
621d88c1a5aSDimitry Andric     ConstantInt *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
622d88c1a5aSDimitry Andric     if (!Idx || CurrIE->getOperand(1) != SplatVal)
623d88c1a5aSDimitry Andric       return nullptr;
624d88c1a5aSDimitry Andric 
625d88c1a5aSDimitry Andric     // Check none of the intermediate steps have any additional uses.
626d88c1a5aSDimitry Andric     if ((CurrIE != &InsElt) && !CurrIE->hasOneUse())
627d88c1a5aSDimitry Andric       return nullptr;
628d88c1a5aSDimitry Andric 
629d88c1a5aSDimitry Andric     ElementPresent[Idx->getZExtValue()] = true;
630d88c1a5aSDimitry Andric     CurrIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
631d88c1a5aSDimitry Andric   }
632d88c1a5aSDimitry Andric 
633d88c1a5aSDimitry Andric   // Make sure we've seen an insert into every element.
634d88c1a5aSDimitry Andric   if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
635d88c1a5aSDimitry Andric     return nullptr;
636d88c1a5aSDimitry Andric 
637d88c1a5aSDimitry Andric   // All right, create the insert + shuffle.
638d88c1a5aSDimitry Andric   Instruction *InsertFirst = InsertElementInst::Create(
639d88c1a5aSDimitry Andric       UndefValue::get(VT), SplatVal,
640d88c1a5aSDimitry Andric       ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), "", &InsElt);
641d88c1a5aSDimitry Andric 
642d88c1a5aSDimitry Andric   Constant *ZeroMask = ConstantAggregateZero::get(
643d88c1a5aSDimitry Andric       VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
644d88c1a5aSDimitry Andric 
645d88c1a5aSDimitry Andric   return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
646d88c1a5aSDimitry Andric }
647d88c1a5aSDimitry Andric 
6487a7e6055SDimitry Andric /// If we have an insertelement instruction feeding into another insertelement
6497a7e6055SDimitry Andric /// and the 2nd is inserting a constant into the vector, canonicalize that
6507a7e6055SDimitry Andric /// constant insertion before the insertion of a variable:
6517a7e6055SDimitry Andric ///
6527a7e6055SDimitry Andric /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
6537a7e6055SDimitry Andric /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
6547a7e6055SDimitry Andric ///
6557a7e6055SDimitry Andric /// This has the potential of eliminating the 2nd insertelement instruction
6567a7e6055SDimitry Andric /// via constant folding of the scalar constant into a vector constant.
6577a7e6055SDimitry Andric static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
6587a7e6055SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
6597a7e6055SDimitry Andric   auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
6607a7e6055SDimitry Andric   if (!InsElt1 || !InsElt1->hasOneUse())
6617a7e6055SDimitry Andric     return nullptr;
6627a7e6055SDimitry Andric 
6637a7e6055SDimitry Andric   Value *X, *Y;
6647a7e6055SDimitry Andric   Constant *ScalarC;
6657a7e6055SDimitry Andric   ConstantInt *IdxC1, *IdxC2;
6667a7e6055SDimitry Andric   if (match(InsElt1->getOperand(0), m_Value(X)) &&
6677a7e6055SDimitry Andric       match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
6687a7e6055SDimitry Andric       match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
6697a7e6055SDimitry Andric       match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
6707a7e6055SDimitry Andric       match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
6717a7e6055SDimitry Andric     Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
6727a7e6055SDimitry Andric     return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
6737a7e6055SDimitry Andric   }
6747a7e6055SDimitry Andric 
6757a7e6055SDimitry Andric   return nullptr;
6767a7e6055SDimitry Andric }
6777a7e6055SDimitry Andric 
678d88c1a5aSDimitry Andric /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
679d88c1a5aSDimitry Andric /// --> shufflevector X, CVec', Mask'
680d88c1a5aSDimitry Andric static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
681d88c1a5aSDimitry Andric   auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
682d88c1a5aSDimitry Andric   // Bail out if the parent has more than one use. In that case, we'd be
683d88c1a5aSDimitry Andric   // replacing the insertelt with a shuffle, and that's not a clear win.
684d88c1a5aSDimitry Andric   if (!Inst || !Inst->hasOneUse())
685d88c1a5aSDimitry Andric     return nullptr;
686d88c1a5aSDimitry Andric   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
687d88c1a5aSDimitry Andric     // The shuffle must have a constant vector operand. The insertelt must have
688d88c1a5aSDimitry Andric     // a constant scalar being inserted at a constant position in the vector.
689d88c1a5aSDimitry Andric     Constant *ShufConstVec, *InsEltScalar;
690d88c1a5aSDimitry Andric     uint64_t InsEltIndex;
691d88c1a5aSDimitry Andric     if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
692d88c1a5aSDimitry Andric         !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
693d88c1a5aSDimitry Andric         !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
694d88c1a5aSDimitry Andric       return nullptr;
695d88c1a5aSDimitry Andric 
696d88c1a5aSDimitry Andric     // Adding an element to an arbitrary shuffle could be expensive, but a
697d88c1a5aSDimitry Andric     // shuffle that selects elements from vectors without crossing lanes is
698d88c1a5aSDimitry Andric     // assumed cheap.
699d88c1a5aSDimitry Andric     // If we're just adding a constant into that shuffle, it will still be
700d88c1a5aSDimitry Andric     // cheap.
701d88c1a5aSDimitry Andric     if (!isShuffleEquivalentToSelect(*Shuf))
702d88c1a5aSDimitry Andric       return nullptr;
703d88c1a5aSDimitry Andric 
704d88c1a5aSDimitry Andric     // From the above 'select' check, we know that the mask has the same number
705d88c1a5aSDimitry Andric     // of elements as the vector input operands. We also know that each constant
706d88c1a5aSDimitry Andric     // input element is used in its lane and can not be used more than once by
707d88c1a5aSDimitry Andric     // the shuffle. Therefore, replace the constant in the shuffle's constant
708d88c1a5aSDimitry Andric     // vector with the insertelt constant. Replace the constant in the shuffle's
709d88c1a5aSDimitry Andric     // mask vector with the insertelt index plus the length of the vector
710d88c1a5aSDimitry Andric     // (because the constant vector operand of a shuffle is always the 2nd
711d88c1a5aSDimitry Andric     // operand).
712d88c1a5aSDimitry Andric     Constant *Mask = Shuf->getMask();
713d88c1a5aSDimitry Andric     unsigned NumElts = Mask->getType()->getVectorNumElements();
714d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> NewShufElts(NumElts);
715d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> NewMaskElts(NumElts);
716d88c1a5aSDimitry Andric     for (unsigned I = 0; I != NumElts; ++I) {
717d88c1a5aSDimitry Andric       if (I == InsEltIndex) {
718d88c1a5aSDimitry Andric         NewShufElts[I] = InsEltScalar;
719d88c1a5aSDimitry Andric         Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
720d88c1a5aSDimitry Andric         NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
721d88c1a5aSDimitry Andric       } else {
722d88c1a5aSDimitry Andric         // Copy over the existing values.
723d88c1a5aSDimitry Andric         NewShufElts[I] = ShufConstVec->getAggregateElement(I);
724d88c1a5aSDimitry Andric         NewMaskElts[I] = Mask->getAggregateElement(I);
725d88c1a5aSDimitry Andric       }
726d88c1a5aSDimitry Andric     }
727d88c1a5aSDimitry Andric 
728d88c1a5aSDimitry Andric     // Create new operands for a shuffle that includes the constant of the
729d88c1a5aSDimitry Andric     // original insertelt. The old shuffle will be dead now.
730d88c1a5aSDimitry Andric     return new ShuffleVectorInst(Shuf->getOperand(0),
731d88c1a5aSDimitry Andric                                  ConstantVector::get(NewShufElts),
732d88c1a5aSDimitry Andric                                  ConstantVector::get(NewMaskElts));
733d88c1a5aSDimitry Andric   } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
734d88c1a5aSDimitry Andric     // Transform sequences of insertelements ops with constant data/indexes into
735d88c1a5aSDimitry Andric     // a single shuffle op.
736d88c1a5aSDimitry Andric     unsigned NumElts = InsElt.getType()->getNumElements();
737d88c1a5aSDimitry Andric 
738d88c1a5aSDimitry Andric     uint64_t InsertIdx[2];
739d88c1a5aSDimitry Andric     Constant *Val[2];
740d88c1a5aSDimitry Andric     if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
741d88c1a5aSDimitry Andric         !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
742d88c1a5aSDimitry Andric         !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
743d88c1a5aSDimitry Andric         !match(IEI->getOperand(1), m_Constant(Val[1])))
744d88c1a5aSDimitry Andric       return nullptr;
745d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> Values(NumElts);
746d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> Mask(NumElts);
747d88c1a5aSDimitry Andric     auto ValI = std::begin(Val);
748d88c1a5aSDimitry Andric     // Generate new constant vector and mask.
749d88c1a5aSDimitry Andric     // We have 2 values/masks from the insertelements instructions. Insert them
750d88c1a5aSDimitry Andric     // into new value/mask vectors.
751d88c1a5aSDimitry Andric     for (uint64_t I : InsertIdx) {
752d88c1a5aSDimitry Andric       if (!Values[I]) {
753d88c1a5aSDimitry Andric         assert(!Mask[I]);
754d88c1a5aSDimitry Andric         Values[I] = *ValI;
755d88c1a5aSDimitry Andric         Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
756d88c1a5aSDimitry Andric                                    NumElts + I);
757d88c1a5aSDimitry Andric       }
758d88c1a5aSDimitry Andric       ++ValI;
759d88c1a5aSDimitry Andric     }
760d88c1a5aSDimitry Andric     // Remaining values are filled with 'undef' values.
761d88c1a5aSDimitry Andric     for (unsigned I = 0; I < NumElts; ++I) {
762d88c1a5aSDimitry Andric       if (!Values[I]) {
763d88c1a5aSDimitry Andric         assert(!Mask[I]);
764d88c1a5aSDimitry Andric         Values[I] = UndefValue::get(InsElt.getType()->getElementType());
765d88c1a5aSDimitry Andric         Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
766d88c1a5aSDimitry Andric       }
767d88c1a5aSDimitry Andric     }
768d88c1a5aSDimitry Andric     // Create new operands for a shuffle that includes the constant of the
769d88c1a5aSDimitry Andric     // original insertelt.
770d88c1a5aSDimitry Andric     return new ShuffleVectorInst(IEI->getOperand(0),
771d88c1a5aSDimitry Andric                                  ConstantVector::get(Values),
772d88c1a5aSDimitry Andric                                  ConstantVector::get(Mask));
773d88c1a5aSDimitry Andric   }
774d88c1a5aSDimitry Andric   return nullptr;
775d88c1a5aSDimitry Andric }
776d88c1a5aSDimitry Andric 
777f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
778f22ef01cSRoman Divacky   Value *VecOp    = IE.getOperand(0);
779f22ef01cSRoman Divacky   Value *ScalarOp = IE.getOperand(1);
780f22ef01cSRoman Divacky   Value *IdxOp    = IE.getOperand(2);
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky   // Inserting an undef or into an undefined place, remove this.
783f22ef01cSRoman Divacky   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
7843ca95b02SDimitry Andric     replaceInstUsesWith(IE, VecOp);
785f22ef01cSRoman Divacky 
786f22ef01cSRoman Divacky   // If the inserted element was extracted from some other vector, and if the
787f22ef01cSRoman Divacky   // indexes are constant, try to turn this into a shufflevector operation.
788f22ef01cSRoman Divacky   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
78991bc56edSDimitry Andric     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
79091bc56edSDimitry Andric       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
79191bc56edSDimitry Andric       unsigned NumExtractVectorElts =
79291bc56edSDimitry Andric           EI->getOperand(0)->getType()->getVectorNumElements();
793f22ef01cSRoman Divacky       unsigned ExtractedIdx =
794f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
795f22ef01cSRoman Divacky       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
796f22ef01cSRoman Divacky 
79791bc56edSDimitry Andric       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
7983ca95b02SDimitry Andric         return replaceInstUsesWith(IE, VecOp);
799f22ef01cSRoman Divacky 
80091bc56edSDimitry Andric       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
8013ca95b02SDimitry Andric         return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
802f22ef01cSRoman Divacky 
803f22ef01cSRoman Divacky       // If we are extracting a value from a vector, then inserting it right
804f22ef01cSRoman Divacky       // back into the same place, just use the input vector.
805f22ef01cSRoman Divacky       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8063ca95b02SDimitry Andric         return replaceInstUsesWith(IE, VecOp);
807f22ef01cSRoman Divacky 
808f22ef01cSRoman Divacky       // If this insertelement isn't used by some other insertelement, turn it
809f22ef01cSRoman Divacky       // (and any insertelements it points to), into one big shuffle.
81091bc56edSDimitry Andric       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
811dff0c46cSDimitry Andric         SmallVector<Constant*, 16> Mask;
8127d523365SDimitry Andric         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
81391bc56edSDimitry Andric 
81491bc56edSDimitry Andric         // The proposed shuffle may be trivial, in which case we shouldn't
81591bc56edSDimitry Andric         // perform the combine.
81691bc56edSDimitry Andric         if (LR.first != &IE && LR.second != &IE) {
817f22ef01cSRoman Divacky           // We now have a shuffle of LHS, RHS, Mask.
81891bc56edSDimitry Andric           if (LR.second == nullptr)
81991bc56edSDimitry Andric             LR.second = UndefValue::get(LR.first->getType());
82091bc56edSDimitry Andric           return new ShuffleVectorInst(LR.first, LR.second,
82191bc56edSDimitry Andric                                        ConstantVector::get(Mask));
82291bc56edSDimitry Andric         }
823f22ef01cSRoman Divacky       }
824f22ef01cSRoman Divacky     }
825f22ef01cSRoman Divacky   }
826f22ef01cSRoman Divacky 
827d88c1a5aSDimitry Andric   unsigned VWidth = VecOp->getType()->getVectorNumElements();
828f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
829f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
8302754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
8312754fe60SDimitry Andric     if (V != &IE)
8323ca95b02SDimitry Andric       return replaceInstUsesWith(IE, V);
833f22ef01cSRoman Divacky     return &IE;
8342754fe60SDimitry Andric   }
835f22ef01cSRoman Divacky 
836d88c1a5aSDimitry Andric   if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
837d88c1a5aSDimitry Andric     return Shuf;
838d88c1a5aSDimitry Andric 
8397a7e6055SDimitry Andric   if (Instruction *NewInsElt = hoistInsEltConst(IE, *Builder))
8407a7e6055SDimitry Andric     return NewInsElt;
8417a7e6055SDimitry Andric 
842d88c1a5aSDimitry Andric   // Turn a sequence of inserts that broadcasts a scalar into a single
843d88c1a5aSDimitry Andric   // insert + shufflevector.
844d88c1a5aSDimitry Andric   if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
845d88c1a5aSDimitry Andric     return Broadcast;
846d88c1a5aSDimitry Andric 
84791bc56edSDimitry Andric   return nullptr;
848f22ef01cSRoman Divacky }
849f22ef01cSRoman Divacky 
850f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector
851f785676fSDimitry Andric /// elements were shuffled in a different order.
852f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
853f785676fSDimitry Andric                                 unsigned Depth = 5) {
854f785676fSDimitry Andric   // We can always reorder the elements of a constant.
855f785676fSDimitry Andric   if (isa<Constant>(V))
856f785676fSDimitry Andric     return true;
857f785676fSDimitry Andric 
858f785676fSDimitry Andric   // We won't reorder vector arguments. No IPO here.
859f785676fSDimitry Andric   Instruction *I = dyn_cast<Instruction>(V);
860f785676fSDimitry Andric   if (!I) return false;
861f785676fSDimitry Andric 
862f785676fSDimitry Andric   // Two users may expect different orders of the elements. Don't try it.
863f785676fSDimitry Andric   if (!I->hasOneUse())
864f785676fSDimitry Andric     return false;
865f785676fSDimitry Andric 
866f785676fSDimitry Andric   if (Depth == 0) return false;
867f785676fSDimitry Andric 
868f785676fSDimitry Andric   switch (I->getOpcode()) {
869f785676fSDimitry Andric     case Instruction::Add:
870f785676fSDimitry Andric     case Instruction::FAdd:
871f785676fSDimitry Andric     case Instruction::Sub:
872f785676fSDimitry Andric     case Instruction::FSub:
873f785676fSDimitry Andric     case Instruction::Mul:
874f785676fSDimitry Andric     case Instruction::FMul:
875f785676fSDimitry Andric     case Instruction::UDiv:
876f785676fSDimitry Andric     case Instruction::SDiv:
877f785676fSDimitry Andric     case Instruction::FDiv:
878f785676fSDimitry Andric     case Instruction::URem:
879f785676fSDimitry Andric     case Instruction::SRem:
880f785676fSDimitry Andric     case Instruction::FRem:
881f785676fSDimitry Andric     case Instruction::Shl:
882f785676fSDimitry Andric     case Instruction::LShr:
883f785676fSDimitry Andric     case Instruction::AShr:
884f785676fSDimitry Andric     case Instruction::And:
885f785676fSDimitry Andric     case Instruction::Or:
886f785676fSDimitry Andric     case Instruction::Xor:
887f785676fSDimitry Andric     case Instruction::ICmp:
888f785676fSDimitry Andric     case Instruction::FCmp:
889f785676fSDimitry Andric     case Instruction::Trunc:
890f785676fSDimitry Andric     case Instruction::ZExt:
891f785676fSDimitry Andric     case Instruction::SExt:
892f785676fSDimitry Andric     case Instruction::FPToUI:
893f785676fSDimitry Andric     case Instruction::FPToSI:
894f785676fSDimitry Andric     case Instruction::UIToFP:
895f785676fSDimitry Andric     case Instruction::SIToFP:
896f785676fSDimitry Andric     case Instruction::FPTrunc:
897f785676fSDimitry Andric     case Instruction::FPExt:
898f785676fSDimitry Andric     case Instruction::GetElementPtr: {
8997d523365SDimitry Andric       for (Value *Operand : I->operands()) {
9007d523365SDimitry Andric         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
901f785676fSDimitry Andric           return false;
902f785676fSDimitry Andric       }
903f785676fSDimitry Andric       return true;
904f785676fSDimitry Andric     }
905f785676fSDimitry Andric     case Instruction::InsertElement: {
906f785676fSDimitry Andric       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
907f785676fSDimitry Andric       if (!CI) return false;
908f785676fSDimitry Andric       int ElementNumber = CI->getLimitedValue();
909f785676fSDimitry Andric 
910f785676fSDimitry Andric       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
911f785676fSDimitry Andric       // can't put an element into multiple indices.
912f785676fSDimitry Andric       bool SeenOnce = false;
913f785676fSDimitry Andric       for (int i = 0, e = Mask.size(); i != e; ++i) {
914f785676fSDimitry Andric         if (Mask[i] == ElementNumber) {
915f785676fSDimitry Andric           if (SeenOnce)
916f785676fSDimitry Andric             return false;
917f785676fSDimitry Andric           SeenOnce = true;
918f785676fSDimitry Andric         }
919f785676fSDimitry Andric       }
920f785676fSDimitry Andric       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
921f785676fSDimitry Andric     }
922f785676fSDimitry Andric   }
923f785676fSDimitry Andric   return false;
924f785676fSDimitry Andric }
925f785676fSDimitry Andric 
926f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given.
927f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct.
9287d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
929f785676fSDimitry Andric   // We don't want to use the IRBuilder here because we want the replacement
930f785676fSDimitry Andric   // instructions to appear next to 'I', not the builder's insertion point.
931f785676fSDimitry Andric   switch (I->getOpcode()) {
932f785676fSDimitry Andric     case Instruction::Add:
933f785676fSDimitry Andric     case Instruction::FAdd:
934f785676fSDimitry Andric     case Instruction::Sub:
935f785676fSDimitry Andric     case Instruction::FSub:
936f785676fSDimitry Andric     case Instruction::Mul:
937f785676fSDimitry Andric     case Instruction::FMul:
938f785676fSDimitry Andric     case Instruction::UDiv:
939f785676fSDimitry Andric     case Instruction::SDiv:
940f785676fSDimitry Andric     case Instruction::FDiv:
941f785676fSDimitry Andric     case Instruction::URem:
942f785676fSDimitry Andric     case Instruction::SRem:
943f785676fSDimitry Andric     case Instruction::FRem:
944f785676fSDimitry Andric     case Instruction::Shl:
945f785676fSDimitry Andric     case Instruction::LShr:
946f785676fSDimitry Andric     case Instruction::AShr:
947f785676fSDimitry Andric     case Instruction::And:
948f785676fSDimitry Andric     case Instruction::Or:
949f785676fSDimitry Andric     case Instruction::Xor: {
950f785676fSDimitry Andric       BinaryOperator *BO = cast<BinaryOperator>(I);
951f785676fSDimitry Andric       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
952f785676fSDimitry Andric       BinaryOperator *New =
953f785676fSDimitry Andric           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
954f785676fSDimitry Andric                                  NewOps[0], NewOps[1], "", BO);
955f785676fSDimitry Andric       if (isa<OverflowingBinaryOperator>(BO)) {
956f785676fSDimitry Andric         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
957f785676fSDimitry Andric         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
958f785676fSDimitry Andric       }
959f785676fSDimitry Andric       if (isa<PossiblyExactOperator>(BO)) {
960f785676fSDimitry Andric         New->setIsExact(BO->isExact());
961f785676fSDimitry Andric       }
96291bc56edSDimitry Andric       if (isa<FPMathOperator>(BO))
96391bc56edSDimitry Andric         New->copyFastMathFlags(I);
964f785676fSDimitry Andric       return New;
965f785676fSDimitry Andric     }
966f785676fSDimitry Andric     case Instruction::ICmp:
967f785676fSDimitry Andric       assert(NewOps.size() == 2 && "icmp with #ops != 2");
968f785676fSDimitry Andric       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
969f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
970f785676fSDimitry Andric     case Instruction::FCmp:
971f785676fSDimitry Andric       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
972f785676fSDimitry Andric       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
973f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
974f785676fSDimitry Andric     case Instruction::Trunc:
975f785676fSDimitry Andric     case Instruction::ZExt:
976f785676fSDimitry Andric     case Instruction::SExt:
977f785676fSDimitry Andric     case Instruction::FPToUI:
978f785676fSDimitry Andric     case Instruction::FPToSI:
979f785676fSDimitry Andric     case Instruction::UIToFP:
980f785676fSDimitry Andric     case Instruction::SIToFP:
981f785676fSDimitry Andric     case Instruction::FPTrunc:
982f785676fSDimitry Andric     case Instruction::FPExt: {
983f785676fSDimitry Andric       // It's possible that the mask has a different number of elements from
984f785676fSDimitry Andric       // the original cast. We recompute the destination type to match the mask.
985f785676fSDimitry Andric       Type *DestTy =
986f785676fSDimitry Andric           VectorType::get(I->getType()->getScalarType(),
987f785676fSDimitry Andric                           NewOps[0]->getType()->getVectorNumElements());
988f785676fSDimitry Andric       assert(NewOps.size() == 1 && "cast with #ops != 1");
989f785676fSDimitry Andric       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
990f785676fSDimitry Andric                               "", I);
991f785676fSDimitry Andric     }
992f785676fSDimitry Andric     case Instruction::GetElementPtr: {
993f785676fSDimitry Andric       Value *Ptr = NewOps[0];
994f785676fSDimitry Andric       ArrayRef<Value*> Idx = NewOps.slice(1);
995ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
996ff0cc061SDimitry Andric           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
997f785676fSDimitry Andric       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
998f785676fSDimitry Andric       return GEP;
999f785676fSDimitry Andric     }
1000f785676fSDimitry Andric   }
1001f785676fSDimitry Andric   llvm_unreachable("failed to rebuild vector instructions");
1002f785676fSDimitry Andric }
1003f785676fSDimitry Andric 
1004f785676fSDimitry Andric Value *
1005f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1006f785676fSDimitry Andric   // Mask.size() does not need to be equal to the number of vector elements.
1007f785676fSDimitry Andric 
1008f785676fSDimitry Andric   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
1009f785676fSDimitry Andric   if (isa<UndefValue>(V)) {
1010f785676fSDimitry Andric     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
1011f785676fSDimitry Andric                                            Mask.size()));
1012f785676fSDimitry Andric   }
1013f785676fSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
1014f785676fSDimitry Andric     return ConstantAggregateZero::get(
1015f785676fSDimitry Andric                VectorType::get(V->getType()->getScalarType(),
1016f785676fSDimitry Andric                                Mask.size()));
1017f785676fSDimitry Andric   }
1018f785676fSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
1019f785676fSDimitry Andric     SmallVector<Constant *, 16> MaskValues;
1020f785676fSDimitry Andric     for (int i = 0, e = Mask.size(); i != e; ++i) {
1021f785676fSDimitry Andric       if (Mask[i] == -1)
1022f785676fSDimitry Andric         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
1023f785676fSDimitry Andric       else
1024f785676fSDimitry Andric         MaskValues.push_back(Builder->getInt32(Mask[i]));
1025f785676fSDimitry Andric     }
1026f785676fSDimitry Andric     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1027f785676fSDimitry Andric                                           ConstantVector::get(MaskValues));
1028f785676fSDimitry Andric   }
1029f785676fSDimitry Andric 
1030f785676fSDimitry Andric   Instruction *I = cast<Instruction>(V);
1031f785676fSDimitry Andric   switch (I->getOpcode()) {
1032f785676fSDimitry Andric     case Instruction::Add:
1033f785676fSDimitry Andric     case Instruction::FAdd:
1034f785676fSDimitry Andric     case Instruction::Sub:
1035f785676fSDimitry Andric     case Instruction::FSub:
1036f785676fSDimitry Andric     case Instruction::Mul:
1037f785676fSDimitry Andric     case Instruction::FMul:
1038f785676fSDimitry Andric     case Instruction::UDiv:
1039f785676fSDimitry Andric     case Instruction::SDiv:
1040f785676fSDimitry Andric     case Instruction::FDiv:
1041f785676fSDimitry Andric     case Instruction::URem:
1042f785676fSDimitry Andric     case Instruction::SRem:
1043f785676fSDimitry Andric     case Instruction::FRem:
1044f785676fSDimitry Andric     case Instruction::Shl:
1045f785676fSDimitry Andric     case Instruction::LShr:
1046f785676fSDimitry Andric     case Instruction::AShr:
1047f785676fSDimitry Andric     case Instruction::And:
1048f785676fSDimitry Andric     case Instruction::Or:
1049f785676fSDimitry Andric     case Instruction::Xor:
1050f785676fSDimitry Andric     case Instruction::ICmp:
1051f785676fSDimitry Andric     case Instruction::FCmp:
1052f785676fSDimitry Andric     case Instruction::Trunc:
1053f785676fSDimitry Andric     case Instruction::ZExt:
1054f785676fSDimitry Andric     case Instruction::SExt:
1055f785676fSDimitry Andric     case Instruction::FPToUI:
1056f785676fSDimitry Andric     case Instruction::FPToSI:
1057f785676fSDimitry Andric     case Instruction::UIToFP:
1058f785676fSDimitry Andric     case Instruction::SIToFP:
1059f785676fSDimitry Andric     case Instruction::FPTrunc:
1060f785676fSDimitry Andric     case Instruction::FPExt:
1061f785676fSDimitry Andric     case Instruction::Select:
1062f785676fSDimitry Andric     case Instruction::GetElementPtr: {
1063f785676fSDimitry Andric       SmallVector<Value*, 8> NewOps;
1064f785676fSDimitry Andric       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1065f785676fSDimitry Andric       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1066f785676fSDimitry Andric         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
1067f785676fSDimitry Andric         NewOps.push_back(V);
1068f785676fSDimitry Andric         NeedsRebuild |= (V != I->getOperand(i));
1069f785676fSDimitry Andric       }
1070f785676fSDimitry Andric       if (NeedsRebuild) {
10717d523365SDimitry Andric         return buildNew(I, NewOps);
1072f785676fSDimitry Andric       }
1073f785676fSDimitry Andric       return I;
1074f785676fSDimitry Andric     }
1075f785676fSDimitry Andric     case Instruction::InsertElement: {
1076f785676fSDimitry Andric       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1077f785676fSDimitry Andric 
1078f785676fSDimitry Andric       // The insertelement was inserting at Element. Figure out which element
1079f785676fSDimitry Andric       // that becomes after shuffling. The answer is guaranteed to be unique
1080f785676fSDimitry Andric       // by CanEvaluateShuffled.
1081f785676fSDimitry Andric       bool Found = false;
1082f785676fSDimitry Andric       int Index = 0;
1083f785676fSDimitry Andric       for (int e = Mask.size(); Index != e; ++Index) {
1084f785676fSDimitry Andric         if (Mask[Index] == Element) {
1085f785676fSDimitry Andric           Found = true;
1086f785676fSDimitry Andric           break;
1087f785676fSDimitry Andric         }
1088f785676fSDimitry Andric       }
1089f785676fSDimitry Andric 
109091bc56edSDimitry Andric       // If element is not in Mask, no need to handle the operand 1 (element to
109191bc56edSDimitry Andric       // be inserted). Just evaluate values in operand 0 according to Mask.
1092f785676fSDimitry Andric       if (!Found)
109391bc56edSDimitry Andric         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1094f785676fSDimitry Andric 
1095f785676fSDimitry Andric       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1096f785676fSDimitry Andric       return InsertElementInst::Create(V, I->getOperand(1),
1097f785676fSDimitry Andric                                        Builder->getInt32(Index), "", I);
1098f785676fSDimitry Andric     }
1099f785676fSDimitry Andric   }
1100f785676fSDimitry Andric   llvm_unreachable("failed to reorder elements of vector instruction!");
1101f785676fSDimitry Andric }
1102f22ef01cSRoman Divacky 
11037d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
110491bc56edSDimitry Andric                                   bool &isLHSID, bool &isRHSID) {
110591bc56edSDimitry Andric   isLHSID = isRHSID = true;
110691bc56edSDimitry Andric 
110791bc56edSDimitry Andric   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
110891bc56edSDimitry Andric     if (Mask[i] < 0) continue;  // Ignore undef values.
110991bc56edSDimitry Andric     // Is this an identity shuffle of the LHS value?
111091bc56edSDimitry Andric     isLHSID &= (Mask[i] == (int)i);
111191bc56edSDimitry Andric 
111291bc56edSDimitry Andric     // Is this an identity shuffle of the RHS value?
111391bc56edSDimitry Andric     isRHSID &= (Mask[i]-e == i);
111491bc56edSDimitry Andric   }
111591bc56edSDimitry Andric }
111691bc56edSDimitry Andric 
1117ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from
1118ff0cc061SDimitry Andric // LHS, for example:
1119ff0cc061SDimitry Andric //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1120ff0cc061SDimitry Andric //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1121ff0cc061SDimitry Andric //   Shuffles to:  |EE|FF|GG|HH|
1122ff0cc061SDimitry Andric //                 +--+--+--+--+
1123ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1124ff0cc061SDimitry Andric                                        SmallVector<int, 16> &Mask) {
1125d88c1a5aSDimitry Andric   unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
1126ff0cc061SDimitry Andric   unsigned MaskElems = Mask.size();
1127ff0cc061SDimitry Andric   unsigned BegIdx = Mask.front();
1128ff0cc061SDimitry Andric   unsigned EndIdx = Mask.back();
1129ff0cc061SDimitry Andric   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1130ff0cc061SDimitry Andric     return false;
1131ff0cc061SDimitry Andric   for (unsigned I = 0; I != MaskElems; ++I)
1132ff0cc061SDimitry Andric     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1133ff0cc061SDimitry Andric       return false;
1134ff0cc061SDimitry Andric   return true;
1135ff0cc061SDimitry Andric }
1136ff0cc061SDimitry Andric 
1137f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1138f22ef01cSRoman Divacky   Value *LHS = SVI.getOperand(0);
1139f22ef01cSRoman Divacky   Value *RHS = SVI.getOperand(1);
1140dff0c46cSDimitry Andric   SmallVector<int, 16> Mask = SVI.getShuffleMask();
1141ff0cc061SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1142f22ef01cSRoman Divacky 
11437a7e6055SDimitry Andric   if (auto *V = SimplifyShuffleVectorInst(LHS, RHS, SVI.getMask(),
11447a7e6055SDimitry Andric                                           SVI.getType(), DL, &TLI, &DT, &AC))
11457a7e6055SDimitry Andric     return replaceInstUsesWith(SVI, V);
11467a7e6055SDimitry Andric 
1147f22ef01cSRoman Divacky   bool MadeChange = false;
1148d88c1a5aSDimitry Andric   unsigned VWidth = SVI.getType()->getVectorNumElements();
1149f22ef01cSRoman Divacky 
1150f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
1151f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
11522754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11532754fe60SDimitry Andric     if (V != &SVI)
11543ca95b02SDimitry Andric       return replaceInstUsesWith(SVI, V);
1155f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
1156f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
1157f22ef01cSRoman Divacky     MadeChange = true;
1158f22ef01cSRoman Divacky   }
1159f22ef01cSRoman Divacky 
1160d88c1a5aSDimitry Andric   unsigned LHSWidth = LHS->getType()->getVectorNumElements();
1161dff0c46cSDimitry Andric 
1162f22ef01cSRoman Divacky   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
1163f22ef01cSRoman Divacky   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
1164f22ef01cSRoman Divacky   if (LHS == RHS || isa<UndefValue>(LHS)) {
1165f22ef01cSRoman Divacky     if (isa<UndefValue>(LHS) && LHS == RHS) {
1166f22ef01cSRoman Divacky       // shuffle(undef,undef,mask) -> undef.
1167f785676fSDimitry Andric       Value *Result = (VWidth == LHSWidth)
1168dff0c46cSDimitry Andric                       ? LHS : UndefValue::get(SVI.getType());
11693ca95b02SDimitry Andric       return replaceInstUsesWith(SVI, Result);
1170f22ef01cSRoman Divacky     }
1171f22ef01cSRoman Divacky 
1172f22ef01cSRoman Divacky     // Remap any references to RHS to use LHS.
1173dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1174dff0c46cSDimitry Andric     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
1175dff0c46cSDimitry Andric       if (Mask[i] < 0) {
1176ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1177dff0c46cSDimitry Andric         continue;
1178dff0c46cSDimitry Andric       }
1179dff0c46cSDimitry Andric 
11802754fe60SDimitry Andric       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
11812754fe60SDimitry Andric           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
11822754fe60SDimitry Andric         Mask[i] = -1;     // Turn into undef.
1183ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1184f22ef01cSRoman Divacky       } else {
1185f22ef01cSRoman Divacky         Mask[i] = Mask[i] % e;  // Force to LHS.
1186ff0cc061SDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
1187f22ef01cSRoman Divacky       }
1188f22ef01cSRoman Divacky     }
1189f22ef01cSRoman Divacky     SVI.setOperand(0, SVI.getOperand(1));
1190f22ef01cSRoman Divacky     SVI.setOperand(1, UndefValue::get(RHS->getType()));
1191f22ef01cSRoman Divacky     SVI.setOperand(2, ConstantVector::get(Elts));
1192f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
1193f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
1194f22ef01cSRoman Divacky     MadeChange = true;
1195f22ef01cSRoman Divacky   }
1196f22ef01cSRoman Divacky 
1197dff0c46cSDimitry Andric   if (VWidth == LHSWidth) {
1198f22ef01cSRoman Divacky     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
119991bc56edSDimitry Andric     bool isLHSID, isRHSID;
12007d523365SDimitry Andric     recognizeIdentityMask(Mask, isLHSID, isRHSID);
1201f22ef01cSRoman Divacky 
1202f22ef01cSRoman Divacky     // Eliminate identity shuffles.
12033ca95b02SDimitry Andric     if (isLHSID) return replaceInstUsesWith(SVI, LHS);
12043ca95b02SDimitry Andric     if (isRHSID) return replaceInstUsesWith(SVI, RHS);
1205dff0c46cSDimitry Andric   }
1206f22ef01cSRoman Divacky 
1207f785676fSDimitry Andric   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
1208f785676fSDimitry Andric     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
12093ca95b02SDimitry Andric     return replaceInstUsesWith(SVI, V);
1210f785676fSDimitry Andric   }
1211f785676fSDimitry Andric 
1212ff0cc061SDimitry Andric   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1213ff0cc061SDimitry Andric   // a non-vector type. We can instead bitcast the original vector followed by
1214ff0cc061SDimitry Andric   // an extract of the desired element:
1215ff0cc061SDimitry Andric   //
1216ff0cc061SDimitry Andric   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1217ff0cc061SDimitry Andric   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1218ff0cc061SDimitry Andric   //   %1 = bitcast <4 x i8> %sroa to i32
1219ff0cc061SDimitry Andric   // Becomes:
1220ff0cc061SDimitry Andric   //   %bc = bitcast <16 x i8> %in to <4 x i32>
1221ff0cc061SDimitry Andric   //   %ext = extractelement <4 x i32> %bc, i32 0
1222ff0cc061SDimitry Andric   //
1223ff0cc061SDimitry Andric   // If the shuffle is extracting a contiguous range of values from the input
1224ff0cc061SDimitry Andric   // vector then each use which is a bitcast of the extracted size can be
1225ff0cc061SDimitry Andric   // replaced. This will work if the vector types are compatible, and the begin
1226ff0cc061SDimitry Andric   // index is aligned to a value in the casted vector type. If the begin index
1227ff0cc061SDimitry Andric   // isn't aligned then we can shuffle the original vector (keeping the same
1228ff0cc061SDimitry Andric   // vector type) before extracting.
1229ff0cc061SDimitry Andric   //
1230ff0cc061SDimitry Andric   // This code will bail out if the target type is fundamentally incompatible
1231ff0cc061SDimitry Andric   // with vectors of the source type.
1232ff0cc061SDimitry Andric   //
1233ff0cc061SDimitry Andric   // Example of <16 x i8>, target type i32:
1234ff0cc061SDimitry Andric   // Index range [4,8):         v-----------v Will work.
1235ff0cc061SDimitry Andric   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1236ff0cc061SDimitry Andric   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
1237ff0cc061SDimitry Andric   //     <4 x i32>: |           |           |           |           |
1238ff0cc061SDimitry Andric   //                +-----------+-----------+-----------+-----------+
1239ff0cc061SDimitry Andric   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
1240ff0cc061SDimitry Andric   // Target type i40:           ^--------------^ Won't work, bail.
1241ff0cc061SDimitry Andric   if (isShuffleExtractingFromLHS(SVI, Mask)) {
1242ff0cc061SDimitry Andric     Value *V = LHS;
1243ff0cc061SDimitry Andric     unsigned MaskElems = Mask.size();
1244ff0cc061SDimitry Andric     VectorType *SrcTy = cast<VectorType>(V->getType());
1245ff0cc061SDimitry Andric     unsigned VecBitWidth = SrcTy->getBitWidth();
1246ff0cc061SDimitry Andric     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1247ff0cc061SDimitry Andric     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1248ff0cc061SDimitry Andric     unsigned SrcNumElems = SrcTy->getNumElements();
1249ff0cc061SDimitry Andric     SmallVector<BitCastInst *, 8> BCs;
1250ff0cc061SDimitry Andric     DenseMap<Type *, Value *> NewBCs;
1251ff0cc061SDimitry Andric     for (User *U : SVI.users())
1252ff0cc061SDimitry Andric       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1253ff0cc061SDimitry Andric         if (!BC->use_empty())
1254ff0cc061SDimitry Andric           // Only visit bitcasts that weren't previously handled.
1255ff0cc061SDimitry Andric           BCs.push_back(BC);
1256ff0cc061SDimitry Andric     for (BitCastInst *BC : BCs) {
12577a7e6055SDimitry Andric       unsigned BegIdx = Mask.front();
1258ff0cc061SDimitry Andric       Type *TgtTy = BC->getDestTy();
1259ff0cc061SDimitry Andric       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1260ff0cc061SDimitry Andric       if (!TgtElemBitWidth)
1261ff0cc061SDimitry Andric         continue;
1262ff0cc061SDimitry Andric       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1263ff0cc061SDimitry Andric       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1264ff0cc061SDimitry Andric       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1265ff0cc061SDimitry Andric       if (!VecBitWidthsEqual)
1266ff0cc061SDimitry Andric         continue;
1267ff0cc061SDimitry Andric       if (!VectorType::isValidElementType(TgtTy))
1268ff0cc061SDimitry Andric         continue;
1269ff0cc061SDimitry Andric       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1270ff0cc061SDimitry Andric       if (!BegIsAligned) {
1271ff0cc061SDimitry Andric         // Shuffle the input so [0,NumElements) contains the output, and
1272ff0cc061SDimitry Andric         // [NumElems,SrcNumElems) is undef.
1273ff0cc061SDimitry Andric         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1274ff0cc061SDimitry Andric                                                 UndefValue::get(Int32Ty));
1275ff0cc061SDimitry Andric         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1276ff0cc061SDimitry Andric           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1277ff0cc061SDimitry Andric         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1278ff0cc061SDimitry Andric                                          ConstantVector::get(ShuffleMask),
1279ff0cc061SDimitry Andric                                          SVI.getName() + ".extract");
1280ff0cc061SDimitry Andric         BegIdx = 0;
1281ff0cc061SDimitry Andric       }
1282ff0cc061SDimitry Andric       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1283ff0cc061SDimitry Andric       assert(SrcElemsPerTgtElem);
1284ff0cc061SDimitry Andric       BegIdx /= SrcElemsPerTgtElem;
1285ff0cc061SDimitry Andric       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1286ff0cc061SDimitry Andric       auto *NewBC =
1287ff0cc061SDimitry Andric           BCAlreadyExists
1288ff0cc061SDimitry Andric               ? NewBCs[CastSrcTy]
1289ff0cc061SDimitry Andric               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1290ff0cc061SDimitry Andric       if (!BCAlreadyExists)
1291ff0cc061SDimitry Andric         NewBCs[CastSrcTy] = NewBC;
1292ff0cc061SDimitry Andric       auto *Ext = Builder->CreateExtractElement(
1293ff0cc061SDimitry Andric           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1294ff0cc061SDimitry Andric       // The shufflevector isn't being replaced: the bitcast that used it
1295ff0cc061SDimitry Andric       // is. InstCombine will visit the newly-created instructions.
12963ca95b02SDimitry Andric       replaceInstUsesWith(*BC, Ext);
1297ff0cc061SDimitry Andric       MadeChange = true;
1298ff0cc061SDimitry Andric     }
1299ff0cc061SDimitry Andric   }
1300ff0cc061SDimitry Andric 
1301f22ef01cSRoman Divacky   // If the LHS is a shufflevector itself, see if we can combine it with this
1302dff0c46cSDimitry Andric   // one without producing an unusual shuffle.
1303dff0c46cSDimitry Andric   // Cases that might be simplified:
1304dff0c46cSDimitry Andric   // 1.
1305dff0c46cSDimitry Andric   // x1=shuffle(v1,v2,mask1)
1306dff0c46cSDimitry Andric   //  x=shuffle(x1,undef,mask)
1307dff0c46cSDimitry Andric   //        ==>
1308dff0c46cSDimitry Andric   //  x=shuffle(v1,undef,newMask)
1309dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1310dff0c46cSDimitry Andric   // 2.
1311dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1312dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1313dff0c46cSDimitry Andric   // where v1.size() == mask1.size()
1314dff0c46cSDimitry Andric   //        ==>
1315dff0c46cSDimitry Andric   //  x=shuffle(v1,x2,newMask)
1316dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1317dff0c46cSDimitry Andric   // 3.
1318dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1319dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1320dff0c46cSDimitry Andric   // where v2.size() == mask2.size()
1321dff0c46cSDimitry Andric   //        ==>
1322dff0c46cSDimitry Andric   //  x=shuffle(x1,v2,newMask)
1323dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1324dff0c46cSDimitry Andric   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1325dff0c46cSDimitry Andric   // 4.
1326dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1327dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1328dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1329dff0c46cSDimitry Andric   // where v1.size() == v2.size()
1330dff0c46cSDimitry Andric   //        ==>
1331dff0c46cSDimitry Andric   //  x=shuffle(v1,v2,newMask)
1332dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1333dff0c46cSDimitry Andric   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1334dff0c46cSDimitry Andric   //
1335dff0c46cSDimitry Andric   // Here we are really conservative:
1336f22ef01cSRoman Divacky   // we are absolutely afraid of producing a shuffle mask not in the input
1337f22ef01cSRoman Divacky   // program, because the code gen may not be smart enough to turn a merged
1338f22ef01cSRoman Divacky   // shuffle into two specific shuffles: it may produce worse code.  As such,
13392754fe60SDimitry Andric   // we only merge two shuffles if the result is either a splat or one of the
1340dff0c46cSDimitry Andric   // input shuffle masks.  In this case, merging the shuffles just removes
13412754fe60SDimitry Andric   // one instruction, which we know is safe.  This is good for things like
1342dff0c46cSDimitry Andric   // turning: (splat(splat)) -> splat, or
1343dff0c46cSDimitry Andric   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1344dff0c46cSDimitry Andric   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1345dff0c46cSDimitry Andric   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1346dff0c46cSDimitry Andric   if (LHSShuffle)
1347dff0c46cSDimitry Andric     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
134891bc56edSDimitry Andric       LHSShuffle = nullptr;
1349dff0c46cSDimitry Andric   if (RHSShuffle)
1350dff0c46cSDimitry Andric     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
135191bc56edSDimitry Andric       RHSShuffle = nullptr;
1352dff0c46cSDimitry Andric   if (!LHSShuffle && !RHSShuffle)
135391bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1354dff0c46cSDimitry Andric 
135591bc56edSDimitry Andric   Value* LHSOp0 = nullptr;
135691bc56edSDimitry Andric   Value* LHSOp1 = nullptr;
135791bc56edSDimitry Andric   Value* RHSOp0 = nullptr;
1358dff0c46cSDimitry Andric   unsigned LHSOp0Width = 0;
1359dff0c46cSDimitry Andric   unsigned RHSOp0Width = 0;
1360dff0c46cSDimitry Andric   if (LHSShuffle) {
1361dff0c46cSDimitry Andric     LHSOp0 = LHSShuffle->getOperand(0);
1362dff0c46cSDimitry Andric     LHSOp1 = LHSShuffle->getOperand(1);
1363d88c1a5aSDimitry Andric     LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
1364dff0c46cSDimitry Andric   }
1365dff0c46cSDimitry Andric   if (RHSShuffle) {
1366dff0c46cSDimitry Andric     RHSOp0 = RHSShuffle->getOperand(0);
1367d88c1a5aSDimitry Andric     RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
1368dff0c46cSDimitry Andric   }
1369dff0c46cSDimitry Andric   Value* newLHS = LHS;
1370dff0c46cSDimitry Andric   Value* newRHS = RHS;
1371dff0c46cSDimitry Andric   if (LHSShuffle) {
1372dff0c46cSDimitry Andric     // case 1
1373f22ef01cSRoman Divacky     if (isa<UndefValue>(RHS)) {
1374dff0c46cSDimitry Andric       newLHS = LHSOp0;
1375dff0c46cSDimitry Andric       newRHS = LHSOp1;
1376dff0c46cSDimitry Andric     }
1377dff0c46cSDimitry Andric     // case 2 or 4
1378dff0c46cSDimitry Andric     else if (LHSOp0Width == LHSWidth) {
1379dff0c46cSDimitry Andric       newLHS = LHSOp0;
1380dff0c46cSDimitry Andric     }
1381dff0c46cSDimitry Andric   }
1382dff0c46cSDimitry Andric   // case 3 or 4
1383dff0c46cSDimitry Andric   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1384dff0c46cSDimitry Andric     newRHS = RHSOp0;
1385dff0c46cSDimitry Andric   }
1386dff0c46cSDimitry Andric   // case 4
1387dff0c46cSDimitry Andric   if (LHSOp0 == RHSOp0) {
1388dff0c46cSDimitry Andric     newLHS = LHSOp0;
138991bc56edSDimitry Andric     newRHS = nullptr;
1390dff0c46cSDimitry Andric   }
1391f22ef01cSRoman Divacky 
1392dff0c46cSDimitry Andric   if (newLHS == LHS && newRHS == RHS)
139391bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1394dff0c46cSDimitry Andric 
1395dff0c46cSDimitry Andric   SmallVector<int, 16> LHSMask;
1396dff0c46cSDimitry Andric   SmallVector<int, 16> RHSMask;
1397dff0c46cSDimitry Andric   if (newLHS != LHS)
1398dff0c46cSDimitry Andric     LHSMask = LHSShuffle->getShuffleMask();
1399dff0c46cSDimitry Andric   if (RHSShuffle && newRHS != RHS)
1400dff0c46cSDimitry Andric     RHSMask = RHSShuffle->getShuffleMask();
1401dff0c46cSDimitry Andric 
1402dff0c46cSDimitry Andric   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1403dff0c46cSDimitry Andric   SmallVector<int, 16> newMask;
14042754fe60SDimitry Andric   bool isSplat = true;
1405dff0c46cSDimitry Andric   int SplatElt = -1;
1406dff0c46cSDimitry Andric   // Create a new mask for the new ShuffleVectorInst so that the new
1407dff0c46cSDimitry Andric   // ShuffleVectorInst is equivalent to the original one.
1408dff0c46cSDimitry Andric   for (unsigned i = 0; i < VWidth; ++i) {
1409dff0c46cSDimitry Andric     int eltMask;
1410139f7f9bSDimitry Andric     if (Mask[i] < 0) {
1411dff0c46cSDimitry Andric       // This element is an undef value.
1412dff0c46cSDimitry Andric       eltMask = -1;
1413dff0c46cSDimitry Andric     } else if (Mask[i] < (int)LHSWidth) {
1414dff0c46cSDimitry Andric       // This element is from left hand side vector operand.
1415dff0c46cSDimitry Andric       //
1416dff0c46cSDimitry Andric       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1417dff0c46cSDimitry Andric       // new mask value for the element.
1418dff0c46cSDimitry Andric       if (newLHS != LHS) {
1419dff0c46cSDimitry Andric         eltMask = LHSMask[Mask[i]];
1420dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1421dff0c46cSDimitry Andric         // with a -1 mask value.
1422dff0c46cSDimitry Andric         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1423dff0c46cSDimitry Andric           eltMask = -1;
1424139f7f9bSDimitry Andric       } else
1425dff0c46cSDimitry Andric         eltMask = Mask[i];
1426dff0c46cSDimitry Andric     } else {
1427dff0c46cSDimitry Andric       // This element is from right hand side vector operand
1428dff0c46cSDimitry Andric       //
1429dff0c46cSDimitry Andric       // If the value selected is an undef value, explicitly specify it
1430dff0c46cSDimitry Andric       // with a -1 mask value. (case 1)
1431dff0c46cSDimitry Andric       if (isa<UndefValue>(RHS))
1432dff0c46cSDimitry Andric         eltMask = -1;
1433dff0c46cSDimitry Andric       // If RHS is going to be replaced (case 3 or 4), calculate the
1434dff0c46cSDimitry Andric       // new mask value for the element.
1435dff0c46cSDimitry Andric       else if (newRHS != RHS) {
1436dff0c46cSDimitry Andric         eltMask = RHSMask[Mask[i]-LHSWidth];
1437dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1438dff0c46cSDimitry Andric         // with a -1 mask value.
1439dff0c46cSDimitry Andric         if (eltMask >= (int)RHSOp0Width) {
1440dff0c46cSDimitry Andric           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1441dff0c46cSDimitry Andric                  && "should have been check above");
1442dff0c46cSDimitry Andric           eltMask = -1;
1443dff0c46cSDimitry Andric         }
1444139f7f9bSDimitry Andric       } else
1445dff0c46cSDimitry Andric         eltMask = Mask[i]-LHSWidth;
1446dff0c46cSDimitry Andric 
1447dff0c46cSDimitry Andric       // If LHS's width is changed, shift the mask value accordingly.
1448dff0c46cSDimitry Andric       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
14493861d79fSDimitry Andric       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
14503861d79fSDimitry Andric       // If newRHS == newLHS, we want to remap any references from newRHS to
14513861d79fSDimitry Andric       // newLHS so that we can properly identify splats that may occur due to
145291bc56edSDimitry Andric       // obfuscation across the two vectors.
145391bc56edSDimitry Andric       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1454dff0c46cSDimitry Andric         eltMask += newLHSWidth;
14552754fe60SDimitry Andric     }
1456f22ef01cSRoman Divacky 
1457dff0c46cSDimitry Andric     // Check if this could still be a splat.
1458dff0c46cSDimitry Andric     if (eltMask >= 0) {
1459dff0c46cSDimitry Andric       if (SplatElt >= 0 && SplatElt != eltMask)
1460dff0c46cSDimitry Andric         isSplat = false;
1461dff0c46cSDimitry Andric       SplatElt = eltMask;
1462dff0c46cSDimitry Andric     }
1463dff0c46cSDimitry Andric 
1464dff0c46cSDimitry Andric     newMask.push_back(eltMask);
1465dff0c46cSDimitry Andric   }
1466dff0c46cSDimitry Andric 
1467dff0c46cSDimitry Andric   // If the result mask is equal to one of the original shuffle masks,
1468dff0c46cSDimitry Andric   // or is a splat, do the replacement.
1469dff0c46cSDimitry Andric   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1470dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1471dff0c46cSDimitry Andric     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1472dff0c46cSDimitry Andric       if (newMask[i] < 0) {
14732754fe60SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1474f22ef01cSRoman Divacky       } else {
1475dff0c46cSDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1476f22ef01cSRoman Divacky       }
1477f22ef01cSRoman Divacky     }
147891bc56edSDimitry Andric     if (!newRHS)
1479dff0c46cSDimitry Andric       newRHS = UndefValue::get(newLHS->getType());
1480dff0c46cSDimitry Andric     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1481f22ef01cSRoman Divacky   }
1482f22ef01cSRoman Divacky 
148391bc56edSDimitry Andric   // If the result mask is an identity, replace uses of this instruction with
148491bc56edSDimitry Andric   // corresponding argument.
148591bc56edSDimitry Andric   bool isLHSID, isRHSID;
14867d523365SDimitry Andric   recognizeIdentityMask(newMask, isLHSID, isRHSID);
14873ca95b02SDimitry Andric   if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
14883ca95b02SDimitry Andric   if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
148991bc56edSDimitry Andric 
149091bc56edSDimitry Andric   return MadeChange ? &SVI : nullptr;
1491f22ef01cSRoman Divacky }
1492