1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements instcombine for ExtractElement, InsertElement and
13 //===----------------------------------------------------------------------===//
15 #include "InstCombineInternal.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/IR/PatternMatch.h"
19 using namespace PatternMatch;
21 #define DEBUG_TYPE "instcombine"
23 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
24 /// is to leave as a vector operation. isConstant indicates whether we're
25 /// extracting one known element. If false we're extracting a variable index.
26 static bool CheapToScalarize(Value *V, bool isConstant) {
27 if (Constant *C = dyn_cast<Constant>(V)) {
28 if (isConstant) return true;
30 // If all elts are the same, we can extract it and use any of the values.
31 if (Constant *Op0 = C->getAggregateElement(0U)) {
32 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
34 if (C->getAggregateElement(i) != Op0)
39 Instruction *I = dyn_cast<Instruction>(V);
42 // Insert element gets simplified to the inserted element or is deleted if
43 // this is constant idx extract element and its a constant idx insertelt.
44 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
45 isa<ConstantInt>(I->getOperand(2)))
47 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
49 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
50 if (BO->hasOneUse() &&
51 (CheapToScalarize(BO->getOperand(0), isConstant) ||
52 CheapToScalarize(BO->getOperand(1), isConstant)))
54 if (CmpInst *CI = dyn_cast<CmpInst>(I))
55 if (CI->hasOneUse() &&
56 (CheapToScalarize(CI->getOperand(0), isConstant) ||
57 CheapToScalarize(CI->getOperand(1), isConstant)))
63 /// FindScalarElement - Given a vector and an element number, see if the scalar
64 /// value is already around as a register, for example if it were inserted then
65 /// extracted from the vector.
66 static Value *FindScalarElement(Value *V, unsigned EltNo) {
67 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
68 VectorType *VTy = cast<VectorType>(V->getType());
69 unsigned Width = VTy->getNumElements();
70 if (EltNo >= Width) // Out of range access.
71 return UndefValue::get(VTy->getElementType());
73 if (Constant *C = dyn_cast<Constant>(V))
74 return C->getAggregateElement(EltNo);
76 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
77 // If this is an insert to a variable element, we don't know what it is.
78 if (!isa<ConstantInt>(III->getOperand(2)))
80 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
82 // If this is an insert to the element we are looking for, return the
85 return III->getOperand(1);
87 // Otherwise, the insertelement doesn't modify the value, recurse on its
89 return FindScalarElement(III->getOperand(0), EltNo);
92 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
93 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
94 int InEl = SVI->getMaskValue(EltNo);
96 return UndefValue::get(VTy->getElementType());
97 if (InEl < (int)LHSWidth)
98 return FindScalarElement(SVI->getOperand(0), InEl);
99 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
102 // Extract a value from a vector add operation with a constant zero.
103 Value *Val = nullptr; Constant *Con = nullptr;
104 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
105 if (Con->getAggregateElement(EltNo)->isNullValue())
106 return FindScalarElement(Val, EltNo);
109 // Otherwise, we don't know.
113 // If we have a PHI node with a vector type that has only 2 uses: feed
114 // itself and be an operand of extractelement at a constant location,
115 // try to replace the PHI of the vector type with a PHI of a scalar type.
116 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
117 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
118 if (!PN->hasNUses(2))
121 // If so, it's known at this point that one operand is PHI and the other is
122 // an extractelement node. Find the PHI user that is not the extractelement
124 auto iu = PN->user_begin();
125 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
126 if (PHIUser == cast<Instruction>(&EI))
127 PHIUser = cast<Instruction>(*(++iu));
129 // Verify that this PHI user has one use, which is the PHI itself,
130 // and that it is a binary operation which is cheap to scalarize.
131 // otherwise return NULL.
132 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
133 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
136 // Create a scalar PHI node that will replace the vector PHI node
137 // just before the current PHI node.
138 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
139 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
140 // Scalarize each PHI operand.
141 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
142 Value *PHIInVal = PN->getIncomingValue(i);
143 BasicBlock *inBB = PN->getIncomingBlock(i);
144 Value *Elt = EI.getIndexOperand();
145 // If the operand is the PHI induction variable:
146 if (PHIInVal == PHIUser) {
147 // Scalarize the binary operation. Its first operand is the
148 // scalar PHI, and the second operand is extracted from the other
150 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
151 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
152 Value *Op = InsertNewInstWith(
153 ExtractElementInst::Create(B0->getOperand(opId), Elt,
154 B0->getOperand(opId)->getName() + ".Elt"),
156 Value *newPHIUser = InsertNewInstWith(
157 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
158 scalarPHI->addIncoming(newPHIUser, inBB);
160 // Scalarize PHI input:
161 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
162 // Insert the new instruction into the predecessor basic block.
163 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
164 BasicBlock::iterator InsertPos;
165 if (pos && !isa<PHINode>(pos)) {
169 InsertPos = inBB->getFirstInsertionPt();
172 InsertNewInstWith(newEI, *InsertPos);
174 scalarPHI->addIncoming(newEI, inBB);
177 return ReplaceInstUsesWith(EI, scalarPHI);
180 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
181 // If vector val is constant with all elements the same, replace EI with
182 // that element. We handle a known element # below.
183 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
184 if (CheapToScalarize(C, false))
185 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
187 // If extracting a specified index from the vector, see if we can recursively
188 // find a previously computed scalar that was inserted into the vector.
189 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
190 unsigned IndexVal = IdxC->getZExtValue();
191 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
193 // If this is extracting an invalid index, turn this into undef, to avoid
194 // crashing the code below.
195 if (IndexVal >= VectorWidth)
196 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
198 // This instruction only demands the single element from the input vector.
199 // If the input vector has a single use, simplify it based on this use
201 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
202 APInt UndefElts(VectorWidth, 0);
203 APInt DemandedMask(VectorWidth, 0);
204 DemandedMask.setBit(IndexVal);
205 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
206 DemandedMask, UndefElts)) {
212 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
213 return ReplaceInstUsesWith(EI, Elt);
215 // If the this extractelement is directly using a bitcast from a vector of
216 // the same number of elements, see if we can find the source element from
217 // it. In this case, we will end up needing to bitcast the scalars.
218 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
219 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
220 if (VT->getNumElements() == VectorWidth)
221 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
222 return new BitCastInst(Elt, EI.getType());
225 // If there's a vector PHI feeding a scalar use through this extractelement
226 // instruction, try to scalarize the PHI.
227 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
228 Instruction *scalarPHI = scalarizePHI(EI, PN);
234 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
235 // Push extractelement into predecessor operation if legal and
236 // profitable to do so
237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
238 if (I->hasOneUse() &&
239 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
241 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
242 EI.getName()+".lhs");
244 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
245 EI.getName()+".rhs");
246 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
248 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
249 // Extracting the inserted element?
250 if (IE->getOperand(2) == EI.getOperand(1))
251 return ReplaceInstUsesWith(EI, IE->getOperand(1));
252 // If the inserted and extracted elements are constants, they must not
253 // be the same value, extract from the pre-inserted value instead.
254 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
255 Worklist.AddValue(EI.getOperand(0));
256 EI.setOperand(0, IE->getOperand(0));
259 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
260 // If this is extracting an element from a shufflevector, figure out where
261 // it came from and extract from the appropriate input element instead.
262 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
263 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
266 SVI->getOperand(0)->getType()->getVectorNumElements();
269 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
270 if (SrcIdx < (int)LHSWidth)
271 Src = SVI->getOperand(0);
274 Src = SVI->getOperand(1);
276 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
277 return ExtractElementInst::Create(Src,
278 ConstantInt::get(Int32Ty,
281 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
282 // Canonicalize extractelement(cast) -> cast(extractelement)
283 // bitcasts can change the number of vector elements and they cost nothing
284 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
285 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
286 EI.getIndexOperand());
287 Worklist.AddValue(EE);
288 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
290 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
291 if (SI->hasOneUse()) {
292 // TODO: For a select on vectors, it might be useful to do this if it
293 // has multiple extractelement uses. For vector select, that seems to
294 // fight the vectorizer.
296 // If we are extracting an element from a vector select or a select on
297 // vectors, a select on the scalars extracted from the vector arguments.
298 Value *TrueVal = SI->getTrueValue();
299 Value *FalseVal = SI->getFalseValue();
301 Value *Cond = SI->getCondition();
302 if (Cond->getType()->isVectorTy()) {
303 Cond = Builder->CreateExtractElement(Cond,
304 EI.getIndexOperand(),
305 Cond->getName() + ".elt");
309 = Builder->CreateExtractElement(TrueVal,
310 EI.getIndexOperand(),
311 TrueVal->getName() + ".elt");
314 = Builder->CreateExtractElement(FalseVal,
315 EI.getIndexOperand(),
316 FalseVal->getName() + ".elt");
317 return SelectInst::Create(Cond,
320 SI->getName() + ".elt");
327 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
328 /// elements from either LHS or RHS, return the shuffle mask and true.
329 /// Otherwise, return false.
330 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
331 SmallVectorImpl<Constant*> &Mask) {
332 assert(LHS->getType() == RHS->getType() &&
333 "Invalid CollectSingleShuffleElements");
334 unsigned NumElts = V->getType()->getVectorNumElements();
336 if (isa<UndefValue>(V)) {
337 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
342 for (unsigned i = 0; i != NumElts; ++i)
343 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
348 for (unsigned i = 0; i != NumElts; ++i)
349 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
354 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
355 // If this is an insert of an extract from some other vector, include it.
356 Value *VecOp = IEI->getOperand(0);
357 Value *ScalarOp = IEI->getOperand(1);
358 Value *IdxOp = IEI->getOperand(2);
360 if (!isa<ConstantInt>(IdxOp))
362 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
364 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
365 // We can handle this if the vector we are inserting into is
367 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
368 // If so, update the mask to reflect the inserted undef.
369 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
372 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
373 if (isa<ConstantInt>(EI->getOperand(1))) {
374 unsigned ExtractedIdx =
375 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
376 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
378 // This must be extracting from either LHS or RHS.
379 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
380 // We can handle this if the vector we are inserting into is
382 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
383 // If so, update the mask to reflect the inserted value.
384 if (EI->getOperand(0) == LHS) {
385 Mask[InsertedIdx % NumElts] =
386 ConstantInt::get(Type::getInt32Ty(V->getContext()),
389 assert(EI->getOperand(0) == RHS);
390 Mask[InsertedIdx % NumElts] =
391 ConstantInt::get(Type::getInt32Ty(V->getContext()),
392 ExtractedIdx + NumLHSElts);
405 /// We are building a shuffle to create V, which is a sequence of insertelement,
406 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
407 /// not rely on the second vector source. Return a std::pair containing the
408 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
409 /// parameter as required.
411 /// Note: we intentionally don't try to fold earlier shuffles since they have
412 /// often been chosen carefully to be efficiently implementable on the target.
413 typedef std::pair<Value *, Value *> ShuffleOps;
415 static ShuffleOps CollectShuffleElements(Value *V,
416 SmallVectorImpl<Constant *> &Mask,
417 Value *PermittedRHS) {
418 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
419 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
421 if (isa<UndefValue>(V)) {
422 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
423 return std::make_pair(
424 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
427 if (isa<ConstantAggregateZero>(V)) {
428 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
429 return std::make_pair(V, nullptr);
432 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
433 // If this is an insert of an extract from some other vector, include it.
434 Value *VecOp = IEI->getOperand(0);
435 Value *ScalarOp = IEI->getOperand(1);
436 Value *IdxOp = IEI->getOperand(2);
438 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
439 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
440 unsigned ExtractedIdx =
441 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
442 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
444 // Either the extracted from or inserted into vector must be RHSVec,
445 // otherwise we'd end up with a shuffle of three inputs.
446 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
447 Value *RHS = EI->getOperand(0);
448 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
449 assert(LR.second == nullptr || LR.second == RHS);
451 if (LR.first->getType() != RHS->getType()) {
452 // We tried our best, but we can't find anything compatible with RHS
453 // further up the chain. Return a trivial shuffle.
454 for (unsigned i = 0; i < NumElts; ++i)
455 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
456 return std::make_pair(V, nullptr);
459 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
460 Mask[InsertedIdx % NumElts] =
461 ConstantInt::get(Type::getInt32Ty(V->getContext()),
462 NumLHSElts+ExtractedIdx);
463 return std::make_pair(LR.first, RHS);
466 if (VecOp == PermittedRHS) {
467 // We've gone as far as we can: anything on the other side of the
468 // extractelement will already have been converted into a shuffle.
469 unsigned NumLHSElts =
470 EI->getOperand(0)->getType()->getVectorNumElements();
471 for (unsigned i = 0; i != NumElts; ++i)
472 Mask.push_back(ConstantInt::get(
473 Type::getInt32Ty(V->getContext()),
474 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
475 return std::make_pair(EI->getOperand(0), PermittedRHS);
478 // If this insertelement is a chain that comes from exactly these two
479 // vectors, return the vector and the effective shuffle.
480 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
481 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
483 return std::make_pair(EI->getOperand(0), PermittedRHS);
488 // Otherwise, can't do anything fancy. Return an identity vector.
489 for (unsigned i = 0; i != NumElts; ++i)
490 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
491 return std::make_pair(V, nullptr);
494 /// Try to find redundant insertvalue instructions, like the following ones:
495 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
496 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
497 /// Here the second instruction inserts values at the same indices, as the
498 /// first one, making the first one redundant.
499 /// It should be transformed to:
500 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
501 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
502 bool IsRedundant = false;
503 ArrayRef<unsigned int> FirstIndices = I.getIndices();
505 // If there is a chain of insertvalue instructions (each of them except the
506 // last one has only one use and it's another insertvalue insn from this
507 // chain), check if any of the 'children' uses the same indices as the first
508 // instruction. In this case, the first one is redundant.
511 while (V->hasOneUse() && Depth < 10) {
512 User *U = V->user_back();
513 auto UserInsInst = dyn_cast<InsertValueInst>(U);
514 if (!UserInsInst || U->getOperand(0) != V)
516 if (UserInsInst->getIndices() == FirstIndices) {
525 return ReplaceInstUsesWith(I, I.getOperand(0));
529 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
530 Value *VecOp = IE.getOperand(0);
531 Value *ScalarOp = IE.getOperand(1);
532 Value *IdxOp = IE.getOperand(2);
534 // Inserting an undef or into an undefined place, remove this.
535 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
536 ReplaceInstUsesWith(IE, VecOp);
538 // If the inserted element was extracted from some other vector, and if the
539 // indexes are constant, try to turn this into a shufflevector operation.
540 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
541 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
542 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
543 unsigned NumExtractVectorElts =
544 EI->getOperand(0)->getType()->getVectorNumElements();
545 unsigned ExtractedIdx =
546 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
547 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
549 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
550 return ReplaceInstUsesWith(IE, VecOp);
552 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
553 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
555 // If we are extracting a value from a vector, then inserting it right
556 // back into the same place, just use the input vector.
557 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
558 return ReplaceInstUsesWith(IE, VecOp);
560 // If this insertelement isn't used by some other insertelement, turn it
561 // (and any insertelements it points to), into one big shuffle.
562 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
563 SmallVector<Constant*, 16> Mask;
564 ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
566 // The proposed shuffle may be trivial, in which case we shouldn't
567 // perform the combine.
568 if (LR.first != &IE && LR.second != &IE) {
569 // We now have a shuffle of LHS, RHS, Mask.
570 if (LR.second == nullptr)
571 LR.second = UndefValue::get(LR.first->getType());
572 return new ShuffleVectorInst(LR.first, LR.second,
573 ConstantVector::get(Mask));
579 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
580 APInt UndefElts(VWidth, 0);
581 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
582 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
584 return ReplaceInstUsesWith(IE, V);
591 /// Return true if we can evaluate the specified expression tree if the vector
592 /// elements were shuffled in a different order.
593 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
594 unsigned Depth = 5) {
595 // We can always reorder the elements of a constant.
596 if (isa<Constant>(V))
599 // We won't reorder vector arguments. No IPO here.
600 Instruction *I = dyn_cast<Instruction>(V);
601 if (!I) return false;
603 // Two users may expect different orders of the elements. Don't try it.
607 if (Depth == 0) return false;
609 switch (I->getOpcode()) {
610 case Instruction::Add:
611 case Instruction::FAdd:
612 case Instruction::Sub:
613 case Instruction::FSub:
614 case Instruction::Mul:
615 case Instruction::FMul:
616 case Instruction::UDiv:
617 case Instruction::SDiv:
618 case Instruction::FDiv:
619 case Instruction::URem:
620 case Instruction::SRem:
621 case Instruction::FRem:
622 case Instruction::Shl:
623 case Instruction::LShr:
624 case Instruction::AShr:
625 case Instruction::And:
626 case Instruction::Or:
627 case Instruction::Xor:
628 case Instruction::ICmp:
629 case Instruction::FCmp:
630 case Instruction::Trunc:
631 case Instruction::ZExt:
632 case Instruction::SExt:
633 case Instruction::FPToUI:
634 case Instruction::FPToSI:
635 case Instruction::UIToFP:
636 case Instruction::SIToFP:
637 case Instruction::FPTrunc:
638 case Instruction::FPExt:
639 case Instruction::GetElementPtr: {
640 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
641 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
646 case Instruction::InsertElement: {
647 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
648 if (!CI) return false;
649 int ElementNumber = CI->getLimitedValue();
651 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
652 // can't put an element into multiple indices.
653 bool SeenOnce = false;
654 for (int i = 0, e = Mask.size(); i != e; ++i) {
655 if (Mask[i] == ElementNumber) {
661 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
667 /// Rebuild a new instruction just like 'I' but with the new operands given.
668 /// In the event of type mismatch, the type of the operands is correct.
669 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
670 // We don't want to use the IRBuilder here because we want the replacement
671 // instructions to appear next to 'I', not the builder's insertion point.
672 switch (I->getOpcode()) {
673 case Instruction::Add:
674 case Instruction::FAdd:
675 case Instruction::Sub:
676 case Instruction::FSub:
677 case Instruction::Mul:
678 case Instruction::FMul:
679 case Instruction::UDiv:
680 case Instruction::SDiv:
681 case Instruction::FDiv:
682 case Instruction::URem:
683 case Instruction::SRem:
684 case Instruction::FRem:
685 case Instruction::Shl:
686 case Instruction::LShr:
687 case Instruction::AShr:
688 case Instruction::And:
689 case Instruction::Or:
690 case Instruction::Xor: {
691 BinaryOperator *BO = cast<BinaryOperator>(I);
692 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
693 BinaryOperator *New =
694 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
695 NewOps[0], NewOps[1], "", BO);
696 if (isa<OverflowingBinaryOperator>(BO)) {
697 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
698 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
700 if (isa<PossiblyExactOperator>(BO)) {
701 New->setIsExact(BO->isExact());
703 if (isa<FPMathOperator>(BO))
704 New->copyFastMathFlags(I);
707 case Instruction::ICmp:
708 assert(NewOps.size() == 2 && "icmp with #ops != 2");
709 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
710 NewOps[0], NewOps[1]);
711 case Instruction::FCmp:
712 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
713 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
714 NewOps[0], NewOps[1]);
715 case Instruction::Trunc:
716 case Instruction::ZExt:
717 case Instruction::SExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::UIToFP:
721 case Instruction::SIToFP:
722 case Instruction::FPTrunc:
723 case Instruction::FPExt: {
724 // It's possible that the mask has a different number of elements from
725 // the original cast. We recompute the destination type to match the mask.
727 VectorType::get(I->getType()->getScalarType(),
728 NewOps[0]->getType()->getVectorNumElements());
729 assert(NewOps.size() == 1 && "cast with #ops != 1");
730 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
733 case Instruction::GetElementPtr: {
734 Value *Ptr = NewOps[0];
735 ArrayRef<Value*> Idx = NewOps.slice(1);
736 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
737 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
741 llvm_unreachable("failed to rebuild vector instructions");
745 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
746 // Mask.size() does not need to be equal to the number of vector elements.
748 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
749 if (isa<UndefValue>(V)) {
750 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
753 if (isa<ConstantAggregateZero>(V)) {
754 return ConstantAggregateZero::get(
755 VectorType::get(V->getType()->getScalarType(),
758 if (Constant *C = dyn_cast<Constant>(V)) {
759 SmallVector<Constant *, 16> MaskValues;
760 for (int i = 0, e = Mask.size(); i != e; ++i) {
762 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
764 MaskValues.push_back(Builder->getInt32(Mask[i]));
766 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
767 ConstantVector::get(MaskValues));
770 Instruction *I = cast<Instruction>(V);
771 switch (I->getOpcode()) {
772 case Instruction::Add:
773 case Instruction::FAdd:
774 case Instruction::Sub:
775 case Instruction::FSub:
776 case Instruction::Mul:
777 case Instruction::FMul:
778 case Instruction::UDiv:
779 case Instruction::SDiv:
780 case Instruction::FDiv:
781 case Instruction::URem:
782 case Instruction::SRem:
783 case Instruction::FRem:
784 case Instruction::Shl:
785 case Instruction::LShr:
786 case Instruction::AShr:
787 case Instruction::And:
788 case Instruction::Or:
789 case Instruction::Xor:
790 case Instruction::ICmp:
791 case Instruction::FCmp:
792 case Instruction::Trunc:
793 case Instruction::ZExt:
794 case Instruction::SExt:
795 case Instruction::FPToUI:
796 case Instruction::FPToSI:
797 case Instruction::UIToFP:
798 case Instruction::SIToFP:
799 case Instruction::FPTrunc:
800 case Instruction::FPExt:
801 case Instruction::Select:
802 case Instruction::GetElementPtr: {
803 SmallVector<Value*, 8> NewOps;
804 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
805 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
806 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
808 NeedsRebuild |= (V != I->getOperand(i));
811 return BuildNew(I, NewOps);
815 case Instruction::InsertElement: {
816 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
818 // The insertelement was inserting at Element. Figure out which element
819 // that becomes after shuffling. The answer is guaranteed to be unique
820 // by CanEvaluateShuffled.
823 for (int e = Mask.size(); Index != e; ++Index) {
824 if (Mask[Index] == Element) {
830 // If element is not in Mask, no need to handle the operand 1 (element to
831 // be inserted). Just evaluate values in operand 0 according to Mask.
833 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
835 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
836 return InsertElementInst::Create(V, I->getOperand(1),
837 Builder->getInt32(Index), "", I);
840 llvm_unreachable("failed to reorder elements of vector instruction!");
843 static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
844 bool &isLHSID, bool &isRHSID) {
845 isLHSID = isRHSID = true;
847 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
848 if (Mask[i] < 0) continue; // Ignore undef values.
849 // Is this an identity shuffle of the LHS value?
850 isLHSID &= (Mask[i] == (int)i);
852 // Is this an identity shuffle of the RHS value?
853 isRHSID &= (Mask[i]-e == i);
857 // Returns true if the shuffle is extracting a contiguous range of values from
859 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
860 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
861 // Shuffles to: |EE|FF|GG|HH|
863 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
864 SmallVector<int, 16> &Mask) {
866 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
867 unsigned MaskElems = Mask.size();
868 unsigned BegIdx = Mask.front();
869 unsigned EndIdx = Mask.back();
870 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
872 for (unsigned I = 0; I != MaskElems; ++I)
873 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
878 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
879 Value *LHS = SVI.getOperand(0);
880 Value *RHS = SVI.getOperand(1);
881 SmallVector<int, 16> Mask = SVI.getShuffleMask();
882 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
884 bool MadeChange = false;
886 // Undefined shuffle mask -> undefined value.
887 if (isa<UndefValue>(SVI.getOperand(2)))
888 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
890 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
892 APInt UndefElts(VWidth, 0);
893 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
894 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
896 return ReplaceInstUsesWith(SVI, V);
897 LHS = SVI.getOperand(0);
898 RHS = SVI.getOperand(1);
902 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
904 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
905 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
906 if (LHS == RHS || isa<UndefValue>(LHS)) {
907 if (isa<UndefValue>(LHS) && LHS == RHS) {
908 // shuffle(undef,undef,mask) -> undef.
909 Value *Result = (VWidth == LHSWidth)
910 ? LHS : UndefValue::get(SVI.getType());
911 return ReplaceInstUsesWith(SVI, Result);
914 // Remap any references to RHS to use LHS.
915 SmallVector<Constant*, 16> Elts;
916 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
918 Elts.push_back(UndefValue::get(Int32Ty));
922 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
923 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
924 Mask[i] = -1; // Turn into undef.
925 Elts.push_back(UndefValue::get(Int32Ty));
927 Mask[i] = Mask[i] % e; // Force to LHS.
928 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
931 SVI.setOperand(0, SVI.getOperand(1));
932 SVI.setOperand(1, UndefValue::get(RHS->getType()));
933 SVI.setOperand(2, ConstantVector::get(Elts));
934 LHS = SVI.getOperand(0);
935 RHS = SVI.getOperand(1);
939 if (VWidth == LHSWidth) {
940 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
941 bool isLHSID, isRHSID;
942 RecognizeIdentityMask(Mask, isLHSID, isRHSID);
944 // Eliminate identity shuffles.
945 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
946 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
949 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
950 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
951 return ReplaceInstUsesWith(SVI, V);
954 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
955 // a non-vector type. We can instead bitcast the original vector followed by
956 // an extract of the desired element:
958 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
959 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
960 // %1 = bitcast <4 x i8> %sroa to i32
962 // %bc = bitcast <16 x i8> %in to <4 x i32>
963 // %ext = extractelement <4 x i32> %bc, i32 0
965 // If the shuffle is extracting a contiguous range of values from the input
966 // vector then each use which is a bitcast of the extracted size can be
967 // replaced. This will work if the vector types are compatible, and the begin
968 // index is aligned to a value in the casted vector type. If the begin index
969 // isn't aligned then we can shuffle the original vector (keeping the same
970 // vector type) before extracting.
972 // This code will bail out if the target type is fundamentally incompatible
973 // with vectors of the source type.
975 // Example of <16 x i8>, target type i32:
976 // Index range [4,8): v-----------v Will work.
977 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
978 // <16 x i8>: | | | | | | | | | | | | | | | | |
979 // <4 x i32>: | | | | |
980 // +-----------+-----------+-----------+-----------+
981 // Index range [6,10): ^-----------^ Needs an extra shuffle.
982 // Target type i40: ^--------------^ Won't work, bail.
983 if (isShuffleExtractingFromLHS(SVI, Mask)) {
985 unsigned MaskElems = Mask.size();
986 unsigned BegIdx = Mask.front();
987 VectorType *SrcTy = cast<VectorType>(V->getType());
988 unsigned VecBitWidth = SrcTy->getBitWidth();
989 unsigned SrcElemBitWidth =
990 SrcTy->getElementType()->getPrimitiveSizeInBits();
991 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
992 unsigned SrcNumElems = SrcTy->getNumElements();
993 SmallVector<BitCastInst *, 8> BCs;
994 DenseMap<Type *, Value *> NewBCs;
995 for (User *U : SVI.users())
996 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
997 if (!BC->use_empty())
998 // Only visit bitcasts that weren't previously handled.
1000 for (BitCastInst *BC : BCs) {
1001 Type *TgtTy = BC->getDestTy();
1002 unsigned TgtElemBitWidth = TgtTy->getPrimitiveSizeInBits();
1003 if (!TgtElemBitWidth)
1005 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1006 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1007 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1008 if (!VecBitWidthsEqual)
1010 if (!VectorType::isValidElementType(TgtTy))
1012 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1013 if (!BegIsAligned) {
1014 // Shuffle the input so [0,NumElements) contains the output, and
1015 // [NumElems,SrcNumElems) is undef.
1016 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1017 UndefValue::get(Int32Ty));
1018 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1019 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1020 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1021 ConstantVector::get(ShuffleMask),
1022 SVI.getName() + ".extract");
1025 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1026 assert(SrcElemsPerTgtElem);
1027 BegIdx /= SrcElemsPerTgtElem;
1028 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1032 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1033 if (!BCAlreadyExists)
1034 NewBCs[CastSrcTy] = NewBC;
1035 auto *Ext = Builder->CreateExtractElement(
1036 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1037 // The shufflevector isn't being replaced: the bitcast that used it
1038 // is. InstCombine will visit the newly-created instructions.
1039 ReplaceInstUsesWith(*BC, Ext);
1044 // If the LHS is a shufflevector itself, see if we can combine it with this
1045 // one without producing an unusual shuffle.
1046 // Cases that might be simplified:
1048 // x1=shuffle(v1,v2,mask1)
1049 // x=shuffle(x1,undef,mask)
1051 // x=shuffle(v1,undef,newMask)
1052 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1054 // x1=shuffle(v1,undef,mask1)
1055 // x=shuffle(x1,x2,mask)
1056 // where v1.size() == mask1.size()
1058 // x=shuffle(v1,x2,newMask)
1059 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1061 // x2=shuffle(v2,undef,mask2)
1062 // x=shuffle(x1,x2,mask)
1063 // where v2.size() == mask2.size()
1065 // x=shuffle(x1,v2,newMask)
1066 // newMask[i] = (mask[i] < x1.size())
1067 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1069 // x1=shuffle(v1,undef,mask1)
1070 // x2=shuffle(v2,undef,mask2)
1071 // x=shuffle(x1,x2,mask)
1072 // where v1.size() == v2.size()
1074 // x=shuffle(v1,v2,newMask)
1075 // newMask[i] = (mask[i] < x1.size())
1076 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1078 // Here we are really conservative:
1079 // we are absolutely afraid of producing a shuffle mask not in the input
1080 // program, because the code gen may not be smart enough to turn a merged
1081 // shuffle into two specific shuffles: it may produce worse code. As such,
1082 // we only merge two shuffles if the result is either a splat or one of the
1083 // input shuffle masks. In this case, merging the shuffles just removes
1084 // one instruction, which we know is safe. This is good for things like
1085 // turning: (splat(splat)) -> splat, or
1086 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1087 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1088 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1090 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
1091 LHSShuffle = nullptr;
1093 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
1094 RHSShuffle = nullptr;
1095 if (!LHSShuffle && !RHSShuffle)
1096 return MadeChange ? &SVI : nullptr;
1098 Value* LHSOp0 = nullptr;
1099 Value* LHSOp1 = nullptr;
1100 Value* RHSOp0 = nullptr;
1101 unsigned LHSOp0Width = 0;
1102 unsigned RHSOp0Width = 0;
1104 LHSOp0 = LHSShuffle->getOperand(0);
1105 LHSOp1 = LHSShuffle->getOperand(1);
1106 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1109 RHSOp0 = RHSShuffle->getOperand(0);
1110 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1112 Value* newLHS = LHS;
1113 Value* newRHS = RHS;
1116 if (isa<UndefValue>(RHS)) {
1121 else if (LHSOp0Width == LHSWidth) {
1126 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1130 if (LHSOp0 == RHSOp0) {
1135 if (newLHS == LHS && newRHS == RHS)
1136 return MadeChange ? &SVI : nullptr;
1138 SmallVector<int, 16> LHSMask;
1139 SmallVector<int, 16> RHSMask;
1141 LHSMask = LHSShuffle->getShuffleMask();
1142 if (RHSShuffle && newRHS != RHS)
1143 RHSMask = RHSShuffle->getShuffleMask();
1145 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1146 SmallVector<int, 16> newMask;
1147 bool isSplat = true;
1149 // Create a new mask for the new ShuffleVectorInst so that the new
1150 // ShuffleVectorInst is equivalent to the original one.
1151 for (unsigned i = 0; i < VWidth; ++i) {
1154 // This element is an undef value.
1156 } else if (Mask[i] < (int)LHSWidth) {
1157 // This element is from left hand side vector operand.
1159 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1160 // new mask value for the element.
1161 if (newLHS != LHS) {
1162 eltMask = LHSMask[Mask[i]];
1163 // If the value selected is an undef value, explicitly specify it
1164 // with a -1 mask value.
1165 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1170 // This element is from right hand side vector operand
1172 // If the value selected is an undef value, explicitly specify it
1173 // with a -1 mask value. (case 1)
1174 if (isa<UndefValue>(RHS))
1176 // If RHS is going to be replaced (case 3 or 4), calculate the
1177 // new mask value for the element.
1178 else if (newRHS != RHS) {
1179 eltMask = RHSMask[Mask[i]-LHSWidth];
1180 // If the value selected is an undef value, explicitly specify it
1181 // with a -1 mask value.
1182 if (eltMask >= (int)RHSOp0Width) {
1183 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1184 && "should have been check above");
1188 eltMask = Mask[i]-LHSWidth;
1190 // If LHS's width is changed, shift the mask value accordingly.
1191 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1192 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1193 // If newRHS == newLHS, we want to remap any references from newRHS to
1194 // newLHS so that we can properly identify splats that may occur due to
1195 // obfuscation across the two vectors.
1196 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1197 eltMask += newLHSWidth;
1200 // Check if this could still be a splat.
1202 if (SplatElt >= 0 && SplatElt != eltMask)
1207 newMask.push_back(eltMask);
1210 // If the result mask is equal to one of the original shuffle masks,
1211 // or is a splat, do the replacement.
1212 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1213 SmallVector<Constant*, 16> Elts;
1214 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1215 if (newMask[i] < 0) {
1216 Elts.push_back(UndefValue::get(Int32Ty));
1218 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1222 newRHS = UndefValue::get(newLHS->getType());
1223 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1226 // If the result mask is an identity, replace uses of this instruction with
1227 // corresponding argument.
1228 bool isLHSID, isRHSID;
1229 RecognizeIdentityMask(newMask, isLHSID, isRHSID);
1230 if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1231 if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
1233 return MadeChange ? &SVI : nullptr;