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();
3837d523365SDimitry Andric   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
3847d523365SDimitry Andric                                         ConstantVector::get(ExtendMask));
3857d523365SDimitry Andric 
3864d0b32cdSDimitry Andric   // Insert the new shuffle after the vector operand of the extract is defined
387444ed5c5SDimitry Andric   // (as long as it's not a PHI) or at the start of the basic block of the
388444ed5c5SDimitry Andric   // extract, so any subsequent extracts in the same basic block can use it.
389444ed5c5SDimitry Andric   // TODO: Insert before the earliest ExtractElementInst that is replaced.
390444ed5c5SDimitry Andric   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
391444ed5c5SDimitry Andric   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
3924d0b32cdSDimitry Andric     WideVec->insertAfter(ExtVecOpInst);
393444ed5c5SDimitry Andric   else
3944d0b32cdSDimitry Andric     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
3954d0b32cdSDimitry Andric 
3964d0b32cdSDimitry Andric   // Replace extracts from the original narrow vector with extracts from the new
3974d0b32cdSDimitry Andric   // wide vector.
3987d523365SDimitry Andric   for (User *U : ExtVecOp->users()) {
3994d0b32cdSDimitry Andric     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
400444ed5c5SDimitry Andric     if (!OldExt || OldExt->getParent() != WideVec->getParent())
4014d0b32cdSDimitry Andric       continue;
4027d523365SDimitry Andric     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
4037d523365SDimitry Andric     NewExt->insertAfter(WideVec);
4047d523365SDimitry Andric     IC.ReplaceInstUsesWith(*OldExt, NewExt);
4057d523365SDimitry Andric   }
4067d523365SDimitry Andric }
40791bc56edSDimitry Andric 
40891bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement,
40991bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or
41091bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the
41191bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask
41291bc56edSDimitry Andric /// parameter as required.
41391bc56edSDimitry Andric ///
41491bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have
41591bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target.
41691bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps;
41791bc56edSDimitry Andric 
4187d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V,
41991bc56edSDimitry Andric                                          SmallVectorImpl<Constant *> &Mask,
4207d523365SDimitry Andric                                          Value *PermittedRHS,
4217d523365SDimitry Andric                                          InstCombiner &IC) {
42291bc56edSDimitry Andric   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
423f22ef01cSRoman Divacky   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
424f22ef01cSRoman Divacky 
425f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
426f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
42791bc56edSDimitry Andric     return std::make_pair(
42891bc56edSDimitry Andric         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
429dff0c46cSDimitry Andric   }
430dff0c46cSDimitry Andric 
431dff0c46cSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
432f22ef01cSRoman Divacky     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
43391bc56edSDimitry Andric     return std::make_pair(V, nullptr);
434dff0c46cSDimitry Andric   }
435dff0c46cSDimitry Andric 
436dff0c46cSDimitry Andric   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
437f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
438f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
439f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
440f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
441f22ef01cSRoman Divacky 
442f22ef01cSRoman Divacky     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
44391bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
444f22ef01cSRoman Divacky         unsigned ExtractedIdx =
445f22ef01cSRoman Divacky           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
446f22ef01cSRoman Divacky         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
447f22ef01cSRoman Divacky 
448f22ef01cSRoman Divacky         // Either the extracted from or inserted into vector must be RHSVec,
449f22ef01cSRoman Divacky         // otherwise we'd end up with a shuffle of three inputs.
45091bc56edSDimitry Andric         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
45191bc56edSDimitry Andric           Value *RHS = EI->getOperand(0);
4527d523365SDimitry Andric           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
45391bc56edSDimitry Andric           assert(LR.second == nullptr || LR.second == RHS);
45491bc56edSDimitry Andric 
45591bc56edSDimitry Andric           if (LR.first->getType() != RHS->getType()) {
4567d523365SDimitry Andric             // Although we are giving up for now, see if we can create extracts
4577d523365SDimitry Andric             // that match the inserts for another round of combining.
4587d523365SDimitry Andric             replaceExtractElements(IEI, EI, IC);
4597d523365SDimitry Andric 
46091bc56edSDimitry Andric             // We tried our best, but we can't find anything compatible with RHS
46191bc56edSDimitry Andric             // further up the chain. Return a trivial shuffle.
46291bc56edSDimitry Andric             for (unsigned i = 0; i < NumElts; ++i)
46391bc56edSDimitry Andric               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
46491bc56edSDimitry Andric             return std::make_pair(V, nullptr);
46591bc56edSDimitry Andric           }
46691bc56edSDimitry Andric 
46791bc56edSDimitry Andric           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
468f22ef01cSRoman Divacky           Mask[InsertedIdx % NumElts] =
469f22ef01cSRoman Divacky             ConstantInt::get(Type::getInt32Ty(V->getContext()),
47091bc56edSDimitry Andric                              NumLHSElts+ExtractedIdx);
47191bc56edSDimitry Andric           return std::make_pair(LR.first, RHS);
472f22ef01cSRoman Divacky         }
473f22ef01cSRoman Divacky 
47491bc56edSDimitry Andric         if (VecOp == PermittedRHS) {
47591bc56edSDimitry Andric           // We've gone as far as we can: anything on the other side of the
47691bc56edSDimitry Andric           // extractelement will already have been converted into a shuffle.
47791bc56edSDimitry Andric           unsigned NumLHSElts =
47891bc56edSDimitry Andric               EI->getOperand(0)->getType()->getVectorNumElements();
47991bc56edSDimitry Andric           for (unsigned i = 0; i != NumElts; ++i)
48091bc56edSDimitry Andric             Mask.push_back(ConstantInt::get(
48191bc56edSDimitry Andric                 Type::getInt32Ty(V->getContext()),
48291bc56edSDimitry Andric                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
48391bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
484f22ef01cSRoman Divacky         }
485f22ef01cSRoman Divacky 
486f22ef01cSRoman Divacky         // If this insertelement is a chain that comes from exactly these two
487f22ef01cSRoman Divacky         // vectors, return the vector and the effective shuffle.
48891bc56edSDimitry Andric         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
4897d523365SDimitry Andric             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
49091bc56edSDimitry Andric                                          Mask))
49191bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
492f22ef01cSRoman Divacky       }
493f22ef01cSRoman Divacky     }
494f22ef01cSRoman Divacky   }
495f22ef01cSRoman Divacky 
4967d523365SDimitry Andric   // Otherwise, we can't do anything fancy. Return an identity vector.
497f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumElts; ++i)
498f22ef01cSRoman Divacky     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
49991bc56edSDimitry Andric   return std::make_pair(V, nullptr);
50091bc56edSDimitry Andric }
50191bc56edSDimitry Andric 
50291bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones:
50391bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
50491bc56edSDimitry Andric ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
50591bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the
50691bc56edSDimitry Andric /// first one, making the first one redundant.
50791bc56edSDimitry Andric /// It should be transformed to:
50891bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
50991bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
51091bc56edSDimitry Andric   bool IsRedundant = false;
51191bc56edSDimitry Andric   ArrayRef<unsigned int> FirstIndices = I.getIndices();
51291bc56edSDimitry Andric 
51391bc56edSDimitry Andric   // If there is a chain of insertvalue instructions (each of them except the
51491bc56edSDimitry Andric   // last one has only one use and it's another insertvalue insn from this
51591bc56edSDimitry Andric   // chain), check if any of the 'children' uses the same indices as the first
51691bc56edSDimitry Andric   // instruction. In this case, the first one is redundant.
51791bc56edSDimitry Andric   Value *V = &I;
51891bc56edSDimitry Andric   unsigned Depth = 0;
51991bc56edSDimitry Andric   while (V->hasOneUse() && Depth < 10) {
52091bc56edSDimitry Andric     User *U = V->user_back();
52191bc56edSDimitry Andric     auto UserInsInst = dyn_cast<InsertValueInst>(U);
52291bc56edSDimitry Andric     if (!UserInsInst || U->getOperand(0) != V)
52391bc56edSDimitry Andric       break;
52491bc56edSDimitry Andric     if (UserInsInst->getIndices() == FirstIndices) {
52591bc56edSDimitry Andric       IsRedundant = true;
52691bc56edSDimitry Andric       break;
52791bc56edSDimitry Andric     }
52891bc56edSDimitry Andric     V = UserInsInst;
52991bc56edSDimitry Andric     Depth++;
53091bc56edSDimitry Andric   }
53191bc56edSDimitry Andric 
53291bc56edSDimitry Andric   if (IsRedundant)
53391bc56edSDimitry Andric     return ReplaceInstUsesWith(I, I.getOperand(0));
53491bc56edSDimitry Andric   return nullptr;
535f22ef01cSRoman Divacky }
536f22ef01cSRoman Divacky 
537f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
538f22ef01cSRoman Divacky   Value *VecOp    = IE.getOperand(0);
539f22ef01cSRoman Divacky   Value *ScalarOp = IE.getOperand(1);
540f22ef01cSRoman Divacky   Value *IdxOp    = IE.getOperand(2);
541f22ef01cSRoman Divacky 
542f22ef01cSRoman Divacky   // Inserting an undef or into an undefined place, remove this.
543f22ef01cSRoman Divacky   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
544f22ef01cSRoman Divacky     ReplaceInstUsesWith(IE, VecOp);
545f22ef01cSRoman Divacky 
546f22ef01cSRoman Divacky   // If the inserted element was extracted from some other vector, and if the
547f22ef01cSRoman Divacky   // indexes are constant, try to turn this into a shufflevector operation.
548f22ef01cSRoman Divacky   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
54991bc56edSDimitry Andric     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
55091bc56edSDimitry Andric       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
55191bc56edSDimitry Andric       unsigned NumExtractVectorElts =
55291bc56edSDimitry Andric           EI->getOperand(0)->getType()->getVectorNumElements();
553f22ef01cSRoman Divacky       unsigned ExtractedIdx =
554f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
555f22ef01cSRoman Divacky       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
556f22ef01cSRoman Divacky 
55791bc56edSDimitry Andric       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
558f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
559f22ef01cSRoman Divacky 
56091bc56edSDimitry Andric       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
561f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
562f22ef01cSRoman Divacky 
563f22ef01cSRoman Divacky       // If we are extracting a value from a vector, then inserting it right
564f22ef01cSRoman Divacky       // back into the same place, just use the input vector.
565f22ef01cSRoman Divacky       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
566f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
567f22ef01cSRoman Divacky 
568f22ef01cSRoman Divacky       // If this insertelement isn't used by some other insertelement, turn it
569f22ef01cSRoman Divacky       // (and any insertelements it points to), into one big shuffle.
57091bc56edSDimitry Andric       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
571dff0c46cSDimitry Andric         SmallVector<Constant*, 16> Mask;
5727d523365SDimitry Andric         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
57391bc56edSDimitry Andric 
57491bc56edSDimitry Andric         // The proposed shuffle may be trivial, in which case we shouldn't
57591bc56edSDimitry Andric         // perform the combine.
57691bc56edSDimitry Andric         if (LR.first != &IE && LR.second != &IE) {
577f22ef01cSRoman Divacky           // We now have a shuffle of LHS, RHS, Mask.
57891bc56edSDimitry Andric           if (LR.second == nullptr)
57991bc56edSDimitry Andric             LR.second = UndefValue::get(LR.first->getType());
58091bc56edSDimitry Andric           return new ShuffleVectorInst(LR.first, LR.second,
58191bc56edSDimitry Andric                                        ConstantVector::get(Mask));
58291bc56edSDimitry Andric         }
583f22ef01cSRoman Divacky       }
584f22ef01cSRoman Divacky     }
585f22ef01cSRoman Divacky   }
586f22ef01cSRoman Divacky 
587f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
588f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
589f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
5902754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
5912754fe60SDimitry Andric     if (V != &IE)
5922754fe60SDimitry Andric       return ReplaceInstUsesWith(IE, V);
593f22ef01cSRoman Divacky     return &IE;
5942754fe60SDimitry Andric   }
595f22ef01cSRoman Divacky 
59691bc56edSDimitry Andric   return nullptr;
597f22ef01cSRoman Divacky }
598f22ef01cSRoman Divacky 
599f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector
600f785676fSDimitry Andric /// elements were shuffled in a different order.
601f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
602f785676fSDimitry Andric                                 unsigned Depth = 5) {
603f785676fSDimitry Andric   // We can always reorder the elements of a constant.
604f785676fSDimitry Andric   if (isa<Constant>(V))
605f785676fSDimitry Andric     return true;
606f785676fSDimitry Andric 
607f785676fSDimitry Andric   // We won't reorder vector arguments. No IPO here.
608f785676fSDimitry Andric   Instruction *I = dyn_cast<Instruction>(V);
609f785676fSDimitry Andric   if (!I) return false;
610f785676fSDimitry Andric 
611f785676fSDimitry Andric   // Two users may expect different orders of the elements. Don't try it.
612f785676fSDimitry Andric   if (!I->hasOneUse())
613f785676fSDimitry Andric     return false;
614f785676fSDimitry Andric 
615f785676fSDimitry Andric   if (Depth == 0) return false;
616f785676fSDimitry Andric 
617f785676fSDimitry Andric   switch (I->getOpcode()) {
618f785676fSDimitry Andric     case Instruction::Add:
619f785676fSDimitry Andric     case Instruction::FAdd:
620f785676fSDimitry Andric     case Instruction::Sub:
621f785676fSDimitry Andric     case Instruction::FSub:
622f785676fSDimitry Andric     case Instruction::Mul:
623f785676fSDimitry Andric     case Instruction::FMul:
624f785676fSDimitry Andric     case Instruction::UDiv:
625f785676fSDimitry Andric     case Instruction::SDiv:
626f785676fSDimitry Andric     case Instruction::FDiv:
627f785676fSDimitry Andric     case Instruction::URem:
628f785676fSDimitry Andric     case Instruction::SRem:
629f785676fSDimitry Andric     case Instruction::FRem:
630f785676fSDimitry Andric     case Instruction::Shl:
631f785676fSDimitry Andric     case Instruction::LShr:
632f785676fSDimitry Andric     case Instruction::AShr:
633f785676fSDimitry Andric     case Instruction::And:
634f785676fSDimitry Andric     case Instruction::Or:
635f785676fSDimitry Andric     case Instruction::Xor:
636f785676fSDimitry Andric     case Instruction::ICmp:
637f785676fSDimitry Andric     case Instruction::FCmp:
638f785676fSDimitry Andric     case Instruction::Trunc:
639f785676fSDimitry Andric     case Instruction::ZExt:
640f785676fSDimitry Andric     case Instruction::SExt:
641f785676fSDimitry Andric     case Instruction::FPToUI:
642f785676fSDimitry Andric     case Instruction::FPToSI:
643f785676fSDimitry Andric     case Instruction::UIToFP:
644f785676fSDimitry Andric     case Instruction::SIToFP:
645f785676fSDimitry Andric     case Instruction::FPTrunc:
646f785676fSDimitry Andric     case Instruction::FPExt:
647f785676fSDimitry Andric     case Instruction::GetElementPtr: {
6487d523365SDimitry Andric       for (Value *Operand : I->operands()) {
6497d523365SDimitry Andric         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
650f785676fSDimitry Andric           return false;
651f785676fSDimitry Andric       }
652f785676fSDimitry Andric       return true;
653f785676fSDimitry Andric     }
654f785676fSDimitry Andric     case Instruction::InsertElement: {
655f785676fSDimitry Andric       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
656f785676fSDimitry Andric       if (!CI) return false;
657f785676fSDimitry Andric       int ElementNumber = CI->getLimitedValue();
658f785676fSDimitry Andric 
659f785676fSDimitry Andric       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
660f785676fSDimitry Andric       // can't put an element into multiple indices.
661f785676fSDimitry Andric       bool SeenOnce = false;
662f785676fSDimitry Andric       for (int i = 0, e = Mask.size(); i != e; ++i) {
663f785676fSDimitry Andric         if (Mask[i] == ElementNumber) {
664f785676fSDimitry Andric           if (SeenOnce)
665f785676fSDimitry Andric             return false;
666f785676fSDimitry Andric           SeenOnce = true;
667f785676fSDimitry Andric         }
668f785676fSDimitry Andric       }
669f785676fSDimitry Andric       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
670f785676fSDimitry Andric     }
671f785676fSDimitry Andric   }
672f785676fSDimitry Andric   return false;
673f785676fSDimitry Andric }
674f785676fSDimitry Andric 
675f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given.
676f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct.
6777d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
678f785676fSDimitry Andric   // We don't want to use the IRBuilder here because we want the replacement
679f785676fSDimitry Andric   // instructions to appear next to 'I', not the builder's insertion point.
680f785676fSDimitry Andric   switch (I->getOpcode()) {
681f785676fSDimitry Andric     case Instruction::Add:
682f785676fSDimitry Andric     case Instruction::FAdd:
683f785676fSDimitry Andric     case Instruction::Sub:
684f785676fSDimitry Andric     case Instruction::FSub:
685f785676fSDimitry Andric     case Instruction::Mul:
686f785676fSDimitry Andric     case Instruction::FMul:
687f785676fSDimitry Andric     case Instruction::UDiv:
688f785676fSDimitry Andric     case Instruction::SDiv:
689f785676fSDimitry Andric     case Instruction::FDiv:
690f785676fSDimitry Andric     case Instruction::URem:
691f785676fSDimitry Andric     case Instruction::SRem:
692f785676fSDimitry Andric     case Instruction::FRem:
693f785676fSDimitry Andric     case Instruction::Shl:
694f785676fSDimitry Andric     case Instruction::LShr:
695f785676fSDimitry Andric     case Instruction::AShr:
696f785676fSDimitry Andric     case Instruction::And:
697f785676fSDimitry Andric     case Instruction::Or:
698f785676fSDimitry Andric     case Instruction::Xor: {
699f785676fSDimitry Andric       BinaryOperator *BO = cast<BinaryOperator>(I);
700f785676fSDimitry Andric       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
701f785676fSDimitry Andric       BinaryOperator *New =
702f785676fSDimitry Andric           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
703f785676fSDimitry Andric                                  NewOps[0], NewOps[1], "", BO);
704f785676fSDimitry Andric       if (isa<OverflowingBinaryOperator>(BO)) {
705f785676fSDimitry Andric         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
706f785676fSDimitry Andric         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
707f785676fSDimitry Andric       }
708f785676fSDimitry Andric       if (isa<PossiblyExactOperator>(BO)) {
709f785676fSDimitry Andric         New->setIsExact(BO->isExact());
710f785676fSDimitry Andric       }
71191bc56edSDimitry Andric       if (isa<FPMathOperator>(BO))
71291bc56edSDimitry Andric         New->copyFastMathFlags(I);
713f785676fSDimitry Andric       return New;
714f785676fSDimitry Andric     }
715f785676fSDimitry Andric     case Instruction::ICmp:
716f785676fSDimitry Andric       assert(NewOps.size() == 2 && "icmp with #ops != 2");
717f785676fSDimitry Andric       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
718f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
719f785676fSDimitry Andric     case Instruction::FCmp:
720f785676fSDimitry Andric       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
721f785676fSDimitry Andric       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
722f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
723f785676fSDimitry Andric     case Instruction::Trunc:
724f785676fSDimitry Andric     case Instruction::ZExt:
725f785676fSDimitry Andric     case Instruction::SExt:
726f785676fSDimitry Andric     case Instruction::FPToUI:
727f785676fSDimitry Andric     case Instruction::FPToSI:
728f785676fSDimitry Andric     case Instruction::UIToFP:
729f785676fSDimitry Andric     case Instruction::SIToFP:
730f785676fSDimitry Andric     case Instruction::FPTrunc:
731f785676fSDimitry Andric     case Instruction::FPExt: {
732f785676fSDimitry Andric       // It's possible that the mask has a different number of elements from
733f785676fSDimitry Andric       // the original cast. We recompute the destination type to match the mask.
734f785676fSDimitry Andric       Type *DestTy =
735f785676fSDimitry Andric           VectorType::get(I->getType()->getScalarType(),
736f785676fSDimitry Andric                           NewOps[0]->getType()->getVectorNumElements());
737f785676fSDimitry Andric       assert(NewOps.size() == 1 && "cast with #ops != 1");
738f785676fSDimitry Andric       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
739f785676fSDimitry Andric                               "", I);
740f785676fSDimitry Andric     }
741f785676fSDimitry Andric     case Instruction::GetElementPtr: {
742f785676fSDimitry Andric       Value *Ptr = NewOps[0];
743f785676fSDimitry Andric       ArrayRef<Value*> Idx = NewOps.slice(1);
744ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
745ff0cc061SDimitry Andric           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
746f785676fSDimitry Andric       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
747f785676fSDimitry Andric       return GEP;
748f785676fSDimitry Andric     }
749f785676fSDimitry Andric   }
750f785676fSDimitry Andric   llvm_unreachable("failed to rebuild vector instructions");
751f785676fSDimitry Andric }
752f785676fSDimitry Andric 
753f785676fSDimitry Andric Value *
754f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
755f785676fSDimitry Andric   // Mask.size() does not need to be equal to the number of vector elements.
756f785676fSDimitry Andric 
757f785676fSDimitry Andric   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
758f785676fSDimitry Andric   if (isa<UndefValue>(V)) {
759f785676fSDimitry Andric     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
760f785676fSDimitry Andric                                            Mask.size()));
761f785676fSDimitry Andric   }
762f785676fSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
763f785676fSDimitry Andric     return ConstantAggregateZero::get(
764f785676fSDimitry Andric                VectorType::get(V->getType()->getScalarType(),
765f785676fSDimitry Andric                                Mask.size()));
766f785676fSDimitry Andric   }
767f785676fSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
768f785676fSDimitry Andric     SmallVector<Constant *, 16> MaskValues;
769f785676fSDimitry Andric     for (int i = 0, e = Mask.size(); i != e; ++i) {
770f785676fSDimitry Andric       if (Mask[i] == -1)
771f785676fSDimitry Andric         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
772f785676fSDimitry Andric       else
773f785676fSDimitry Andric         MaskValues.push_back(Builder->getInt32(Mask[i]));
774f785676fSDimitry Andric     }
775f785676fSDimitry Andric     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
776f785676fSDimitry Andric                                           ConstantVector::get(MaskValues));
777f785676fSDimitry Andric   }
778f785676fSDimitry Andric 
779f785676fSDimitry Andric   Instruction *I = cast<Instruction>(V);
780f785676fSDimitry Andric   switch (I->getOpcode()) {
781f785676fSDimitry Andric     case Instruction::Add:
782f785676fSDimitry Andric     case Instruction::FAdd:
783f785676fSDimitry Andric     case Instruction::Sub:
784f785676fSDimitry Andric     case Instruction::FSub:
785f785676fSDimitry Andric     case Instruction::Mul:
786f785676fSDimitry Andric     case Instruction::FMul:
787f785676fSDimitry Andric     case Instruction::UDiv:
788f785676fSDimitry Andric     case Instruction::SDiv:
789f785676fSDimitry Andric     case Instruction::FDiv:
790f785676fSDimitry Andric     case Instruction::URem:
791f785676fSDimitry Andric     case Instruction::SRem:
792f785676fSDimitry Andric     case Instruction::FRem:
793f785676fSDimitry Andric     case Instruction::Shl:
794f785676fSDimitry Andric     case Instruction::LShr:
795f785676fSDimitry Andric     case Instruction::AShr:
796f785676fSDimitry Andric     case Instruction::And:
797f785676fSDimitry Andric     case Instruction::Or:
798f785676fSDimitry Andric     case Instruction::Xor:
799f785676fSDimitry Andric     case Instruction::ICmp:
800f785676fSDimitry Andric     case Instruction::FCmp:
801f785676fSDimitry Andric     case Instruction::Trunc:
802f785676fSDimitry Andric     case Instruction::ZExt:
803f785676fSDimitry Andric     case Instruction::SExt:
804f785676fSDimitry Andric     case Instruction::FPToUI:
805f785676fSDimitry Andric     case Instruction::FPToSI:
806f785676fSDimitry Andric     case Instruction::UIToFP:
807f785676fSDimitry Andric     case Instruction::SIToFP:
808f785676fSDimitry Andric     case Instruction::FPTrunc:
809f785676fSDimitry Andric     case Instruction::FPExt:
810f785676fSDimitry Andric     case Instruction::Select:
811f785676fSDimitry Andric     case Instruction::GetElementPtr: {
812f785676fSDimitry Andric       SmallVector<Value*, 8> NewOps;
813f785676fSDimitry Andric       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
814f785676fSDimitry Andric       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
815f785676fSDimitry Andric         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
816f785676fSDimitry Andric         NewOps.push_back(V);
817f785676fSDimitry Andric         NeedsRebuild |= (V != I->getOperand(i));
818f785676fSDimitry Andric       }
819f785676fSDimitry Andric       if (NeedsRebuild) {
8207d523365SDimitry Andric         return buildNew(I, NewOps);
821f785676fSDimitry Andric       }
822f785676fSDimitry Andric       return I;
823f785676fSDimitry Andric     }
824f785676fSDimitry Andric     case Instruction::InsertElement: {
825f785676fSDimitry Andric       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
826f785676fSDimitry Andric 
827f785676fSDimitry Andric       // The insertelement was inserting at Element. Figure out which element
828f785676fSDimitry Andric       // that becomes after shuffling. The answer is guaranteed to be unique
829f785676fSDimitry Andric       // by CanEvaluateShuffled.
830f785676fSDimitry Andric       bool Found = false;
831f785676fSDimitry Andric       int Index = 0;
832f785676fSDimitry Andric       for (int e = Mask.size(); Index != e; ++Index) {
833f785676fSDimitry Andric         if (Mask[Index] == Element) {
834f785676fSDimitry Andric           Found = true;
835f785676fSDimitry Andric           break;
836f785676fSDimitry Andric         }
837f785676fSDimitry Andric       }
838f785676fSDimitry Andric 
83991bc56edSDimitry Andric       // If element is not in Mask, no need to handle the operand 1 (element to
84091bc56edSDimitry Andric       // be inserted). Just evaluate values in operand 0 according to Mask.
841f785676fSDimitry Andric       if (!Found)
84291bc56edSDimitry Andric         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
843f785676fSDimitry Andric 
844f785676fSDimitry Andric       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
845f785676fSDimitry Andric       return InsertElementInst::Create(V, I->getOperand(1),
846f785676fSDimitry Andric                                        Builder->getInt32(Index), "", I);
847f785676fSDimitry Andric     }
848f785676fSDimitry Andric   }
849f785676fSDimitry Andric   llvm_unreachable("failed to reorder elements of vector instruction!");
850f785676fSDimitry Andric }
851f22ef01cSRoman Divacky 
8527d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
85391bc56edSDimitry Andric                                   bool &isLHSID, bool &isRHSID) {
85491bc56edSDimitry Andric   isLHSID = isRHSID = true;
85591bc56edSDimitry Andric 
85691bc56edSDimitry Andric   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
85791bc56edSDimitry Andric     if (Mask[i] < 0) continue;  // Ignore undef values.
85891bc56edSDimitry Andric     // Is this an identity shuffle of the LHS value?
85991bc56edSDimitry Andric     isLHSID &= (Mask[i] == (int)i);
86091bc56edSDimitry Andric 
86191bc56edSDimitry Andric     // Is this an identity shuffle of the RHS value?
86291bc56edSDimitry Andric     isRHSID &= (Mask[i]-e == i);
86391bc56edSDimitry Andric   }
86491bc56edSDimitry Andric }
86591bc56edSDimitry Andric 
866ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from
867ff0cc061SDimitry Andric // LHS, for example:
868ff0cc061SDimitry Andric //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
869ff0cc061SDimitry Andric //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
870ff0cc061SDimitry Andric //   Shuffles to:  |EE|FF|GG|HH|
871ff0cc061SDimitry Andric //                 +--+--+--+--+
872ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
873ff0cc061SDimitry Andric                                        SmallVector<int, 16> &Mask) {
874ff0cc061SDimitry Andric   unsigned LHSElems =
875ff0cc061SDimitry Andric       cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
876ff0cc061SDimitry Andric   unsigned MaskElems = Mask.size();
877ff0cc061SDimitry Andric   unsigned BegIdx = Mask.front();
878ff0cc061SDimitry Andric   unsigned EndIdx = Mask.back();
879ff0cc061SDimitry Andric   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
880ff0cc061SDimitry Andric     return false;
881ff0cc061SDimitry Andric   for (unsigned I = 0; I != MaskElems; ++I)
882ff0cc061SDimitry Andric     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
883ff0cc061SDimitry Andric       return false;
884ff0cc061SDimitry Andric   return true;
885ff0cc061SDimitry Andric }
886ff0cc061SDimitry Andric 
887f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
888f22ef01cSRoman Divacky   Value *LHS = SVI.getOperand(0);
889f22ef01cSRoman Divacky   Value *RHS = SVI.getOperand(1);
890dff0c46cSDimitry Andric   SmallVector<int, 16> Mask = SVI.getShuffleMask();
891ff0cc061SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
892f22ef01cSRoman Divacky 
893f22ef01cSRoman Divacky   bool MadeChange = false;
894f22ef01cSRoman Divacky 
895f22ef01cSRoman Divacky   // Undefined shuffle mask -> undefined value.
896f22ef01cSRoman Divacky   if (isa<UndefValue>(SVI.getOperand(2)))
897f22ef01cSRoman Divacky     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
898f22ef01cSRoman Divacky 
899f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
900f22ef01cSRoman Divacky 
901f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
902f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
9032754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
9042754fe60SDimitry Andric     if (V != &SVI)
9052754fe60SDimitry Andric       return ReplaceInstUsesWith(SVI, V);
906f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
907f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
908f22ef01cSRoman Divacky     MadeChange = true;
909f22ef01cSRoman Divacky   }
910f22ef01cSRoman Divacky 
911dff0c46cSDimitry Andric   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
912dff0c46cSDimitry Andric 
913f22ef01cSRoman Divacky   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
914f22ef01cSRoman Divacky   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
915f22ef01cSRoman Divacky   if (LHS == RHS || isa<UndefValue>(LHS)) {
916f22ef01cSRoman Divacky     if (isa<UndefValue>(LHS) && LHS == RHS) {
917f22ef01cSRoman Divacky       // shuffle(undef,undef,mask) -> undef.
918f785676fSDimitry Andric       Value *Result = (VWidth == LHSWidth)
919dff0c46cSDimitry Andric                       ? LHS : UndefValue::get(SVI.getType());
920f785676fSDimitry Andric       return ReplaceInstUsesWith(SVI, Result);
921f22ef01cSRoman Divacky     }
922f22ef01cSRoman Divacky 
923f22ef01cSRoman Divacky     // Remap any references to RHS to use LHS.
924dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
925dff0c46cSDimitry Andric     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
926dff0c46cSDimitry Andric       if (Mask[i] < 0) {
927ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
928dff0c46cSDimitry Andric         continue;
929dff0c46cSDimitry Andric       }
930dff0c46cSDimitry Andric 
9312754fe60SDimitry Andric       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
9322754fe60SDimitry Andric           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
9332754fe60SDimitry Andric         Mask[i] = -1;     // Turn into undef.
934ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
935f22ef01cSRoman Divacky       } else {
936f22ef01cSRoman Divacky         Mask[i] = Mask[i] % e;  // Force to LHS.
937ff0cc061SDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
938f22ef01cSRoman Divacky       }
939f22ef01cSRoman Divacky     }
940f22ef01cSRoman Divacky     SVI.setOperand(0, SVI.getOperand(1));
941f22ef01cSRoman Divacky     SVI.setOperand(1, UndefValue::get(RHS->getType()));
942f22ef01cSRoman Divacky     SVI.setOperand(2, ConstantVector::get(Elts));
943f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
944f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
945f22ef01cSRoman Divacky     MadeChange = true;
946f22ef01cSRoman Divacky   }
947f22ef01cSRoman Divacky 
948dff0c46cSDimitry Andric   if (VWidth == LHSWidth) {
949f22ef01cSRoman Divacky     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
95091bc56edSDimitry Andric     bool isLHSID, isRHSID;
9517d523365SDimitry Andric     recognizeIdentityMask(Mask, isLHSID, isRHSID);
952f22ef01cSRoman Divacky 
953f22ef01cSRoman Divacky     // Eliminate identity shuffles.
954f22ef01cSRoman Divacky     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
955f22ef01cSRoman Divacky     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
956dff0c46cSDimitry Andric   }
957f22ef01cSRoman Divacky 
958f785676fSDimitry Andric   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
959f785676fSDimitry Andric     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
960f785676fSDimitry Andric     return ReplaceInstUsesWith(SVI, V);
961f785676fSDimitry Andric   }
962f785676fSDimitry Andric 
963ff0cc061SDimitry Andric   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
964ff0cc061SDimitry Andric   // a non-vector type. We can instead bitcast the original vector followed by
965ff0cc061SDimitry Andric   // an extract of the desired element:
966ff0cc061SDimitry Andric   //
967ff0cc061SDimitry Andric   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
968ff0cc061SDimitry Andric   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
969ff0cc061SDimitry Andric   //   %1 = bitcast <4 x i8> %sroa to i32
970ff0cc061SDimitry Andric   // Becomes:
971ff0cc061SDimitry Andric   //   %bc = bitcast <16 x i8> %in to <4 x i32>
972ff0cc061SDimitry Andric   //   %ext = extractelement <4 x i32> %bc, i32 0
973ff0cc061SDimitry Andric   //
974ff0cc061SDimitry Andric   // If the shuffle is extracting a contiguous range of values from the input
975ff0cc061SDimitry Andric   // vector then each use which is a bitcast of the extracted size can be
976ff0cc061SDimitry Andric   // replaced. This will work if the vector types are compatible, and the begin
977ff0cc061SDimitry Andric   // index is aligned to a value in the casted vector type. If the begin index
978ff0cc061SDimitry Andric   // isn't aligned then we can shuffle the original vector (keeping the same
979ff0cc061SDimitry Andric   // vector type) before extracting.
980ff0cc061SDimitry Andric   //
981ff0cc061SDimitry Andric   // This code will bail out if the target type is fundamentally incompatible
982ff0cc061SDimitry Andric   // with vectors of the source type.
983ff0cc061SDimitry Andric   //
984ff0cc061SDimitry Andric   // Example of <16 x i8>, target type i32:
985ff0cc061SDimitry Andric   // Index range [4,8):         v-----------v Will work.
986ff0cc061SDimitry Andric   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
987ff0cc061SDimitry Andric   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
988ff0cc061SDimitry Andric   //     <4 x i32>: |           |           |           |           |
989ff0cc061SDimitry Andric   //                +-----------+-----------+-----------+-----------+
990ff0cc061SDimitry Andric   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
991ff0cc061SDimitry Andric   // Target type i40:           ^--------------^ Won't work, bail.
992ff0cc061SDimitry Andric   if (isShuffleExtractingFromLHS(SVI, Mask)) {
993ff0cc061SDimitry Andric     Value *V = LHS;
994ff0cc061SDimitry Andric     unsigned MaskElems = Mask.size();
995ff0cc061SDimitry Andric     unsigned BegIdx = Mask.front();
996ff0cc061SDimitry Andric     VectorType *SrcTy = cast<VectorType>(V->getType());
997ff0cc061SDimitry Andric     unsigned VecBitWidth = SrcTy->getBitWidth();
998ff0cc061SDimitry Andric     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
999ff0cc061SDimitry Andric     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1000ff0cc061SDimitry Andric     unsigned SrcNumElems = SrcTy->getNumElements();
1001ff0cc061SDimitry Andric     SmallVector<BitCastInst *, 8> BCs;
1002ff0cc061SDimitry Andric     DenseMap<Type *, Value *> NewBCs;
1003ff0cc061SDimitry Andric     for (User *U : SVI.users())
1004ff0cc061SDimitry Andric       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1005ff0cc061SDimitry Andric         if (!BC->use_empty())
1006ff0cc061SDimitry Andric           // Only visit bitcasts that weren't previously handled.
1007ff0cc061SDimitry Andric           BCs.push_back(BC);
1008ff0cc061SDimitry Andric     for (BitCastInst *BC : BCs) {
1009ff0cc061SDimitry Andric       Type *TgtTy = BC->getDestTy();
1010ff0cc061SDimitry Andric       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1011ff0cc061SDimitry Andric       if (!TgtElemBitWidth)
1012ff0cc061SDimitry Andric         continue;
1013ff0cc061SDimitry Andric       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1014ff0cc061SDimitry Andric       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1015ff0cc061SDimitry Andric       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1016ff0cc061SDimitry Andric       if (!VecBitWidthsEqual)
1017ff0cc061SDimitry Andric         continue;
1018ff0cc061SDimitry Andric       if (!VectorType::isValidElementType(TgtTy))
1019ff0cc061SDimitry Andric         continue;
1020ff0cc061SDimitry Andric       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1021ff0cc061SDimitry Andric       if (!BegIsAligned) {
1022ff0cc061SDimitry Andric         // Shuffle the input so [0,NumElements) contains the output, and
1023ff0cc061SDimitry Andric         // [NumElems,SrcNumElems) is undef.
1024ff0cc061SDimitry Andric         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1025ff0cc061SDimitry Andric                                                 UndefValue::get(Int32Ty));
1026ff0cc061SDimitry Andric         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1027ff0cc061SDimitry Andric           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1028ff0cc061SDimitry Andric         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1029ff0cc061SDimitry Andric                                          ConstantVector::get(ShuffleMask),
1030ff0cc061SDimitry Andric                                          SVI.getName() + ".extract");
1031ff0cc061SDimitry Andric         BegIdx = 0;
1032ff0cc061SDimitry Andric       }
1033ff0cc061SDimitry Andric       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1034ff0cc061SDimitry Andric       assert(SrcElemsPerTgtElem);
1035ff0cc061SDimitry Andric       BegIdx /= SrcElemsPerTgtElem;
1036ff0cc061SDimitry Andric       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1037ff0cc061SDimitry Andric       auto *NewBC =
1038ff0cc061SDimitry Andric           BCAlreadyExists
1039ff0cc061SDimitry Andric               ? NewBCs[CastSrcTy]
1040ff0cc061SDimitry Andric               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1041ff0cc061SDimitry Andric       if (!BCAlreadyExists)
1042ff0cc061SDimitry Andric         NewBCs[CastSrcTy] = NewBC;
1043ff0cc061SDimitry Andric       auto *Ext = Builder->CreateExtractElement(
1044ff0cc061SDimitry Andric           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1045ff0cc061SDimitry Andric       // The shufflevector isn't being replaced: the bitcast that used it
1046ff0cc061SDimitry Andric       // is. InstCombine will visit the newly-created instructions.
1047ff0cc061SDimitry Andric       ReplaceInstUsesWith(*BC, Ext);
1048ff0cc061SDimitry Andric       MadeChange = true;
1049ff0cc061SDimitry Andric     }
1050ff0cc061SDimitry Andric   }
1051ff0cc061SDimitry Andric 
1052f22ef01cSRoman Divacky   // If the LHS is a shufflevector itself, see if we can combine it with this
1053dff0c46cSDimitry Andric   // one without producing an unusual shuffle.
1054dff0c46cSDimitry Andric   // Cases that might be simplified:
1055dff0c46cSDimitry Andric   // 1.
1056dff0c46cSDimitry Andric   // x1=shuffle(v1,v2,mask1)
1057dff0c46cSDimitry Andric   //  x=shuffle(x1,undef,mask)
1058dff0c46cSDimitry Andric   //        ==>
1059dff0c46cSDimitry Andric   //  x=shuffle(v1,undef,newMask)
1060dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1061dff0c46cSDimitry Andric   // 2.
1062dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1063dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1064dff0c46cSDimitry Andric   // where v1.size() == mask1.size()
1065dff0c46cSDimitry Andric   //        ==>
1066dff0c46cSDimitry Andric   //  x=shuffle(v1,x2,newMask)
1067dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1068dff0c46cSDimitry Andric   // 3.
1069dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1070dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1071dff0c46cSDimitry Andric   // where v2.size() == mask2.size()
1072dff0c46cSDimitry Andric   //        ==>
1073dff0c46cSDimitry Andric   //  x=shuffle(x1,v2,newMask)
1074dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1075dff0c46cSDimitry Andric   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1076dff0c46cSDimitry Andric   // 4.
1077dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1078dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1079dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1080dff0c46cSDimitry Andric   // where v1.size() == v2.size()
1081dff0c46cSDimitry Andric   //        ==>
1082dff0c46cSDimitry Andric   //  x=shuffle(v1,v2,newMask)
1083dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1084dff0c46cSDimitry Andric   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1085dff0c46cSDimitry Andric   //
1086dff0c46cSDimitry Andric   // Here we are really conservative:
1087f22ef01cSRoman Divacky   // we are absolutely afraid of producing a shuffle mask not in the input
1088f22ef01cSRoman Divacky   // program, because the code gen may not be smart enough to turn a merged
1089f22ef01cSRoman Divacky   // shuffle into two specific shuffles: it may produce worse code.  As such,
10902754fe60SDimitry Andric   // we only merge two shuffles if the result is either a splat or one of the
1091dff0c46cSDimitry Andric   // input shuffle masks.  In this case, merging the shuffles just removes
10922754fe60SDimitry Andric   // one instruction, which we know is safe.  This is good for things like
1093dff0c46cSDimitry Andric   // turning: (splat(splat)) -> splat, or
1094dff0c46cSDimitry Andric   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1095dff0c46cSDimitry Andric   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1096dff0c46cSDimitry Andric   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1097dff0c46cSDimitry Andric   if (LHSShuffle)
1098dff0c46cSDimitry Andric     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
109991bc56edSDimitry Andric       LHSShuffle = nullptr;
1100dff0c46cSDimitry Andric   if (RHSShuffle)
1101dff0c46cSDimitry Andric     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
110291bc56edSDimitry Andric       RHSShuffle = nullptr;
1103dff0c46cSDimitry Andric   if (!LHSShuffle && !RHSShuffle)
110491bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1105dff0c46cSDimitry Andric 
110691bc56edSDimitry Andric   Value* LHSOp0 = nullptr;
110791bc56edSDimitry Andric   Value* LHSOp1 = nullptr;
110891bc56edSDimitry Andric   Value* RHSOp0 = nullptr;
1109dff0c46cSDimitry Andric   unsigned LHSOp0Width = 0;
1110dff0c46cSDimitry Andric   unsigned RHSOp0Width = 0;
1111dff0c46cSDimitry Andric   if (LHSShuffle) {
1112dff0c46cSDimitry Andric     LHSOp0 = LHSShuffle->getOperand(0);
1113dff0c46cSDimitry Andric     LHSOp1 = LHSShuffle->getOperand(1);
1114dff0c46cSDimitry Andric     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1115dff0c46cSDimitry Andric   }
1116dff0c46cSDimitry Andric   if (RHSShuffle) {
1117dff0c46cSDimitry Andric     RHSOp0 = RHSShuffle->getOperand(0);
1118dff0c46cSDimitry Andric     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1119dff0c46cSDimitry Andric   }
1120dff0c46cSDimitry Andric   Value* newLHS = LHS;
1121dff0c46cSDimitry Andric   Value* newRHS = RHS;
1122dff0c46cSDimitry Andric   if (LHSShuffle) {
1123dff0c46cSDimitry Andric     // case 1
1124f22ef01cSRoman Divacky     if (isa<UndefValue>(RHS)) {
1125dff0c46cSDimitry Andric       newLHS = LHSOp0;
1126dff0c46cSDimitry Andric       newRHS = LHSOp1;
1127dff0c46cSDimitry Andric     }
1128dff0c46cSDimitry Andric     // case 2 or 4
1129dff0c46cSDimitry Andric     else if (LHSOp0Width == LHSWidth) {
1130dff0c46cSDimitry Andric       newLHS = LHSOp0;
1131dff0c46cSDimitry Andric     }
1132dff0c46cSDimitry Andric   }
1133dff0c46cSDimitry Andric   // case 3 or 4
1134dff0c46cSDimitry Andric   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1135dff0c46cSDimitry Andric     newRHS = RHSOp0;
1136dff0c46cSDimitry Andric   }
1137dff0c46cSDimitry Andric   // case 4
1138dff0c46cSDimitry Andric   if (LHSOp0 == RHSOp0) {
1139dff0c46cSDimitry Andric     newLHS = LHSOp0;
114091bc56edSDimitry Andric     newRHS = nullptr;
1141dff0c46cSDimitry Andric   }
1142f22ef01cSRoman Divacky 
1143dff0c46cSDimitry Andric   if (newLHS == LHS && newRHS == RHS)
114491bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1145dff0c46cSDimitry Andric 
1146dff0c46cSDimitry Andric   SmallVector<int, 16> LHSMask;
1147dff0c46cSDimitry Andric   SmallVector<int, 16> RHSMask;
1148dff0c46cSDimitry Andric   if (newLHS != LHS)
1149dff0c46cSDimitry Andric     LHSMask = LHSShuffle->getShuffleMask();
1150dff0c46cSDimitry Andric   if (RHSShuffle && newRHS != RHS)
1151dff0c46cSDimitry Andric     RHSMask = RHSShuffle->getShuffleMask();
1152dff0c46cSDimitry Andric 
1153dff0c46cSDimitry Andric   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1154dff0c46cSDimitry Andric   SmallVector<int, 16> newMask;
11552754fe60SDimitry Andric   bool isSplat = true;
1156dff0c46cSDimitry Andric   int SplatElt = -1;
1157dff0c46cSDimitry Andric   // Create a new mask for the new ShuffleVectorInst so that the new
1158dff0c46cSDimitry Andric   // ShuffleVectorInst is equivalent to the original one.
1159dff0c46cSDimitry Andric   for (unsigned i = 0; i < VWidth; ++i) {
1160dff0c46cSDimitry Andric     int eltMask;
1161139f7f9bSDimitry Andric     if (Mask[i] < 0) {
1162dff0c46cSDimitry Andric       // This element is an undef value.
1163dff0c46cSDimitry Andric       eltMask = -1;
1164dff0c46cSDimitry Andric     } else if (Mask[i] < (int)LHSWidth) {
1165dff0c46cSDimitry Andric       // This element is from left hand side vector operand.
1166dff0c46cSDimitry Andric       //
1167dff0c46cSDimitry Andric       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1168dff0c46cSDimitry Andric       // new mask value for the element.
1169dff0c46cSDimitry Andric       if (newLHS != LHS) {
1170dff0c46cSDimitry Andric         eltMask = LHSMask[Mask[i]];
1171dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1172dff0c46cSDimitry Andric         // with a -1 mask value.
1173dff0c46cSDimitry Andric         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1174dff0c46cSDimitry Andric           eltMask = -1;
1175139f7f9bSDimitry Andric       } else
1176dff0c46cSDimitry Andric         eltMask = Mask[i];
1177dff0c46cSDimitry Andric     } else {
1178dff0c46cSDimitry Andric       // This element is from right hand side vector operand
1179dff0c46cSDimitry Andric       //
1180dff0c46cSDimitry Andric       // If the value selected is an undef value, explicitly specify it
1181dff0c46cSDimitry Andric       // with a -1 mask value. (case 1)
1182dff0c46cSDimitry Andric       if (isa<UndefValue>(RHS))
1183dff0c46cSDimitry Andric         eltMask = -1;
1184dff0c46cSDimitry Andric       // If RHS is going to be replaced (case 3 or 4), calculate the
1185dff0c46cSDimitry Andric       // new mask value for the element.
1186dff0c46cSDimitry Andric       else if (newRHS != RHS) {
1187dff0c46cSDimitry Andric         eltMask = RHSMask[Mask[i]-LHSWidth];
1188dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1189dff0c46cSDimitry Andric         // with a -1 mask value.
1190dff0c46cSDimitry Andric         if (eltMask >= (int)RHSOp0Width) {
1191dff0c46cSDimitry Andric           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1192dff0c46cSDimitry Andric                  && "should have been check above");
1193dff0c46cSDimitry Andric           eltMask = -1;
1194dff0c46cSDimitry Andric         }
1195139f7f9bSDimitry Andric       } else
1196dff0c46cSDimitry Andric         eltMask = Mask[i]-LHSWidth;
1197dff0c46cSDimitry Andric 
1198dff0c46cSDimitry Andric       // If LHS's width is changed, shift the mask value accordingly.
1199dff0c46cSDimitry Andric       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
12003861d79fSDimitry Andric       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
12013861d79fSDimitry Andric       // If newRHS == newLHS, we want to remap any references from newRHS to
12023861d79fSDimitry Andric       // newLHS so that we can properly identify splats that may occur due to
120391bc56edSDimitry Andric       // obfuscation across the two vectors.
120491bc56edSDimitry Andric       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1205dff0c46cSDimitry Andric         eltMask += newLHSWidth;
12062754fe60SDimitry Andric     }
1207f22ef01cSRoman Divacky 
1208dff0c46cSDimitry Andric     // Check if this could still be a splat.
1209dff0c46cSDimitry Andric     if (eltMask >= 0) {
1210dff0c46cSDimitry Andric       if (SplatElt >= 0 && SplatElt != eltMask)
1211dff0c46cSDimitry Andric         isSplat = false;
1212dff0c46cSDimitry Andric       SplatElt = eltMask;
1213dff0c46cSDimitry Andric     }
1214dff0c46cSDimitry Andric 
1215dff0c46cSDimitry Andric     newMask.push_back(eltMask);
1216dff0c46cSDimitry Andric   }
1217dff0c46cSDimitry Andric 
1218dff0c46cSDimitry Andric   // If the result mask is equal to one of the original shuffle masks,
1219dff0c46cSDimitry Andric   // or is a splat, do the replacement.
1220dff0c46cSDimitry Andric   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1221dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1222dff0c46cSDimitry Andric     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1223dff0c46cSDimitry Andric       if (newMask[i] < 0) {
12242754fe60SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1225f22ef01cSRoman Divacky       } else {
1226dff0c46cSDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1227f22ef01cSRoman Divacky       }
1228f22ef01cSRoman Divacky     }
122991bc56edSDimitry Andric     if (!newRHS)
1230dff0c46cSDimitry Andric       newRHS = UndefValue::get(newLHS->getType());
1231dff0c46cSDimitry Andric     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1232f22ef01cSRoman Divacky   }
1233f22ef01cSRoman Divacky 
123491bc56edSDimitry Andric   // If the result mask is an identity, replace uses of this instruction with
123591bc56edSDimitry Andric   // corresponding argument.
123691bc56edSDimitry Andric   bool isLHSID, isRHSID;
12377d523365SDimitry Andric   recognizeIdentityMask(newMask, isLHSID, isRHSID);
123891bc56edSDimitry Andric   if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
123991bc56edSDimitry Andric   if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
124091bc56edSDimitry Andric 
124191bc56edSDimitry Andric   return MadeChange ? &SVI : nullptr;
1242f22ef01cSRoman Divacky }
1243