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 
65284c1978SDimitry Andric // If we have a PHI node with a vector type that has only 2 uses: 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) {
69284c1978SDimitry Andric   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
70284c1978SDimitry Andric   if (!PN->hasNUses(2))
7191bc56edSDimitry Andric     return nullptr;
72284c1978SDimitry Andric 
73284c1978SDimitry Andric   // If so, it's known at this point that one operand is PHI and the other is
74284c1978SDimitry Andric   // an extractelement node. Find the PHI user that is not the extractelement
75284c1978SDimitry Andric   // node.
7691bc56edSDimitry Andric   auto iu = PN->user_begin();
77284c1978SDimitry Andric   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
78284c1978SDimitry Andric   if (PHIUser == cast<Instruction>(&EI))
79284c1978SDimitry Andric     PHIUser = cast<Instruction>(*(++iu));
80284c1978SDimitry Andric 
81284c1978SDimitry Andric   // Verify that this PHI user has one use, which is the PHI itself,
82284c1978SDimitry Andric   // and that it is a binary operation which is cheap to scalarize.
83284c1978SDimitry Andric   // otherwise return NULL.
8491bc56edSDimitry Andric   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
857d523365SDimitry Andric       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
8691bc56edSDimitry Andric     return nullptr;
87284c1978SDimitry Andric 
88284c1978SDimitry Andric   // Create a scalar PHI node that will replace the vector PHI node
89284c1978SDimitry Andric   // just before the current PHI node.
90f785676fSDimitry Andric   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
91f785676fSDimitry Andric       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
92284c1978SDimitry Andric   // Scalarize each PHI operand.
93284c1978SDimitry Andric   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
94284c1978SDimitry Andric     Value *PHIInVal = PN->getIncomingValue(i);
95284c1978SDimitry Andric     BasicBlock *inBB = PN->getIncomingBlock(i);
96284c1978SDimitry Andric     Value *Elt = EI.getIndexOperand();
97284c1978SDimitry Andric     // If the operand is the PHI induction variable:
98284c1978SDimitry Andric     if (PHIInVal == PHIUser) {
99284c1978SDimitry Andric       // Scalarize the binary operation. Its first operand is the
10091bc56edSDimitry Andric       // scalar PHI, and the second operand is extracted from the other
101284c1978SDimitry Andric       // vector operand.
102284c1978SDimitry Andric       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
103284c1978SDimitry Andric       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
104f785676fSDimitry Andric       Value *Op = InsertNewInstWith(
105f785676fSDimitry Andric           ExtractElementInst::Create(B0->getOperand(opId), Elt,
106f785676fSDimitry Andric                                      B0->getOperand(opId)->getName() + ".Elt"),
107284c1978SDimitry Andric           *B0);
108f785676fSDimitry Andric       Value *newPHIUser = InsertNewInstWith(
109f785676fSDimitry Andric           BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
110284c1978SDimitry Andric       scalarPHI->addIncoming(newPHIUser, inBB);
111284c1978SDimitry Andric     } else {
112284c1978SDimitry Andric       // Scalarize PHI input:
113f785676fSDimitry Andric       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
114284c1978SDimitry Andric       // Insert the new instruction into the predecessor basic block.
115284c1978SDimitry Andric       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
116284c1978SDimitry Andric       BasicBlock::iterator InsertPos;
117284c1978SDimitry Andric       if (pos && !isa<PHINode>(pos)) {
1187d523365SDimitry Andric         InsertPos = ++pos->getIterator();
119284c1978SDimitry Andric       } else {
120284c1978SDimitry Andric         InsertPos = inBB->getFirstInsertionPt();
121284c1978SDimitry Andric       }
122284c1978SDimitry Andric 
123284c1978SDimitry Andric       InsertNewInstWith(newEI, *InsertPos);
124284c1978SDimitry Andric 
125284c1978SDimitry Andric       scalarPHI->addIncoming(newEI, inBB);
126284c1978SDimitry Andric     }
127284c1978SDimitry Andric   }
128284c1978SDimitry Andric   return ReplaceInstUsesWith(EI, scalarPHI);
129284c1978SDimitry Andric }
130284c1978SDimitry Andric 
131f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
132875ed548SDimitry Andric   if (Value *V = SimplifyExtractElementInst(
133875ed548SDimitry Andric           EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
134875ed548SDimitry Andric     return ReplaceInstUsesWith(EI, V);
135875ed548SDimitry Andric 
136f22ef01cSRoman Divacky   // If vector val is constant with all elements the same, replace EI with
137dff0c46cSDimitry Andric   // that element.  We handle a known element # below.
138dff0c46cSDimitry Andric   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
1397d523365SDimitry Andric     if (cheapToScalarize(C, false))
140dff0c46cSDimitry Andric       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
141f22ef01cSRoman Divacky 
142f22ef01cSRoman Divacky   // If extracting a specified index from the vector, see if we can recursively
143f22ef01cSRoman Divacky   // find a previously computed scalar that was inserted into the vector.
144f22ef01cSRoman Divacky   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
145f22ef01cSRoman Divacky     unsigned IndexVal = IdxC->getZExtValue();
146f22ef01cSRoman Divacky     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
147f22ef01cSRoman Divacky 
148875ed548SDimitry Andric     // InstSimplify handles cases where the index is invalid.
149875ed548SDimitry Andric     assert(IndexVal < VectorWidth);
150f22ef01cSRoman Divacky 
151f22ef01cSRoman Divacky     // This instruction only demands the single element from the input vector.
152f22ef01cSRoman Divacky     // If the input vector has a single use, simplify it based on this use
153f22ef01cSRoman Divacky     // property.
154f22ef01cSRoman Divacky     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
155f22ef01cSRoman Divacky       APInt UndefElts(VectorWidth, 0);
156f22ef01cSRoman Divacky       APInt DemandedMask(VectorWidth, 0);
1572754fe60SDimitry Andric       DemandedMask.setBit(IndexVal);
158ff0cc061SDimitry Andric       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
159ff0cc061SDimitry Andric                                                 UndefElts)) {
160f22ef01cSRoman Divacky         EI.setOperand(0, V);
161f22ef01cSRoman Divacky         return &EI;
162f22ef01cSRoman Divacky       }
163f22ef01cSRoman Divacky     }
164f22ef01cSRoman Divacky 
1657d523365SDimitry Andric     // If this extractelement is directly using a bitcast from a vector of
166f22ef01cSRoman Divacky     // the same number of elements, see if we can find the source element from
167f22ef01cSRoman Divacky     // it.  In this case, we will end up needing to bitcast the scalars.
168f22ef01cSRoman Divacky     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
169dff0c46cSDimitry Andric       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
170f22ef01cSRoman Divacky         if (VT->getNumElements() == VectorWidth)
171875ed548SDimitry Andric           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
172f22ef01cSRoman Divacky             return new BitCastInst(Elt, EI.getType());
173f22ef01cSRoman Divacky     }
174284c1978SDimitry Andric 
175284c1978SDimitry Andric     // If there's a vector PHI feeding a scalar use through this extractelement
176284c1978SDimitry Andric     // instruction, try to scalarize the PHI.
177284c1978SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
178284c1978SDimitry Andric       Instruction *scalarPHI = scalarizePHI(EI, PN);
179284c1978SDimitry Andric       if (scalarPHI)
180f785676fSDimitry Andric         return scalarPHI;
181284c1978SDimitry Andric     }
182f22ef01cSRoman Divacky   }
183f22ef01cSRoman Divacky 
184f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
185f22ef01cSRoman Divacky     // Push extractelement into predecessor operation if legal and
1867d523365SDimitry Andric     // profitable to do so.
187f22ef01cSRoman Divacky     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
188f22ef01cSRoman Divacky       if (I->hasOneUse() &&
1897d523365SDimitry Andric           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
190f22ef01cSRoman Divacky         Value *newEI0 =
191f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
192f22ef01cSRoman Divacky                                         EI.getName()+".lhs");
193f22ef01cSRoman Divacky         Value *newEI1 =
194f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
195f22ef01cSRoman Divacky                                         EI.getName()+".rhs");
196f22ef01cSRoman Divacky         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
197f22ef01cSRoman Divacky       }
198f22ef01cSRoman Divacky     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
199f22ef01cSRoman Divacky       // Extracting the inserted element?
200f22ef01cSRoman Divacky       if (IE->getOperand(2) == EI.getOperand(1))
201f22ef01cSRoman Divacky         return ReplaceInstUsesWith(EI, IE->getOperand(1));
202f22ef01cSRoman Divacky       // If the inserted and extracted elements are constants, they must not
203f22ef01cSRoman Divacky       // be the same value, extract from the pre-inserted value instead.
204f22ef01cSRoman Divacky       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
205f22ef01cSRoman Divacky         Worklist.AddValue(EI.getOperand(0));
206f22ef01cSRoman Divacky         EI.setOperand(0, IE->getOperand(0));
207f22ef01cSRoman Divacky         return &EI;
208f22ef01cSRoman Divacky       }
209f22ef01cSRoman Divacky     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
210f22ef01cSRoman Divacky       // If this is extracting an element from a shufflevector, figure out where
211f22ef01cSRoman Divacky       // it came from and extract from the appropriate input element instead.
212f22ef01cSRoman Divacky       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
213dff0c46cSDimitry Andric         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
214f22ef01cSRoman Divacky         Value *Src;
215f22ef01cSRoman Divacky         unsigned LHSWidth =
216dff0c46cSDimitry Andric           SVI->getOperand(0)->getType()->getVectorNumElements();
217f22ef01cSRoman Divacky 
2182754fe60SDimitry Andric         if (SrcIdx < 0)
2192754fe60SDimitry Andric           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
2202754fe60SDimitry Andric         if (SrcIdx < (int)LHSWidth)
221f22ef01cSRoman Divacky           Src = SVI->getOperand(0);
2222754fe60SDimitry Andric         else {
223f22ef01cSRoman Divacky           SrcIdx -= LHSWidth;
224f22ef01cSRoman Divacky           Src = SVI->getOperand(1);
225f22ef01cSRoman Divacky         }
2266122f3e6SDimitry Andric         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
227f22ef01cSRoman Divacky         return ExtractElementInst::Create(Src,
2282754fe60SDimitry Andric                                           ConstantInt::get(Int32Ty,
229f22ef01cSRoman Divacky                                                            SrcIdx, false));
230f22ef01cSRoman Divacky       }
2313b0f4066SDimitry Andric     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2327d523365SDimitry Andric       // Canonicalize extractelement(cast) -> cast(extractelement).
2337d523365SDimitry Andric       // Bitcasts can change the number of vector elements, and they cost
2347d523365SDimitry Andric       // nothing.
235284c1978SDimitry Andric       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
2363b0f4066SDimitry Andric         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
2373b0f4066SDimitry Andric                                                   EI.getIndexOperand());
238284c1978SDimitry Andric         Worklist.AddValue(EE);
2393b0f4066SDimitry Andric         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
240f22ef01cSRoman Divacky       }
241f785676fSDimitry Andric     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
242f785676fSDimitry Andric       if (SI->hasOneUse()) {
243f785676fSDimitry Andric         // TODO: For a select on vectors, it might be useful to do this if it
244f785676fSDimitry Andric         // has multiple extractelement uses. For vector select, that seems to
245f785676fSDimitry Andric         // fight the vectorizer.
246f785676fSDimitry Andric 
247f785676fSDimitry Andric         // If we are extracting an element from a vector select or a select on
2487d523365SDimitry Andric         // vectors, create a select on the scalars extracted from the vector
2497d523365SDimitry Andric         // arguments.
250f785676fSDimitry Andric         Value *TrueVal = SI->getTrueValue();
251f785676fSDimitry Andric         Value *FalseVal = SI->getFalseValue();
252f785676fSDimitry Andric 
253f785676fSDimitry Andric         Value *Cond = SI->getCondition();
254f785676fSDimitry Andric         if (Cond->getType()->isVectorTy()) {
255f785676fSDimitry Andric           Cond = Builder->CreateExtractElement(Cond,
256f785676fSDimitry Andric                                                EI.getIndexOperand(),
257f785676fSDimitry Andric                                                Cond->getName() + ".elt");
258f785676fSDimitry Andric         }
259f785676fSDimitry Andric 
260f785676fSDimitry Andric         Value *V1Elem
261f785676fSDimitry Andric           = Builder->CreateExtractElement(TrueVal,
262f785676fSDimitry Andric                                           EI.getIndexOperand(),
263f785676fSDimitry Andric                                           TrueVal->getName() + ".elt");
264f785676fSDimitry Andric 
265f785676fSDimitry Andric         Value *V2Elem
266f785676fSDimitry Andric           = Builder->CreateExtractElement(FalseVal,
267f785676fSDimitry Andric                                           EI.getIndexOperand(),
268f785676fSDimitry Andric                                           FalseVal->getName() + ".elt");
269f785676fSDimitry Andric         return SelectInst::Create(Cond,
270f785676fSDimitry Andric                                   V1Elem,
271f785676fSDimitry Andric                                   V2Elem,
272f785676fSDimitry Andric                                   SI->getName() + ".elt");
273f785676fSDimitry Andric       }
2743b0f4066SDimitry Andric     }
275f22ef01cSRoman Divacky   }
27691bc56edSDimitry Andric   return nullptr;
277f22ef01cSRoman Divacky }
278f22ef01cSRoman Divacky 
2797d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or
2807d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false.
2817d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
282dff0c46cSDimitry Andric                                          SmallVectorImpl<Constant*> &Mask) {
28391bc56edSDimitry Andric   assert(LHS->getType() == RHS->getType() &&
284f22ef01cSRoman Divacky          "Invalid CollectSingleShuffleElements");
285f785676fSDimitry Andric   unsigned NumElts = V->getType()->getVectorNumElements();
286f22ef01cSRoman Divacky 
287f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
288f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
289f22ef01cSRoman Divacky     return true;
290f22ef01cSRoman Divacky   }
291f22ef01cSRoman Divacky 
292f22ef01cSRoman Divacky   if (V == LHS) {
293f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
294f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
295f22ef01cSRoman Divacky     return true;
296f22ef01cSRoman Divacky   }
297f22ef01cSRoman Divacky 
298f22ef01cSRoman Divacky   if (V == RHS) {
299f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
300f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
301f22ef01cSRoman Divacky                                       i+NumElts));
302f22ef01cSRoman Divacky     return true;
303f22ef01cSRoman Divacky   }
304f22ef01cSRoman Divacky 
305f22ef01cSRoman Divacky   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
306f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
307f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
308f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
309f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
310f22ef01cSRoman Divacky 
311f22ef01cSRoman Divacky     if (!isa<ConstantInt>(IdxOp))
312f22ef01cSRoman Divacky       return false;
313f22ef01cSRoman Divacky     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
314f22ef01cSRoman Divacky 
315f22ef01cSRoman Divacky     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
31691bc56edSDimitry Andric       // We can handle this if the vector we are inserting into is
317f22ef01cSRoman Divacky       // transitively ok.
3187d523365SDimitry Andric       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
319f22ef01cSRoman Divacky         // If so, update the mask to reflect the inserted undef.
320f22ef01cSRoman Divacky         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
321f22ef01cSRoman Divacky         return true;
322f22ef01cSRoman Divacky       }
323f22ef01cSRoman Divacky     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
32491bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1))) {
325f22ef01cSRoman Divacky         unsigned ExtractedIdx =
326f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
32791bc56edSDimitry Andric         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
328f22ef01cSRoman Divacky 
329f22ef01cSRoman Divacky         // This must be extracting from either LHS or RHS.
330f22ef01cSRoman Divacky         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
33191bc56edSDimitry Andric           // We can handle this if the vector we are inserting into is
332f22ef01cSRoman Divacky           // transitively ok.
3337d523365SDimitry Andric           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
334f22ef01cSRoman Divacky             // If so, update the mask to reflect the inserted value.
335f22ef01cSRoman Divacky             if (EI->getOperand(0) == LHS) {
336f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
337f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
338f22ef01cSRoman Divacky                                ExtractedIdx);
339f22ef01cSRoman Divacky             } else {
340f22ef01cSRoman Divacky               assert(EI->getOperand(0) == RHS);
341f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
342f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
34391bc56edSDimitry Andric                                ExtractedIdx + NumLHSElts);
344f22ef01cSRoman Divacky             }
345f22ef01cSRoman Divacky             return true;
346f22ef01cSRoman Divacky           }
347f22ef01cSRoman Divacky         }
348f22ef01cSRoman Divacky       }
349f22ef01cSRoman Divacky     }
350f22ef01cSRoman Divacky   }
351f22ef01cSRoman Divacky 
352f22ef01cSRoman Divacky   return false;
353f22ef01cSRoman Divacky }
354f22ef01cSRoman Divacky 
3557d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we
3567d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single
3577d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs.
3587d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt,
3597d523365SDimitry Andric                                    ExtractElementInst *ExtElt,
3607d523365SDimitry Andric                                    InstCombiner &IC) {
3617d523365SDimitry Andric   VectorType *InsVecType = InsElt->getType();
3627d523365SDimitry Andric   VectorType *ExtVecType = ExtElt->getVectorOperandType();
3637d523365SDimitry Andric   unsigned NumInsElts = InsVecType->getVectorNumElements();
3647d523365SDimitry Andric   unsigned NumExtElts = ExtVecType->getVectorNumElements();
3657d523365SDimitry Andric 
3667d523365SDimitry Andric   // The inserted-to vector must be wider than the extracted-from vector.
3677d523365SDimitry Andric   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
3687d523365SDimitry Andric       NumExtElts >= NumInsElts)
3697d523365SDimitry Andric     return;
3707d523365SDimitry Andric 
3717d523365SDimitry Andric   // Create a shuffle mask to widen the extended-from vector using undefined
3727d523365SDimitry Andric   // values. The mask selects all of the values of the original vector followed
3737d523365SDimitry Andric   // by as many undefined values as needed to create a vector of the same length
3747d523365SDimitry Andric   // as the inserted-to vector.
3757d523365SDimitry Andric   SmallVector<Constant *, 16> ExtendMask;
3767d523365SDimitry Andric   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
3777d523365SDimitry Andric   for (unsigned i = 0; i < NumExtElts; ++i)
3787d523365SDimitry Andric     ExtendMask.push_back(ConstantInt::get(IntType, i));
3797d523365SDimitry Andric   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
3807d523365SDimitry Andric     ExtendMask.push_back(UndefValue::get(IntType));
3817d523365SDimitry Andric 
3827d523365SDimitry Andric   Value *ExtVecOp = ExtElt->getVectorOperand();
383a8bcc4d8SDimitry Andric   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
384a8bcc4d8SDimitry Andric   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
385a8bcc4d8SDimitry Andric                                    ? ExtVecOpInst->getParent()
386a8bcc4d8SDimitry Andric                                    : ExtElt->getParent();
387a8bcc4d8SDimitry Andric 
388a8bcc4d8SDimitry Andric   // TODO: This restriction matches the basic block check below when creating
389a8bcc4d8SDimitry Andric   // new extractelement instructions. If that limitation is removed, this one
390a8bcc4d8SDimitry Andric   // could also be removed. But for now, we just bail out to ensure that we
391a8bcc4d8SDimitry Andric   // will replace the extractelement instruction that is feeding our
392a8bcc4d8SDimitry Andric   // insertelement instruction. This allows the insertelement to then be
393a8bcc4d8SDimitry Andric   // replaced by a shufflevector. If the insertelement is not replaced, we can
394a8bcc4d8SDimitry Andric   // induce infinite looping because there's an optimization for extractelement
395a8bcc4d8SDimitry Andric   // that will delete our widening shuffle. This would trigger another attempt
396a8bcc4d8SDimitry Andric   // here to create that shuffle, and we spin forever.
397a8bcc4d8SDimitry Andric   if (InsertionBlock != InsElt->getParent())
398a8bcc4d8SDimitry Andric     return;
399a8bcc4d8SDimitry Andric 
4007d523365SDimitry Andric   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
4017d523365SDimitry Andric                                         ConstantVector::get(ExtendMask));
4027d523365SDimitry Andric 
4034d0b32cdSDimitry Andric   // Insert the new shuffle after the vector operand of the extract is defined
404444ed5c5SDimitry Andric   // (as long as it's not a PHI) or at the start of the basic block of the
405444ed5c5SDimitry Andric   // extract, so any subsequent extracts in the same basic block can use it.
406444ed5c5SDimitry Andric   // TODO: Insert before the earliest ExtractElementInst that is replaced.
407444ed5c5SDimitry Andric   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
4084d0b32cdSDimitry Andric     WideVec->insertAfter(ExtVecOpInst);
409444ed5c5SDimitry Andric   else
4104d0b32cdSDimitry Andric     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
4114d0b32cdSDimitry Andric 
4124d0b32cdSDimitry Andric   // Replace extracts from the original narrow vector with extracts from the new
4134d0b32cdSDimitry Andric   // wide vector.
4147d523365SDimitry Andric   for (User *U : ExtVecOp->users()) {
4154d0b32cdSDimitry Andric     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
416444ed5c5SDimitry Andric     if (!OldExt || OldExt->getParent() != WideVec->getParent())
4174d0b32cdSDimitry Andric       continue;
4187d523365SDimitry Andric     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
4197d523365SDimitry Andric     NewExt->insertAfter(WideVec);
4207d523365SDimitry Andric     IC.ReplaceInstUsesWith(*OldExt, NewExt);
4217d523365SDimitry Andric   }
4227d523365SDimitry Andric }
42391bc56edSDimitry Andric 
42491bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement,
42591bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or
42691bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the
42791bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask
42891bc56edSDimitry Andric /// parameter as required.
42991bc56edSDimitry Andric ///
43091bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have
43191bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target.
43291bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps;
43391bc56edSDimitry Andric 
4347d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V,
43591bc56edSDimitry Andric                                          SmallVectorImpl<Constant *> &Mask,
4367d523365SDimitry Andric                                          Value *PermittedRHS,
4377d523365SDimitry Andric                                          InstCombiner &IC) {
43891bc56edSDimitry Andric   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
439f22ef01cSRoman Divacky   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
440f22ef01cSRoman Divacky 
441f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
442f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
44391bc56edSDimitry Andric     return std::make_pair(
44491bc56edSDimitry Andric         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
445dff0c46cSDimitry Andric   }
446dff0c46cSDimitry Andric 
447dff0c46cSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
448f22ef01cSRoman Divacky     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
44991bc56edSDimitry Andric     return std::make_pair(V, nullptr);
450dff0c46cSDimitry Andric   }
451dff0c46cSDimitry Andric 
452dff0c46cSDimitry Andric   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
453f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
454f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
455f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
456f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
457f22ef01cSRoman Divacky 
458f22ef01cSRoman Divacky     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
45991bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
460f22ef01cSRoman Divacky         unsigned ExtractedIdx =
461f22ef01cSRoman Divacky           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
462f22ef01cSRoman Divacky         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
463f22ef01cSRoman Divacky 
464f22ef01cSRoman Divacky         // Either the extracted from or inserted into vector must be RHSVec,
465f22ef01cSRoman Divacky         // otherwise we'd end up with a shuffle of three inputs.
46691bc56edSDimitry Andric         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
46791bc56edSDimitry Andric           Value *RHS = EI->getOperand(0);
4687d523365SDimitry Andric           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
46991bc56edSDimitry Andric           assert(LR.second == nullptr || LR.second == RHS);
47091bc56edSDimitry Andric 
47191bc56edSDimitry Andric           if (LR.first->getType() != RHS->getType()) {
4727d523365SDimitry Andric             // Although we are giving up for now, see if we can create extracts
4737d523365SDimitry Andric             // that match the inserts for another round of combining.
4747d523365SDimitry Andric             replaceExtractElements(IEI, EI, IC);
4757d523365SDimitry Andric 
47691bc56edSDimitry Andric             // We tried our best, but we can't find anything compatible with RHS
47791bc56edSDimitry Andric             // further up the chain. Return a trivial shuffle.
47891bc56edSDimitry Andric             for (unsigned i = 0; i < NumElts; ++i)
47991bc56edSDimitry Andric               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
48091bc56edSDimitry Andric             return std::make_pair(V, nullptr);
48191bc56edSDimitry Andric           }
48291bc56edSDimitry Andric 
48391bc56edSDimitry Andric           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
484f22ef01cSRoman Divacky           Mask[InsertedIdx % NumElts] =
485f22ef01cSRoman Divacky             ConstantInt::get(Type::getInt32Ty(V->getContext()),
48691bc56edSDimitry Andric                              NumLHSElts+ExtractedIdx);
48791bc56edSDimitry Andric           return std::make_pair(LR.first, RHS);
488f22ef01cSRoman Divacky         }
489f22ef01cSRoman Divacky 
49091bc56edSDimitry Andric         if (VecOp == PermittedRHS) {
49191bc56edSDimitry Andric           // We've gone as far as we can: anything on the other side of the
49291bc56edSDimitry Andric           // extractelement will already have been converted into a shuffle.
49391bc56edSDimitry Andric           unsigned NumLHSElts =
49491bc56edSDimitry Andric               EI->getOperand(0)->getType()->getVectorNumElements();
49591bc56edSDimitry Andric           for (unsigned i = 0; i != NumElts; ++i)
49691bc56edSDimitry Andric             Mask.push_back(ConstantInt::get(
49791bc56edSDimitry Andric                 Type::getInt32Ty(V->getContext()),
49891bc56edSDimitry Andric                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
49991bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
500f22ef01cSRoman Divacky         }
501f22ef01cSRoman Divacky 
502f22ef01cSRoman Divacky         // If this insertelement is a chain that comes from exactly these two
503f22ef01cSRoman Divacky         // vectors, return the vector and the effective shuffle.
50491bc56edSDimitry Andric         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
5057d523365SDimitry Andric             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
50691bc56edSDimitry Andric                                          Mask))
50791bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
508f22ef01cSRoman Divacky       }
509f22ef01cSRoman Divacky     }
510f22ef01cSRoman Divacky   }
511f22ef01cSRoman Divacky 
5127d523365SDimitry Andric   // Otherwise, we can't do anything fancy. Return an identity vector.
513f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumElts; ++i)
514f22ef01cSRoman Divacky     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
51591bc56edSDimitry Andric   return std::make_pair(V, nullptr);
51691bc56edSDimitry Andric }
51791bc56edSDimitry Andric 
51891bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones:
51991bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
52091bc56edSDimitry Andric ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
52191bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the
52291bc56edSDimitry Andric /// first one, making the first one redundant.
52391bc56edSDimitry Andric /// It should be transformed to:
52491bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
52591bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
52691bc56edSDimitry Andric   bool IsRedundant = false;
52791bc56edSDimitry Andric   ArrayRef<unsigned int> FirstIndices = I.getIndices();
52891bc56edSDimitry Andric 
52991bc56edSDimitry Andric   // If there is a chain of insertvalue instructions (each of them except the
53091bc56edSDimitry Andric   // last one has only one use and it's another insertvalue insn from this
53191bc56edSDimitry Andric   // chain), check if any of the 'children' uses the same indices as the first
53291bc56edSDimitry Andric   // instruction. In this case, the first one is redundant.
53391bc56edSDimitry Andric   Value *V = &I;
53491bc56edSDimitry Andric   unsigned Depth = 0;
53591bc56edSDimitry Andric   while (V->hasOneUse() && Depth < 10) {
53691bc56edSDimitry Andric     User *U = V->user_back();
53791bc56edSDimitry Andric     auto UserInsInst = dyn_cast<InsertValueInst>(U);
53891bc56edSDimitry Andric     if (!UserInsInst || U->getOperand(0) != V)
53991bc56edSDimitry Andric       break;
54091bc56edSDimitry Andric     if (UserInsInst->getIndices() == FirstIndices) {
54191bc56edSDimitry Andric       IsRedundant = true;
54291bc56edSDimitry Andric       break;
54391bc56edSDimitry Andric     }
54491bc56edSDimitry Andric     V = UserInsInst;
54591bc56edSDimitry Andric     Depth++;
54691bc56edSDimitry Andric   }
54791bc56edSDimitry Andric 
54891bc56edSDimitry Andric   if (IsRedundant)
54991bc56edSDimitry Andric     return ReplaceInstUsesWith(I, I.getOperand(0));
55091bc56edSDimitry Andric   return nullptr;
551f22ef01cSRoman Divacky }
552f22ef01cSRoman Divacky 
553f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
554f22ef01cSRoman Divacky   Value *VecOp    = IE.getOperand(0);
555f22ef01cSRoman Divacky   Value *ScalarOp = IE.getOperand(1);
556f22ef01cSRoman Divacky   Value *IdxOp    = IE.getOperand(2);
557f22ef01cSRoman Divacky 
558f22ef01cSRoman Divacky   // Inserting an undef or into an undefined place, remove this.
559f22ef01cSRoman Divacky   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
560f22ef01cSRoman Divacky     ReplaceInstUsesWith(IE, VecOp);
561f22ef01cSRoman Divacky 
562f22ef01cSRoman Divacky   // If the inserted element was extracted from some other vector, and if the
563f22ef01cSRoman Divacky   // indexes are constant, try to turn this into a shufflevector operation.
564f22ef01cSRoman Divacky   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
56591bc56edSDimitry Andric     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
56691bc56edSDimitry Andric       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
56791bc56edSDimitry Andric       unsigned NumExtractVectorElts =
56891bc56edSDimitry Andric           EI->getOperand(0)->getType()->getVectorNumElements();
569f22ef01cSRoman Divacky       unsigned ExtractedIdx =
570f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
571f22ef01cSRoman Divacky       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
572f22ef01cSRoman Divacky 
57391bc56edSDimitry Andric       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
574f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
575f22ef01cSRoman Divacky 
57691bc56edSDimitry Andric       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
577f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
578f22ef01cSRoman Divacky 
579f22ef01cSRoman Divacky       // If we are extracting a value from a vector, then inserting it right
580f22ef01cSRoman Divacky       // back into the same place, just use the input vector.
581f22ef01cSRoman Divacky       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
582f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
583f22ef01cSRoman Divacky 
584f22ef01cSRoman Divacky       // If this insertelement isn't used by some other insertelement, turn it
585f22ef01cSRoman Divacky       // (and any insertelements it points to), into one big shuffle.
58691bc56edSDimitry Andric       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
587dff0c46cSDimitry Andric         SmallVector<Constant*, 16> Mask;
5887d523365SDimitry Andric         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
58991bc56edSDimitry Andric 
59091bc56edSDimitry Andric         // The proposed shuffle may be trivial, in which case we shouldn't
59191bc56edSDimitry Andric         // perform the combine.
59291bc56edSDimitry Andric         if (LR.first != &IE && LR.second != &IE) {
593f22ef01cSRoman Divacky           // We now have a shuffle of LHS, RHS, Mask.
59491bc56edSDimitry Andric           if (LR.second == nullptr)
59591bc56edSDimitry Andric             LR.second = UndefValue::get(LR.first->getType());
59691bc56edSDimitry Andric           return new ShuffleVectorInst(LR.first, LR.second,
59791bc56edSDimitry Andric                                        ConstantVector::get(Mask));
59891bc56edSDimitry Andric         }
599f22ef01cSRoman Divacky       }
600f22ef01cSRoman Divacky     }
601f22ef01cSRoman Divacky   }
602f22ef01cSRoman Divacky 
603f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
604f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
605f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
6062754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
6072754fe60SDimitry Andric     if (V != &IE)
6082754fe60SDimitry Andric       return ReplaceInstUsesWith(IE, V);
609f22ef01cSRoman Divacky     return &IE;
6102754fe60SDimitry Andric   }
611f22ef01cSRoman Divacky 
61291bc56edSDimitry Andric   return nullptr;
613f22ef01cSRoman Divacky }
614f22ef01cSRoman Divacky 
615f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector
616f785676fSDimitry Andric /// elements were shuffled in a different order.
617f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
618f785676fSDimitry Andric                                 unsigned Depth = 5) {
619f785676fSDimitry Andric   // We can always reorder the elements of a constant.
620f785676fSDimitry Andric   if (isa<Constant>(V))
621f785676fSDimitry Andric     return true;
622f785676fSDimitry Andric 
623f785676fSDimitry Andric   // We won't reorder vector arguments. No IPO here.
624f785676fSDimitry Andric   Instruction *I = dyn_cast<Instruction>(V);
625f785676fSDimitry Andric   if (!I) return false;
626f785676fSDimitry Andric 
627f785676fSDimitry Andric   // Two users may expect different orders of the elements. Don't try it.
628f785676fSDimitry Andric   if (!I->hasOneUse())
629f785676fSDimitry Andric     return false;
630f785676fSDimitry Andric 
631f785676fSDimitry Andric   if (Depth == 0) return false;
632f785676fSDimitry Andric 
633f785676fSDimitry Andric   switch (I->getOpcode()) {
634f785676fSDimitry Andric     case Instruction::Add:
635f785676fSDimitry Andric     case Instruction::FAdd:
636f785676fSDimitry Andric     case Instruction::Sub:
637f785676fSDimitry Andric     case Instruction::FSub:
638f785676fSDimitry Andric     case Instruction::Mul:
639f785676fSDimitry Andric     case Instruction::FMul:
640f785676fSDimitry Andric     case Instruction::UDiv:
641f785676fSDimitry Andric     case Instruction::SDiv:
642f785676fSDimitry Andric     case Instruction::FDiv:
643f785676fSDimitry Andric     case Instruction::URem:
644f785676fSDimitry Andric     case Instruction::SRem:
645f785676fSDimitry Andric     case Instruction::FRem:
646f785676fSDimitry Andric     case Instruction::Shl:
647f785676fSDimitry Andric     case Instruction::LShr:
648f785676fSDimitry Andric     case Instruction::AShr:
649f785676fSDimitry Andric     case Instruction::And:
650f785676fSDimitry Andric     case Instruction::Or:
651f785676fSDimitry Andric     case Instruction::Xor:
652f785676fSDimitry Andric     case Instruction::ICmp:
653f785676fSDimitry Andric     case Instruction::FCmp:
654f785676fSDimitry Andric     case Instruction::Trunc:
655f785676fSDimitry Andric     case Instruction::ZExt:
656f785676fSDimitry Andric     case Instruction::SExt:
657f785676fSDimitry Andric     case Instruction::FPToUI:
658f785676fSDimitry Andric     case Instruction::FPToSI:
659f785676fSDimitry Andric     case Instruction::UIToFP:
660f785676fSDimitry Andric     case Instruction::SIToFP:
661f785676fSDimitry Andric     case Instruction::FPTrunc:
662f785676fSDimitry Andric     case Instruction::FPExt:
663f785676fSDimitry Andric     case Instruction::GetElementPtr: {
6647d523365SDimitry Andric       for (Value *Operand : I->operands()) {
6657d523365SDimitry Andric         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
666f785676fSDimitry Andric           return false;
667f785676fSDimitry Andric       }
668f785676fSDimitry Andric       return true;
669f785676fSDimitry Andric     }
670f785676fSDimitry Andric     case Instruction::InsertElement: {
671f785676fSDimitry Andric       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
672f785676fSDimitry Andric       if (!CI) return false;
673f785676fSDimitry Andric       int ElementNumber = CI->getLimitedValue();
674f785676fSDimitry Andric 
675f785676fSDimitry Andric       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
676f785676fSDimitry Andric       // can't put an element into multiple indices.
677f785676fSDimitry Andric       bool SeenOnce = false;
678f785676fSDimitry Andric       for (int i = 0, e = Mask.size(); i != e; ++i) {
679f785676fSDimitry Andric         if (Mask[i] == ElementNumber) {
680f785676fSDimitry Andric           if (SeenOnce)
681f785676fSDimitry Andric             return false;
682f785676fSDimitry Andric           SeenOnce = true;
683f785676fSDimitry Andric         }
684f785676fSDimitry Andric       }
685f785676fSDimitry Andric       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
686f785676fSDimitry Andric     }
687f785676fSDimitry Andric   }
688f785676fSDimitry Andric   return false;
689f785676fSDimitry Andric }
690f785676fSDimitry Andric 
691f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given.
692f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct.
6937d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
694f785676fSDimitry Andric   // We don't want to use the IRBuilder here because we want the replacement
695f785676fSDimitry Andric   // instructions to appear next to 'I', not the builder's insertion point.
696f785676fSDimitry Andric   switch (I->getOpcode()) {
697f785676fSDimitry Andric     case Instruction::Add:
698f785676fSDimitry Andric     case Instruction::FAdd:
699f785676fSDimitry Andric     case Instruction::Sub:
700f785676fSDimitry Andric     case Instruction::FSub:
701f785676fSDimitry Andric     case Instruction::Mul:
702f785676fSDimitry Andric     case Instruction::FMul:
703f785676fSDimitry Andric     case Instruction::UDiv:
704f785676fSDimitry Andric     case Instruction::SDiv:
705f785676fSDimitry Andric     case Instruction::FDiv:
706f785676fSDimitry Andric     case Instruction::URem:
707f785676fSDimitry Andric     case Instruction::SRem:
708f785676fSDimitry Andric     case Instruction::FRem:
709f785676fSDimitry Andric     case Instruction::Shl:
710f785676fSDimitry Andric     case Instruction::LShr:
711f785676fSDimitry Andric     case Instruction::AShr:
712f785676fSDimitry Andric     case Instruction::And:
713f785676fSDimitry Andric     case Instruction::Or:
714f785676fSDimitry Andric     case Instruction::Xor: {
715f785676fSDimitry Andric       BinaryOperator *BO = cast<BinaryOperator>(I);
716f785676fSDimitry Andric       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
717f785676fSDimitry Andric       BinaryOperator *New =
718f785676fSDimitry Andric           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
719f785676fSDimitry Andric                                  NewOps[0], NewOps[1], "", BO);
720f785676fSDimitry Andric       if (isa<OverflowingBinaryOperator>(BO)) {
721f785676fSDimitry Andric         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
722f785676fSDimitry Andric         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
723f785676fSDimitry Andric       }
724f785676fSDimitry Andric       if (isa<PossiblyExactOperator>(BO)) {
725f785676fSDimitry Andric         New->setIsExact(BO->isExact());
726f785676fSDimitry Andric       }
72791bc56edSDimitry Andric       if (isa<FPMathOperator>(BO))
72891bc56edSDimitry Andric         New->copyFastMathFlags(I);
729f785676fSDimitry Andric       return New;
730f785676fSDimitry Andric     }
731f785676fSDimitry Andric     case Instruction::ICmp:
732f785676fSDimitry Andric       assert(NewOps.size() == 2 && "icmp with #ops != 2");
733f785676fSDimitry Andric       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
734f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
735f785676fSDimitry Andric     case Instruction::FCmp:
736f785676fSDimitry Andric       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
737f785676fSDimitry Andric       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
738f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
739f785676fSDimitry Andric     case Instruction::Trunc:
740f785676fSDimitry Andric     case Instruction::ZExt:
741f785676fSDimitry Andric     case Instruction::SExt:
742f785676fSDimitry Andric     case Instruction::FPToUI:
743f785676fSDimitry Andric     case Instruction::FPToSI:
744f785676fSDimitry Andric     case Instruction::UIToFP:
745f785676fSDimitry Andric     case Instruction::SIToFP:
746f785676fSDimitry Andric     case Instruction::FPTrunc:
747f785676fSDimitry Andric     case Instruction::FPExt: {
748f785676fSDimitry Andric       // It's possible that the mask has a different number of elements from
749f785676fSDimitry Andric       // the original cast. We recompute the destination type to match the mask.
750f785676fSDimitry Andric       Type *DestTy =
751f785676fSDimitry Andric           VectorType::get(I->getType()->getScalarType(),
752f785676fSDimitry Andric                           NewOps[0]->getType()->getVectorNumElements());
753f785676fSDimitry Andric       assert(NewOps.size() == 1 && "cast with #ops != 1");
754f785676fSDimitry Andric       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
755f785676fSDimitry Andric                               "", I);
756f785676fSDimitry Andric     }
757f785676fSDimitry Andric     case Instruction::GetElementPtr: {
758f785676fSDimitry Andric       Value *Ptr = NewOps[0];
759f785676fSDimitry Andric       ArrayRef<Value*> Idx = NewOps.slice(1);
760ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
761ff0cc061SDimitry Andric           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
762f785676fSDimitry Andric       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
763f785676fSDimitry Andric       return GEP;
764f785676fSDimitry Andric     }
765f785676fSDimitry Andric   }
766f785676fSDimitry Andric   llvm_unreachable("failed to rebuild vector instructions");
767f785676fSDimitry Andric }
768f785676fSDimitry Andric 
769f785676fSDimitry Andric Value *
770f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
771f785676fSDimitry Andric   // Mask.size() does not need to be equal to the number of vector elements.
772f785676fSDimitry Andric 
773f785676fSDimitry Andric   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
774f785676fSDimitry Andric   if (isa<UndefValue>(V)) {
775f785676fSDimitry Andric     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
776f785676fSDimitry Andric                                            Mask.size()));
777f785676fSDimitry Andric   }
778f785676fSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
779f785676fSDimitry Andric     return ConstantAggregateZero::get(
780f785676fSDimitry Andric                VectorType::get(V->getType()->getScalarType(),
781f785676fSDimitry Andric                                Mask.size()));
782f785676fSDimitry Andric   }
783f785676fSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
784f785676fSDimitry Andric     SmallVector<Constant *, 16> MaskValues;
785f785676fSDimitry Andric     for (int i = 0, e = Mask.size(); i != e; ++i) {
786f785676fSDimitry Andric       if (Mask[i] == -1)
787f785676fSDimitry Andric         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
788f785676fSDimitry Andric       else
789f785676fSDimitry Andric         MaskValues.push_back(Builder->getInt32(Mask[i]));
790f785676fSDimitry Andric     }
791f785676fSDimitry Andric     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
792f785676fSDimitry Andric                                           ConstantVector::get(MaskValues));
793f785676fSDimitry Andric   }
794f785676fSDimitry Andric 
795f785676fSDimitry Andric   Instruction *I = cast<Instruction>(V);
796f785676fSDimitry Andric   switch (I->getOpcode()) {
797f785676fSDimitry Andric     case Instruction::Add:
798f785676fSDimitry Andric     case Instruction::FAdd:
799f785676fSDimitry Andric     case Instruction::Sub:
800f785676fSDimitry Andric     case Instruction::FSub:
801f785676fSDimitry Andric     case Instruction::Mul:
802f785676fSDimitry Andric     case Instruction::FMul:
803f785676fSDimitry Andric     case Instruction::UDiv:
804f785676fSDimitry Andric     case Instruction::SDiv:
805f785676fSDimitry Andric     case Instruction::FDiv:
806f785676fSDimitry Andric     case Instruction::URem:
807f785676fSDimitry Andric     case Instruction::SRem:
808f785676fSDimitry Andric     case Instruction::FRem:
809f785676fSDimitry Andric     case Instruction::Shl:
810f785676fSDimitry Andric     case Instruction::LShr:
811f785676fSDimitry Andric     case Instruction::AShr:
812f785676fSDimitry Andric     case Instruction::And:
813f785676fSDimitry Andric     case Instruction::Or:
814f785676fSDimitry Andric     case Instruction::Xor:
815f785676fSDimitry Andric     case Instruction::ICmp:
816f785676fSDimitry Andric     case Instruction::FCmp:
817f785676fSDimitry Andric     case Instruction::Trunc:
818f785676fSDimitry Andric     case Instruction::ZExt:
819f785676fSDimitry Andric     case Instruction::SExt:
820f785676fSDimitry Andric     case Instruction::FPToUI:
821f785676fSDimitry Andric     case Instruction::FPToSI:
822f785676fSDimitry Andric     case Instruction::UIToFP:
823f785676fSDimitry Andric     case Instruction::SIToFP:
824f785676fSDimitry Andric     case Instruction::FPTrunc:
825f785676fSDimitry Andric     case Instruction::FPExt:
826f785676fSDimitry Andric     case Instruction::Select:
827f785676fSDimitry Andric     case Instruction::GetElementPtr: {
828f785676fSDimitry Andric       SmallVector<Value*, 8> NewOps;
829f785676fSDimitry Andric       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
830f785676fSDimitry Andric       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
831f785676fSDimitry Andric         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
832f785676fSDimitry Andric         NewOps.push_back(V);
833f785676fSDimitry Andric         NeedsRebuild |= (V != I->getOperand(i));
834f785676fSDimitry Andric       }
835f785676fSDimitry Andric       if (NeedsRebuild) {
8367d523365SDimitry Andric         return buildNew(I, NewOps);
837f785676fSDimitry Andric       }
838f785676fSDimitry Andric       return I;
839f785676fSDimitry Andric     }
840f785676fSDimitry Andric     case Instruction::InsertElement: {
841f785676fSDimitry Andric       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
842f785676fSDimitry Andric 
843f785676fSDimitry Andric       // The insertelement was inserting at Element. Figure out which element
844f785676fSDimitry Andric       // that becomes after shuffling. The answer is guaranteed to be unique
845f785676fSDimitry Andric       // by CanEvaluateShuffled.
846f785676fSDimitry Andric       bool Found = false;
847f785676fSDimitry Andric       int Index = 0;
848f785676fSDimitry Andric       for (int e = Mask.size(); Index != e; ++Index) {
849f785676fSDimitry Andric         if (Mask[Index] == Element) {
850f785676fSDimitry Andric           Found = true;
851f785676fSDimitry Andric           break;
852f785676fSDimitry Andric         }
853f785676fSDimitry Andric       }
854f785676fSDimitry Andric 
85591bc56edSDimitry Andric       // If element is not in Mask, no need to handle the operand 1 (element to
85691bc56edSDimitry Andric       // be inserted). Just evaluate values in operand 0 according to Mask.
857f785676fSDimitry Andric       if (!Found)
85891bc56edSDimitry Andric         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
859f785676fSDimitry Andric 
860f785676fSDimitry Andric       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
861f785676fSDimitry Andric       return InsertElementInst::Create(V, I->getOperand(1),
862f785676fSDimitry Andric                                        Builder->getInt32(Index), "", I);
863f785676fSDimitry Andric     }
864f785676fSDimitry Andric   }
865f785676fSDimitry Andric   llvm_unreachable("failed to reorder elements of vector instruction!");
866f785676fSDimitry Andric }
867f22ef01cSRoman Divacky 
8687d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
86991bc56edSDimitry Andric                                   bool &isLHSID, bool &isRHSID) {
87091bc56edSDimitry Andric   isLHSID = isRHSID = true;
87191bc56edSDimitry Andric 
87291bc56edSDimitry Andric   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
87391bc56edSDimitry Andric     if (Mask[i] < 0) continue;  // Ignore undef values.
87491bc56edSDimitry Andric     // Is this an identity shuffle of the LHS value?
87591bc56edSDimitry Andric     isLHSID &= (Mask[i] == (int)i);
87691bc56edSDimitry Andric 
87791bc56edSDimitry Andric     // Is this an identity shuffle of the RHS value?
87891bc56edSDimitry Andric     isRHSID &= (Mask[i]-e == i);
87991bc56edSDimitry Andric   }
88091bc56edSDimitry Andric }
88191bc56edSDimitry Andric 
882ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from
883ff0cc061SDimitry Andric // LHS, for example:
884ff0cc061SDimitry Andric //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
885ff0cc061SDimitry Andric //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
886ff0cc061SDimitry Andric //   Shuffles to:  |EE|FF|GG|HH|
887ff0cc061SDimitry Andric //                 +--+--+--+--+
888ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
889ff0cc061SDimitry Andric                                        SmallVector<int, 16> &Mask) {
890ff0cc061SDimitry Andric   unsigned LHSElems =
891ff0cc061SDimitry Andric       cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
892ff0cc061SDimitry Andric   unsigned MaskElems = Mask.size();
893ff0cc061SDimitry Andric   unsigned BegIdx = Mask.front();
894ff0cc061SDimitry Andric   unsigned EndIdx = Mask.back();
895ff0cc061SDimitry Andric   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
896ff0cc061SDimitry Andric     return false;
897ff0cc061SDimitry Andric   for (unsigned I = 0; I != MaskElems; ++I)
898ff0cc061SDimitry Andric     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
899ff0cc061SDimitry Andric       return false;
900ff0cc061SDimitry Andric   return true;
901ff0cc061SDimitry Andric }
902ff0cc061SDimitry Andric 
903f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
904f22ef01cSRoman Divacky   Value *LHS = SVI.getOperand(0);
905f22ef01cSRoman Divacky   Value *RHS = SVI.getOperand(1);
906dff0c46cSDimitry Andric   SmallVector<int, 16> Mask = SVI.getShuffleMask();
907ff0cc061SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
908f22ef01cSRoman Divacky 
909f22ef01cSRoman Divacky   bool MadeChange = false;
910f22ef01cSRoman Divacky 
911f22ef01cSRoman Divacky   // Undefined shuffle mask -> undefined value.
912f22ef01cSRoman Divacky   if (isa<UndefValue>(SVI.getOperand(2)))
913f22ef01cSRoman Divacky     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
914f22ef01cSRoman Divacky 
915f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
916f22ef01cSRoman Divacky 
917f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
918f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9192754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
9202754fe60SDimitry Andric     if (V != &SVI)
9212754fe60SDimitry Andric       return ReplaceInstUsesWith(SVI, V);
922f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
923f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
924f22ef01cSRoman Divacky     MadeChange = true;
925f22ef01cSRoman Divacky   }
926f22ef01cSRoman Divacky 
927dff0c46cSDimitry Andric   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
928dff0c46cSDimitry Andric 
929f22ef01cSRoman Divacky   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
930f22ef01cSRoman Divacky   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
931f22ef01cSRoman Divacky   if (LHS == RHS || isa<UndefValue>(LHS)) {
932f22ef01cSRoman Divacky     if (isa<UndefValue>(LHS) && LHS == RHS) {
933f22ef01cSRoman Divacky       // shuffle(undef,undef,mask) -> undef.
934f785676fSDimitry Andric       Value *Result = (VWidth == LHSWidth)
935dff0c46cSDimitry Andric                       ? LHS : UndefValue::get(SVI.getType());
936f785676fSDimitry Andric       return ReplaceInstUsesWith(SVI, Result);
937f22ef01cSRoman Divacky     }
938f22ef01cSRoman Divacky 
939f22ef01cSRoman Divacky     // Remap any references to RHS to use LHS.
940dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
941dff0c46cSDimitry Andric     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
942dff0c46cSDimitry Andric       if (Mask[i] < 0) {
943ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
944dff0c46cSDimitry Andric         continue;
945dff0c46cSDimitry Andric       }
946dff0c46cSDimitry Andric 
9472754fe60SDimitry Andric       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
9482754fe60SDimitry Andric           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
9492754fe60SDimitry Andric         Mask[i] = -1;     // Turn into undef.
950ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
951f22ef01cSRoman Divacky       } else {
952f22ef01cSRoman Divacky         Mask[i] = Mask[i] % e;  // Force to LHS.
953ff0cc061SDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
954f22ef01cSRoman Divacky       }
955f22ef01cSRoman Divacky     }
956f22ef01cSRoman Divacky     SVI.setOperand(0, SVI.getOperand(1));
957f22ef01cSRoman Divacky     SVI.setOperand(1, UndefValue::get(RHS->getType()));
958f22ef01cSRoman Divacky     SVI.setOperand(2, ConstantVector::get(Elts));
959f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
960f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
961f22ef01cSRoman Divacky     MadeChange = true;
962f22ef01cSRoman Divacky   }
963f22ef01cSRoman Divacky 
964dff0c46cSDimitry Andric   if (VWidth == LHSWidth) {
965f22ef01cSRoman Divacky     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
96691bc56edSDimitry Andric     bool isLHSID, isRHSID;
9677d523365SDimitry Andric     recognizeIdentityMask(Mask, isLHSID, isRHSID);
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky     // Eliminate identity shuffles.
970f22ef01cSRoman Divacky     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
971f22ef01cSRoman Divacky     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
972dff0c46cSDimitry Andric   }
973f22ef01cSRoman Divacky 
974f785676fSDimitry Andric   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
975f785676fSDimitry Andric     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
976f785676fSDimitry Andric     return ReplaceInstUsesWith(SVI, V);
977f785676fSDimitry Andric   }
978f785676fSDimitry Andric 
979ff0cc061SDimitry Andric   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
980ff0cc061SDimitry Andric   // a non-vector type. We can instead bitcast the original vector followed by
981ff0cc061SDimitry Andric   // an extract of the desired element:
982ff0cc061SDimitry Andric   //
983ff0cc061SDimitry Andric   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
984ff0cc061SDimitry Andric   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
985ff0cc061SDimitry Andric   //   %1 = bitcast <4 x i8> %sroa to i32
986ff0cc061SDimitry Andric   // Becomes:
987ff0cc061SDimitry Andric   //   %bc = bitcast <16 x i8> %in to <4 x i32>
988ff0cc061SDimitry Andric   //   %ext = extractelement <4 x i32> %bc, i32 0
989ff0cc061SDimitry Andric   //
990ff0cc061SDimitry Andric   // If the shuffle is extracting a contiguous range of values from the input
991ff0cc061SDimitry Andric   // vector then each use which is a bitcast of the extracted size can be
992ff0cc061SDimitry Andric   // replaced. This will work if the vector types are compatible, and the begin
993ff0cc061SDimitry Andric   // index is aligned to a value in the casted vector type. If the begin index
994ff0cc061SDimitry Andric   // isn't aligned then we can shuffle the original vector (keeping the same
995ff0cc061SDimitry Andric   // vector type) before extracting.
996ff0cc061SDimitry Andric   //
997ff0cc061SDimitry Andric   // This code will bail out if the target type is fundamentally incompatible
998ff0cc061SDimitry Andric   // with vectors of the source type.
999ff0cc061SDimitry Andric   //
1000ff0cc061SDimitry Andric   // Example of <16 x i8>, target type i32:
1001ff0cc061SDimitry Andric   // Index range [4,8):         v-----------v Will work.
1002ff0cc061SDimitry Andric   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1003ff0cc061SDimitry Andric   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
1004ff0cc061SDimitry Andric   //     <4 x i32>: |           |           |           |           |
1005ff0cc061SDimitry Andric   //                +-----------+-----------+-----------+-----------+
1006ff0cc061SDimitry Andric   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
1007ff0cc061SDimitry Andric   // Target type i40:           ^--------------^ Won't work, bail.
1008ff0cc061SDimitry Andric   if (isShuffleExtractingFromLHS(SVI, Mask)) {
1009ff0cc061SDimitry Andric     Value *V = LHS;
1010ff0cc061SDimitry Andric     unsigned MaskElems = Mask.size();
1011ff0cc061SDimitry Andric     unsigned BegIdx = Mask.front();
1012ff0cc061SDimitry Andric     VectorType *SrcTy = cast<VectorType>(V->getType());
1013ff0cc061SDimitry Andric     unsigned VecBitWidth = SrcTy->getBitWidth();
1014ff0cc061SDimitry Andric     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1015ff0cc061SDimitry Andric     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1016ff0cc061SDimitry Andric     unsigned SrcNumElems = SrcTy->getNumElements();
1017ff0cc061SDimitry Andric     SmallVector<BitCastInst *, 8> BCs;
1018ff0cc061SDimitry Andric     DenseMap<Type *, Value *> NewBCs;
1019ff0cc061SDimitry Andric     for (User *U : SVI.users())
1020ff0cc061SDimitry Andric       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1021ff0cc061SDimitry Andric         if (!BC->use_empty())
1022ff0cc061SDimitry Andric           // Only visit bitcasts that weren't previously handled.
1023ff0cc061SDimitry Andric           BCs.push_back(BC);
1024ff0cc061SDimitry Andric     for (BitCastInst *BC : BCs) {
1025ff0cc061SDimitry Andric       Type *TgtTy = BC->getDestTy();
1026ff0cc061SDimitry Andric       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1027ff0cc061SDimitry Andric       if (!TgtElemBitWidth)
1028ff0cc061SDimitry Andric         continue;
1029ff0cc061SDimitry Andric       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1030ff0cc061SDimitry Andric       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1031ff0cc061SDimitry Andric       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1032ff0cc061SDimitry Andric       if (!VecBitWidthsEqual)
1033ff0cc061SDimitry Andric         continue;
1034ff0cc061SDimitry Andric       if (!VectorType::isValidElementType(TgtTy))
1035ff0cc061SDimitry Andric         continue;
1036ff0cc061SDimitry Andric       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1037ff0cc061SDimitry Andric       if (!BegIsAligned) {
1038ff0cc061SDimitry Andric         // Shuffle the input so [0,NumElements) contains the output, and
1039ff0cc061SDimitry Andric         // [NumElems,SrcNumElems) is undef.
1040ff0cc061SDimitry Andric         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1041ff0cc061SDimitry Andric                                                 UndefValue::get(Int32Ty));
1042ff0cc061SDimitry Andric         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1043ff0cc061SDimitry Andric           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1044ff0cc061SDimitry Andric         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1045ff0cc061SDimitry Andric                                          ConstantVector::get(ShuffleMask),
1046ff0cc061SDimitry Andric                                          SVI.getName() + ".extract");
1047ff0cc061SDimitry Andric         BegIdx = 0;
1048ff0cc061SDimitry Andric       }
1049ff0cc061SDimitry Andric       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1050ff0cc061SDimitry Andric       assert(SrcElemsPerTgtElem);
1051ff0cc061SDimitry Andric       BegIdx /= SrcElemsPerTgtElem;
1052ff0cc061SDimitry Andric       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1053ff0cc061SDimitry Andric       auto *NewBC =
1054ff0cc061SDimitry Andric           BCAlreadyExists
1055ff0cc061SDimitry Andric               ? NewBCs[CastSrcTy]
1056ff0cc061SDimitry Andric               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1057ff0cc061SDimitry Andric       if (!BCAlreadyExists)
1058ff0cc061SDimitry Andric         NewBCs[CastSrcTy] = NewBC;
1059ff0cc061SDimitry Andric       auto *Ext = Builder->CreateExtractElement(
1060ff0cc061SDimitry Andric           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1061ff0cc061SDimitry Andric       // The shufflevector isn't being replaced: the bitcast that used it
1062ff0cc061SDimitry Andric       // is. InstCombine will visit the newly-created instructions.
1063ff0cc061SDimitry Andric       ReplaceInstUsesWith(*BC, Ext);
1064ff0cc061SDimitry Andric       MadeChange = true;
1065ff0cc061SDimitry Andric     }
1066ff0cc061SDimitry Andric   }
1067ff0cc061SDimitry Andric 
1068f22ef01cSRoman Divacky   // If the LHS is a shufflevector itself, see if we can combine it with this
1069dff0c46cSDimitry Andric   // one without producing an unusual shuffle.
1070dff0c46cSDimitry Andric   // Cases that might be simplified:
1071dff0c46cSDimitry Andric   // 1.
1072dff0c46cSDimitry Andric   // x1=shuffle(v1,v2,mask1)
1073dff0c46cSDimitry Andric   //  x=shuffle(x1,undef,mask)
1074dff0c46cSDimitry Andric   //        ==>
1075dff0c46cSDimitry Andric   //  x=shuffle(v1,undef,newMask)
1076dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1077dff0c46cSDimitry Andric   // 2.
1078dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1079dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1080dff0c46cSDimitry Andric   // where v1.size() == mask1.size()
1081dff0c46cSDimitry Andric   //        ==>
1082dff0c46cSDimitry Andric   //  x=shuffle(v1,x2,newMask)
1083dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1084dff0c46cSDimitry Andric   // 3.
1085dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1086dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1087dff0c46cSDimitry Andric   // where v2.size() == mask2.size()
1088dff0c46cSDimitry Andric   //        ==>
1089dff0c46cSDimitry Andric   //  x=shuffle(x1,v2,newMask)
1090dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1091dff0c46cSDimitry Andric   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1092dff0c46cSDimitry Andric   // 4.
1093dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1094dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1095dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1096dff0c46cSDimitry Andric   // where v1.size() == v2.size()
1097dff0c46cSDimitry Andric   //        ==>
1098dff0c46cSDimitry Andric   //  x=shuffle(v1,v2,newMask)
1099dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1100dff0c46cSDimitry Andric   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1101dff0c46cSDimitry Andric   //
1102dff0c46cSDimitry Andric   // Here we are really conservative:
1103f22ef01cSRoman Divacky   // we are absolutely afraid of producing a shuffle mask not in the input
1104f22ef01cSRoman Divacky   // program, because the code gen may not be smart enough to turn a merged
1105f22ef01cSRoman Divacky   // shuffle into two specific shuffles: it may produce worse code.  As such,
11062754fe60SDimitry Andric   // we only merge two shuffles if the result is either a splat or one of the
1107dff0c46cSDimitry Andric   // input shuffle masks.  In this case, merging the shuffles just removes
11082754fe60SDimitry Andric   // one instruction, which we know is safe.  This is good for things like
1109dff0c46cSDimitry Andric   // turning: (splat(splat)) -> splat, or
1110dff0c46cSDimitry Andric   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1111dff0c46cSDimitry Andric   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1112dff0c46cSDimitry Andric   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1113dff0c46cSDimitry Andric   if (LHSShuffle)
1114dff0c46cSDimitry Andric     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
111591bc56edSDimitry Andric       LHSShuffle = nullptr;
1116dff0c46cSDimitry Andric   if (RHSShuffle)
1117dff0c46cSDimitry Andric     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
111891bc56edSDimitry Andric       RHSShuffle = nullptr;
1119dff0c46cSDimitry Andric   if (!LHSShuffle && !RHSShuffle)
112091bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1121dff0c46cSDimitry Andric 
112291bc56edSDimitry Andric   Value* LHSOp0 = nullptr;
112391bc56edSDimitry Andric   Value* LHSOp1 = nullptr;
112491bc56edSDimitry Andric   Value* RHSOp0 = nullptr;
1125dff0c46cSDimitry Andric   unsigned LHSOp0Width = 0;
1126dff0c46cSDimitry Andric   unsigned RHSOp0Width = 0;
1127dff0c46cSDimitry Andric   if (LHSShuffle) {
1128dff0c46cSDimitry Andric     LHSOp0 = LHSShuffle->getOperand(0);
1129dff0c46cSDimitry Andric     LHSOp1 = LHSShuffle->getOperand(1);
1130dff0c46cSDimitry Andric     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1131dff0c46cSDimitry Andric   }
1132dff0c46cSDimitry Andric   if (RHSShuffle) {
1133dff0c46cSDimitry Andric     RHSOp0 = RHSShuffle->getOperand(0);
1134dff0c46cSDimitry Andric     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1135dff0c46cSDimitry Andric   }
1136dff0c46cSDimitry Andric   Value* newLHS = LHS;
1137dff0c46cSDimitry Andric   Value* newRHS = RHS;
1138dff0c46cSDimitry Andric   if (LHSShuffle) {
1139dff0c46cSDimitry Andric     // case 1
1140f22ef01cSRoman Divacky     if (isa<UndefValue>(RHS)) {
1141dff0c46cSDimitry Andric       newLHS = LHSOp0;
1142dff0c46cSDimitry Andric       newRHS = LHSOp1;
1143dff0c46cSDimitry Andric     }
1144dff0c46cSDimitry Andric     // case 2 or 4
1145dff0c46cSDimitry Andric     else if (LHSOp0Width == LHSWidth) {
1146dff0c46cSDimitry Andric       newLHS = LHSOp0;
1147dff0c46cSDimitry Andric     }
1148dff0c46cSDimitry Andric   }
1149dff0c46cSDimitry Andric   // case 3 or 4
1150dff0c46cSDimitry Andric   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1151dff0c46cSDimitry Andric     newRHS = RHSOp0;
1152dff0c46cSDimitry Andric   }
1153dff0c46cSDimitry Andric   // case 4
1154dff0c46cSDimitry Andric   if (LHSOp0 == RHSOp0) {
1155dff0c46cSDimitry Andric     newLHS = LHSOp0;
115691bc56edSDimitry Andric     newRHS = nullptr;
1157dff0c46cSDimitry Andric   }
1158f22ef01cSRoman Divacky 
1159dff0c46cSDimitry Andric   if (newLHS == LHS && newRHS == RHS)
116091bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1161dff0c46cSDimitry Andric 
1162dff0c46cSDimitry Andric   SmallVector<int, 16> LHSMask;
1163dff0c46cSDimitry Andric   SmallVector<int, 16> RHSMask;
1164dff0c46cSDimitry Andric   if (newLHS != LHS)
1165dff0c46cSDimitry Andric     LHSMask = LHSShuffle->getShuffleMask();
1166dff0c46cSDimitry Andric   if (RHSShuffle && newRHS != RHS)
1167dff0c46cSDimitry Andric     RHSMask = RHSShuffle->getShuffleMask();
1168dff0c46cSDimitry Andric 
1169dff0c46cSDimitry Andric   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1170dff0c46cSDimitry Andric   SmallVector<int, 16> newMask;
11712754fe60SDimitry Andric   bool isSplat = true;
1172dff0c46cSDimitry Andric   int SplatElt = -1;
1173dff0c46cSDimitry Andric   // Create a new mask for the new ShuffleVectorInst so that the new
1174dff0c46cSDimitry Andric   // ShuffleVectorInst is equivalent to the original one.
1175dff0c46cSDimitry Andric   for (unsigned i = 0; i < VWidth; ++i) {
1176dff0c46cSDimitry Andric     int eltMask;
1177139f7f9bSDimitry Andric     if (Mask[i] < 0) {
1178dff0c46cSDimitry Andric       // This element is an undef value.
1179dff0c46cSDimitry Andric       eltMask = -1;
1180dff0c46cSDimitry Andric     } else if (Mask[i] < (int)LHSWidth) {
1181dff0c46cSDimitry Andric       // This element is from left hand side vector operand.
1182dff0c46cSDimitry Andric       //
1183dff0c46cSDimitry Andric       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1184dff0c46cSDimitry Andric       // new mask value for the element.
1185dff0c46cSDimitry Andric       if (newLHS != LHS) {
1186dff0c46cSDimitry Andric         eltMask = LHSMask[Mask[i]];
1187dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1188dff0c46cSDimitry Andric         // with a -1 mask value.
1189dff0c46cSDimitry Andric         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1190dff0c46cSDimitry Andric           eltMask = -1;
1191139f7f9bSDimitry Andric       } else
1192dff0c46cSDimitry Andric         eltMask = Mask[i];
1193dff0c46cSDimitry Andric     } else {
1194dff0c46cSDimitry Andric       // This element is from right hand side vector operand
1195dff0c46cSDimitry Andric       //
1196dff0c46cSDimitry Andric       // If the value selected is an undef value, explicitly specify it
1197dff0c46cSDimitry Andric       // with a -1 mask value. (case 1)
1198dff0c46cSDimitry Andric       if (isa<UndefValue>(RHS))
1199dff0c46cSDimitry Andric         eltMask = -1;
1200dff0c46cSDimitry Andric       // If RHS is going to be replaced (case 3 or 4), calculate the
1201dff0c46cSDimitry Andric       // new mask value for the element.
1202dff0c46cSDimitry Andric       else if (newRHS != RHS) {
1203dff0c46cSDimitry Andric         eltMask = RHSMask[Mask[i]-LHSWidth];
1204dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1205dff0c46cSDimitry Andric         // with a -1 mask value.
1206dff0c46cSDimitry Andric         if (eltMask >= (int)RHSOp0Width) {
1207dff0c46cSDimitry Andric           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1208dff0c46cSDimitry Andric                  && "should have been check above");
1209dff0c46cSDimitry Andric           eltMask = -1;
1210dff0c46cSDimitry Andric         }
1211139f7f9bSDimitry Andric       } else
1212dff0c46cSDimitry Andric         eltMask = Mask[i]-LHSWidth;
1213dff0c46cSDimitry Andric 
1214dff0c46cSDimitry Andric       // If LHS's width is changed, shift the mask value accordingly.
1215dff0c46cSDimitry Andric       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
12163861d79fSDimitry Andric       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
12173861d79fSDimitry Andric       // If newRHS == newLHS, we want to remap any references from newRHS to
12183861d79fSDimitry Andric       // newLHS so that we can properly identify splats that may occur due to
121991bc56edSDimitry Andric       // obfuscation across the two vectors.
122091bc56edSDimitry Andric       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1221dff0c46cSDimitry Andric         eltMask += newLHSWidth;
12222754fe60SDimitry Andric     }
1223f22ef01cSRoman Divacky 
1224dff0c46cSDimitry Andric     // Check if this could still be a splat.
1225dff0c46cSDimitry Andric     if (eltMask >= 0) {
1226dff0c46cSDimitry Andric       if (SplatElt >= 0 && SplatElt != eltMask)
1227dff0c46cSDimitry Andric         isSplat = false;
1228dff0c46cSDimitry Andric       SplatElt = eltMask;
1229dff0c46cSDimitry Andric     }
1230dff0c46cSDimitry Andric 
1231dff0c46cSDimitry Andric     newMask.push_back(eltMask);
1232dff0c46cSDimitry Andric   }
1233dff0c46cSDimitry Andric 
1234dff0c46cSDimitry Andric   // If the result mask is equal to one of the original shuffle masks,
1235dff0c46cSDimitry Andric   // or is a splat, do the replacement.
1236dff0c46cSDimitry Andric   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1237dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1238dff0c46cSDimitry Andric     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1239dff0c46cSDimitry Andric       if (newMask[i] < 0) {
12402754fe60SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1241f22ef01cSRoman Divacky       } else {
1242dff0c46cSDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1243f22ef01cSRoman Divacky       }
1244f22ef01cSRoman Divacky     }
124591bc56edSDimitry Andric     if (!newRHS)
1246dff0c46cSDimitry Andric       newRHS = UndefValue::get(newLHS->getType());
1247dff0c46cSDimitry Andric     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1248f22ef01cSRoman Divacky   }
1249f22ef01cSRoman Divacky 
125091bc56edSDimitry Andric   // If the result mask is an identity, replace uses of this instruction with
125191bc56edSDimitry Andric   // corresponding argument.
125291bc56edSDimitry Andric   bool isLHSID, isRHSID;
12537d523365SDimitry Andric   recognizeIdentityMask(newMask, isLHSID, isRHSID);
125491bc56edSDimitry Andric   if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
125591bc56edSDimitry Andric   if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
125691bc56edSDimitry Andric 
125791bc56edSDimitry Andric   return MadeChange ? &SVI : nullptr;
1258f22ef01cSRoman Divacky }
1259