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/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/VectorUtils.h"
19 #include "llvm/IR/PatternMatch.h"
21 using namespace PatternMatch;
23 #define DEBUG_TYPE "instcombine"
25 /// Return true if the value is cheaper to scalarize than it is to leave as a
26 /// vector operation. isConstant indicates whether we're extracting one known
27 /// element. If false we're extracting a variable index.
28 static bool cheapToScalarize(Value *V, bool isConstant) {
29 if (Constant *C = dyn_cast<Constant>(V)) {
30 if (isConstant) return true;
32 // If all elts are the same, we can extract it and use any of the values.
33 if (Constant *Op0 = C->getAggregateElement(0U)) {
34 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
36 if (C->getAggregateElement(i) != Op0)
41 Instruction *I = dyn_cast<Instruction>(V);
44 // Insert element gets simplified to the inserted element or is deleted if
45 // this is constant idx extract element and its a constant idx insertelt.
46 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
47 isa<ConstantInt>(I->getOperand(2)))
49 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
51 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
52 if (BO->hasOneUse() &&
53 (cheapToScalarize(BO->getOperand(0), isConstant) ||
54 cheapToScalarize(BO->getOperand(1), isConstant)))
56 if (CmpInst *CI = dyn_cast<CmpInst>(I))
57 if (CI->hasOneUse() &&
58 (cheapToScalarize(CI->getOperand(0), isConstant) ||
59 cheapToScalarize(CI->getOperand(1), isConstant)))
65 // If we have a PHI node with a vector type that has only 2 uses: feed
66 // itself and be an operand of extractelement at a constant location,
67 // try to replace the PHI of the vector type with a PHI of a scalar type.
68 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
69 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
73 // If so, it's known at this point that one operand is PHI and the other is
74 // an extractelement node. Find the PHI user that is not the extractelement
76 auto iu = PN->user_begin();
77 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
78 if (PHIUser == cast<Instruction>(&EI))
79 PHIUser = cast<Instruction>(*(++iu));
81 // Verify that this PHI user has one use, which is the PHI itself,
82 // and that it is a binary operation which is cheap to scalarize.
83 // otherwise return NULL.
84 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
85 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
88 // Create a scalar PHI node that will replace the vector PHI node
89 // just before the current PHI node.
90 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
91 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
92 // Scalarize each PHI operand.
93 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
94 Value *PHIInVal = PN->getIncomingValue(i);
95 BasicBlock *inBB = PN->getIncomingBlock(i);
96 Value *Elt = EI.getIndexOperand();
97 // If the operand is the PHI induction variable:
98 if (PHIInVal == PHIUser) {
99 // Scalarize the binary operation. Its first operand is the
100 // scalar PHI, and the second operand is extracted from the other
102 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
103 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
104 Value *Op = InsertNewInstWith(
105 ExtractElementInst::Create(B0->getOperand(opId), Elt,
106 B0->getOperand(opId)->getName() + ".Elt"),
108 Value *newPHIUser = InsertNewInstWith(
109 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
110 scalarPHI->addIncoming(newPHIUser, inBB);
112 // Scalarize PHI input:
113 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
114 // Insert the new instruction into the predecessor basic block.
115 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
116 BasicBlock::iterator InsertPos;
117 if (pos && !isa<PHINode>(pos)) {
118 InsertPos = ++pos->getIterator();
120 InsertPos = inBB->getFirstInsertionPt();
123 InsertNewInstWith(newEI, *InsertPos);
125 scalarPHI->addIncoming(newEI, inBB);
128 return ReplaceInstUsesWith(EI, scalarPHI);
131 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
132 if (Value *V = SimplifyExtractElementInst(
133 EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
134 return ReplaceInstUsesWith(EI, V);
136 // If vector val is constant with all elements the same, replace EI with
137 // that element. We handle a known element # below.
138 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
139 if (cheapToScalarize(C, false))
140 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
142 // If extracting a specified index from the vector, see if we can recursively
143 // find a previously computed scalar that was inserted into the vector.
144 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
145 unsigned IndexVal = IdxC->getZExtValue();
146 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
148 // InstSimplify handles cases where the index is invalid.
149 assert(IndexVal < VectorWidth);
151 // This instruction only demands the single element from the input vector.
152 // If the input vector has a single use, simplify it based on this use
154 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
155 APInt UndefElts(VectorWidth, 0);
156 APInt DemandedMask(VectorWidth, 0);
157 DemandedMask.setBit(IndexVal);
158 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
165 // If this extractelement is directly using a bitcast from a vector of
166 // the same number of elements, see if we can find the source element from
167 // it. In this case, we will end up needing to bitcast the scalars.
168 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
169 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
170 if (VT->getNumElements() == VectorWidth)
171 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
172 return new BitCastInst(Elt, EI.getType());
175 // If there's a vector PHI feeding a scalar use through this extractelement
176 // instruction, try to scalarize the PHI.
177 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
178 Instruction *scalarPHI = scalarizePHI(EI, PN);
184 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
185 // Push extractelement into predecessor operation if legal and
186 // profitable to do so.
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
188 if (I->hasOneUse() &&
189 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
191 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
192 EI.getName()+".lhs");
194 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
195 EI.getName()+".rhs");
196 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
198 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
199 // Extracting the inserted element?
200 if (IE->getOperand(2) == EI.getOperand(1))
201 return ReplaceInstUsesWith(EI, IE->getOperand(1));
202 // If the inserted and extracted elements are constants, they must not
203 // be the same value, extract from the pre-inserted value instead.
204 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
205 Worklist.AddValue(EI.getOperand(0));
206 EI.setOperand(0, IE->getOperand(0));
209 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
210 // If this is extracting an element from a shufflevector, figure out where
211 // it came from and extract from the appropriate input element instead.
212 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
213 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
216 SVI->getOperand(0)->getType()->getVectorNumElements();
219 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
220 if (SrcIdx < (int)LHSWidth)
221 Src = SVI->getOperand(0);
224 Src = SVI->getOperand(1);
226 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
227 return ExtractElementInst::Create(Src,
228 ConstantInt::get(Int32Ty,
231 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
232 // Canonicalize extractelement(cast) -> cast(extractelement).
233 // Bitcasts can change the number of vector elements, and they cost
235 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
236 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
237 EI.getIndexOperand());
238 Worklist.AddValue(EE);
239 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
241 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
242 if (SI->hasOneUse()) {
243 // TODO: For a select on vectors, it might be useful to do this if it
244 // has multiple extractelement uses. For vector select, that seems to
245 // fight the vectorizer.
247 // If we are extracting an element from a vector select or a select on
248 // vectors, create a select on the scalars extracted from the vector
250 Value *TrueVal = SI->getTrueValue();
251 Value *FalseVal = SI->getFalseValue();
253 Value *Cond = SI->getCondition();
254 if (Cond->getType()->isVectorTy()) {
255 Cond = Builder->CreateExtractElement(Cond,
256 EI.getIndexOperand(),
257 Cond->getName() + ".elt");
261 = Builder->CreateExtractElement(TrueVal,
262 EI.getIndexOperand(),
263 TrueVal->getName() + ".elt");
266 = Builder->CreateExtractElement(FalseVal,
267 EI.getIndexOperand(),
268 FalseVal->getName() + ".elt");
269 return SelectInst::Create(Cond,
272 SI->getName() + ".elt");
279 /// If V is a shuffle of values that ONLY returns elements from either LHS or
280 /// RHS, return the shuffle mask and true. Otherwise, return false.
281 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
282 SmallVectorImpl<Constant*> &Mask) {
283 assert(LHS->getType() == RHS->getType() &&
284 "Invalid CollectSingleShuffleElements");
285 unsigned NumElts = V->getType()->getVectorNumElements();
287 if (isa<UndefValue>(V)) {
288 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
293 for (unsigned i = 0; i != NumElts; ++i)
294 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
299 for (unsigned i = 0; i != NumElts; ++i)
300 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
305 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
306 // If this is an insert of an extract from some other vector, include it.
307 Value *VecOp = IEI->getOperand(0);
308 Value *ScalarOp = IEI->getOperand(1);
309 Value *IdxOp = IEI->getOperand(2);
311 if (!isa<ConstantInt>(IdxOp))
313 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
315 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
316 // We can handle this if the vector we are inserting into is
318 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
319 // If so, update the mask to reflect the inserted undef.
320 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
323 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
324 if (isa<ConstantInt>(EI->getOperand(1))) {
325 unsigned ExtractedIdx =
326 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
327 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
329 // This must be extracting from either LHS or RHS.
330 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
331 // We can handle this if the vector we are inserting into is
333 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
334 // If so, update the mask to reflect the inserted value.
335 if (EI->getOperand(0) == LHS) {
336 Mask[InsertedIdx % NumElts] =
337 ConstantInt::get(Type::getInt32Ty(V->getContext()),
340 assert(EI->getOperand(0) == RHS);
341 Mask[InsertedIdx % NumElts] =
342 ConstantInt::get(Type::getInt32Ty(V->getContext()),
343 ExtractedIdx + NumLHSElts);
355 /// If we have insertion into a vector that is wider than the vector that we
356 /// are extracting from, try to widen the source vector to allow a single
357 /// shufflevector to replace one or more insert/extract pairs.
358 static void replaceExtractElements(InsertElementInst *InsElt,
359 ExtractElementInst *ExtElt,
361 VectorType *InsVecType = InsElt->getType();
362 VectorType *ExtVecType = ExtElt->getVectorOperandType();
363 unsigned NumInsElts = InsVecType->getVectorNumElements();
364 unsigned NumExtElts = ExtVecType->getVectorNumElements();
366 // The inserted-to vector must be wider than the extracted-from vector.
367 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
368 NumExtElts >= NumInsElts)
371 // Create a shuffle mask to widen the extended-from vector using undefined
372 // values. The mask selects all of the values of the original vector followed
373 // by as many undefined values as needed to create a vector of the same length
374 // as the inserted-to vector.
375 SmallVector<Constant *, 16> ExtendMask;
376 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
377 for (unsigned i = 0; i < NumExtElts; ++i)
378 ExtendMask.push_back(ConstantInt::get(IntType, i));
379 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
380 ExtendMask.push_back(UndefValue::get(IntType));
382 Value *ExtVecOp = ExtElt->getVectorOperand();
383 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
384 ConstantVector::get(ExtendMask));
386 // Replace all extracts from the original narrow vector with extracts from
387 // the new wide vector.
388 WideVec->insertBefore(ExtElt);
389 for (User *U : ExtVecOp->users()) {
390 if (ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U)) {
391 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
392 NewExt->insertAfter(WideVec);
393 IC.ReplaceInstUsesWith(*OldExt, NewExt);
398 /// We are building a shuffle to create V, which is a sequence of insertelement,
399 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
400 /// not rely on the second vector source. Return a std::pair containing the
401 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
402 /// parameter as required.
404 /// Note: we intentionally don't try to fold earlier shuffles since they have
405 /// often been chosen carefully to be efficiently implementable on the target.
406 typedef std::pair<Value *, Value *> ShuffleOps;
408 static ShuffleOps collectShuffleElements(Value *V,
409 SmallVectorImpl<Constant *> &Mask,
412 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
413 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
415 if (isa<UndefValue>(V)) {
416 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
417 return std::make_pair(
418 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
421 if (isa<ConstantAggregateZero>(V)) {
422 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
423 return std::make_pair(V, nullptr);
426 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
427 // If this is an insert of an extract from some other vector, include it.
428 Value *VecOp = IEI->getOperand(0);
429 Value *ScalarOp = IEI->getOperand(1);
430 Value *IdxOp = IEI->getOperand(2);
432 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
433 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
434 unsigned ExtractedIdx =
435 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
436 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
438 // Either the extracted from or inserted into vector must be RHSVec,
439 // otherwise we'd end up with a shuffle of three inputs.
440 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
441 Value *RHS = EI->getOperand(0);
442 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
443 assert(LR.second == nullptr || LR.second == RHS);
445 if (LR.first->getType() != RHS->getType()) {
446 // Although we are giving up for now, see if we can create extracts
447 // that match the inserts for another round of combining.
448 replaceExtractElements(IEI, EI, IC);
450 // We tried our best, but we can't find anything compatible with RHS
451 // further up the chain. Return a trivial shuffle.
452 for (unsigned i = 0; i < NumElts; ++i)
453 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
454 return std::make_pair(V, nullptr);
457 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
458 Mask[InsertedIdx % NumElts] =
459 ConstantInt::get(Type::getInt32Ty(V->getContext()),
460 NumLHSElts+ExtractedIdx);
461 return std::make_pair(LR.first, RHS);
464 if (VecOp == PermittedRHS) {
465 // We've gone as far as we can: anything on the other side of the
466 // extractelement will already have been converted into a shuffle.
467 unsigned NumLHSElts =
468 EI->getOperand(0)->getType()->getVectorNumElements();
469 for (unsigned i = 0; i != NumElts; ++i)
470 Mask.push_back(ConstantInt::get(
471 Type::getInt32Ty(V->getContext()),
472 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
473 return std::make_pair(EI->getOperand(0), PermittedRHS);
476 // If this insertelement is a chain that comes from exactly these two
477 // vectors, return the vector and the effective shuffle.
478 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
479 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
481 return std::make_pair(EI->getOperand(0), PermittedRHS);
486 // Otherwise, we can't do anything fancy. Return an identity vector.
487 for (unsigned i = 0; i != NumElts; ++i)
488 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
489 return std::make_pair(V, nullptr);
492 /// Try to find redundant insertvalue instructions, like the following ones:
493 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
494 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
495 /// Here the second instruction inserts values at the same indices, as the
496 /// first one, making the first one redundant.
497 /// It should be transformed to:
498 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
499 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
500 bool IsRedundant = false;
501 ArrayRef<unsigned int> FirstIndices = I.getIndices();
503 // If there is a chain of insertvalue instructions (each of them except the
504 // last one has only one use and it's another insertvalue insn from this
505 // chain), check if any of the 'children' uses the same indices as the first
506 // instruction. In this case, the first one is redundant.
509 while (V->hasOneUse() && Depth < 10) {
510 User *U = V->user_back();
511 auto UserInsInst = dyn_cast<InsertValueInst>(U);
512 if (!UserInsInst || U->getOperand(0) != V)
514 if (UserInsInst->getIndices() == FirstIndices) {
523 return ReplaceInstUsesWith(I, I.getOperand(0));
527 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
528 Value *VecOp = IE.getOperand(0);
529 Value *ScalarOp = IE.getOperand(1);
530 Value *IdxOp = IE.getOperand(2);
532 // Inserting an undef or into an undefined place, remove this.
533 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
534 ReplaceInstUsesWith(IE, VecOp);
536 // If the inserted element was extracted from some other vector, and if the
537 // indexes are constant, try to turn this into a shufflevector operation.
538 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
539 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
540 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
541 unsigned NumExtractVectorElts =
542 EI->getOperand(0)->getType()->getVectorNumElements();
543 unsigned ExtractedIdx =
544 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
545 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
547 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
548 return ReplaceInstUsesWith(IE, VecOp);
550 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
551 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
553 // If we are extracting a value from a vector, then inserting it right
554 // back into the same place, just use the input vector.
555 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
556 return ReplaceInstUsesWith(IE, VecOp);
558 // If this insertelement isn't used by some other insertelement, turn it
559 // (and any insertelements it points to), into one big shuffle.
560 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
561 SmallVector<Constant*, 16> Mask;
562 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
564 // The proposed shuffle may be trivial, in which case we shouldn't
565 // perform the combine.
566 if (LR.first != &IE && LR.second != &IE) {
567 // We now have a shuffle of LHS, RHS, Mask.
568 if (LR.second == nullptr)
569 LR.second = UndefValue::get(LR.first->getType());
570 return new ShuffleVectorInst(LR.first, LR.second,
571 ConstantVector::get(Mask));
577 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
578 APInt UndefElts(VWidth, 0);
579 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
580 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
582 return ReplaceInstUsesWith(IE, V);
589 /// Return true if we can evaluate the specified expression tree if the vector
590 /// elements were shuffled in a different order.
591 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
592 unsigned Depth = 5) {
593 // We can always reorder the elements of a constant.
594 if (isa<Constant>(V))
597 // We won't reorder vector arguments. No IPO here.
598 Instruction *I = dyn_cast<Instruction>(V);
599 if (!I) return false;
601 // Two users may expect different orders of the elements. Don't try it.
605 if (Depth == 0) return false;
607 switch (I->getOpcode()) {
608 case Instruction::Add:
609 case Instruction::FAdd:
610 case Instruction::Sub:
611 case Instruction::FSub:
612 case Instruction::Mul:
613 case Instruction::FMul:
614 case Instruction::UDiv:
615 case Instruction::SDiv:
616 case Instruction::FDiv:
617 case Instruction::URem:
618 case Instruction::SRem:
619 case Instruction::FRem:
620 case Instruction::Shl:
621 case Instruction::LShr:
622 case Instruction::AShr:
623 case Instruction::And:
624 case Instruction::Or:
625 case Instruction::Xor:
626 case Instruction::ICmp:
627 case Instruction::FCmp:
628 case Instruction::Trunc:
629 case Instruction::ZExt:
630 case Instruction::SExt:
631 case Instruction::FPToUI:
632 case Instruction::FPToSI:
633 case Instruction::UIToFP:
634 case Instruction::SIToFP:
635 case Instruction::FPTrunc:
636 case Instruction::FPExt:
637 case Instruction::GetElementPtr: {
638 for (Value *Operand : I->operands()) {
639 if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
644 case Instruction::InsertElement: {
645 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
646 if (!CI) return false;
647 int ElementNumber = CI->getLimitedValue();
649 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
650 // can't put an element into multiple indices.
651 bool SeenOnce = false;
652 for (int i = 0, e = Mask.size(); i != e; ++i) {
653 if (Mask[i] == ElementNumber) {
659 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
665 /// Rebuild a new instruction just like 'I' but with the new operands given.
666 /// In the event of type mismatch, the type of the operands is correct.
667 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
668 // We don't want to use the IRBuilder here because we want the replacement
669 // instructions to appear next to 'I', not the builder's insertion point.
670 switch (I->getOpcode()) {
671 case Instruction::Add:
672 case Instruction::FAdd:
673 case Instruction::Sub:
674 case Instruction::FSub:
675 case Instruction::Mul:
676 case Instruction::FMul:
677 case Instruction::UDiv:
678 case Instruction::SDiv:
679 case Instruction::FDiv:
680 case Instruction::URem:
681 case Instruction::SRem:
682 case Instruction::FRem:
683 case Instruction::Shl:
684 case Instruction::LShr:
685 case Instruction::AShr:
686 case Instruction::And:
687 case Instruction::Or:
688 case Instruction::Xor: {
689 BinaryOperator *BO = cast<BinaryOperator>(I);
690 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
691 BinaryOperator *New =
692 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
693 NewOps[0], NewOps[1], "", BO);
694 if (isa<OverflowingBinaryOperator>(BO)) {
695 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
696 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
698 if (isa<PossiblyExactOperator>(BO)) {
699 New->setIsExact(BO->isExact());
701 if (isa<FPMathOperator>(BO))
702 New->copyFastMathFlags(I);
705 case Instruction::ICmp:
706 assert(NewOps.size() == 2 && "icmp with #ops != 2");
707 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
708 NewOps[0], NewOps[1]);
709 case Instruction::FCmp:
710 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
711 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
712 NewOps[0], NewOps[1]);
713 case Instruction::Trunc:
714 case Instruction::ZExt:
715 case Instruction::SExt:
716 case Instruction::FPToUI:
717 case Instruction::FPToSI:
718 case Instruction::UIToFP:
719 case Instruction::SIToFP:
720 case Instruction::FPTrunc:
721 case Instruction::FPExt: {
722 // It's possible that the mask has a different number of elements from
723 // the original cast. We recompute the destination type to match the mask.
725 VectorType::get(I->getType()->getScalarType(),
726 NewOps[0]->getType()->getVectorNumElements());
727 assert(NewOps.size() == 1 && "cast with #ops != 1");
728 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
731 case Instruction::GetElementPtr: {
732 Value *Ptr = NewOps[0];
733 ArrayRef<Value*> Idx = NewOps.slice(1);
734 GetElementPtrInst *GEP = GetElementPtrInst::Create(
735 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
736 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
740 llvm_unreachable("failed to rebuild vector instructions");
744 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
745 // Mask.size() does not need to be equal to the number of vector elements.
747 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
748 if (isa<UndefValue>(V)) {
749 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
752 if (isa<ConstantAggregateZero>(V)) {
753 return ConstantAggregateZero::get(
754 VectorType::get(V->getType()->getScalarType(),
757 if (Constant *C = dyn_cast<Constant>(V)) {
758 SmallVector<Constant *, 16> MaskValues;
759 for (int i = 0, e = Mask.size(); i != e; ++i) {
761 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
763 MaskValues.push_back(Builder->getInt32(Mask[i]));
765 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
766 ConstantVector::get(MaskValues));
769 Instruction *I = cast<Instruction>(V);
770 switch (I->getOpcode()) {
771 case Instruction::Add:
772 case Instruction::FAdd:
773 case Instruction::Sub:
774 case Instruction::FSub:
775 case Instruction::Mul:
776 case Instruction::FMul:
777 case Instruction::UDiv:
778 case Instruction::SDiv:
779 case Instruction::FDiv:
780 case Instruction::URem:
781 case Instruction::SRem:
782 case Instruction::FRem:
783 case Instruction::Shl:
784 case Instruction::LShr:
785 case Instruction::AShr:
786 case Instruction::And:
787 case Instruction::Or:
788 case Instruction::Xor:
789 case Instruction::ICmp:
790 case Instruction::FCmp:
791 case Instruction::Trunc:
792 case Instruction::ZExt:
793 case Instruction::SExt:
794 case Instruction::FPToUI:
795 case Instruction::FPToSI:
796 case Instruction::UIToFP:
797 case Instruction::SIToFP:
798 case Instruction::FPTrunc:
799 case Instruction::FPExt:
800 case Instruction::Select:
801 case Instruction::GetElementPtr: {
802 SmallVector<Value*, 8> NewOps;
803 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
804 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
805 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
807 NeedsRebuild |= (V != I->getOperand(i));
810 return buildNew(I, NewOps);
814 case Instruction::InsertElement: {
815 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
817 // The insertelement was inserting at Element. Figure out which element
818 // that becomes after shuffling. The answer is guaranteed to be unique
819 // by CanEvaluateShuffled.
822 for (int e = Mask.size(); Index != e; ++Index) {
823 if (Mask[Index] == Element) {
829 // If element is not in Mask, no need to handle the operand 1 (element to
830 // be inserted). Just evaluate values in operand 0 according to Mask.
832 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
834 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
835 return InsertElementInst::Create(V, I->getOperand(1),
836 Builder->getInt32(Index), "", I);
839 llvm_unreachable("failed to reorder elements of vector instruction!");
842 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
843 bool &isLHSID, bool &isRHSID) {
844 isLHSID = isRHSID = true;
846 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
847 if (Mask[i] < 0) continue; // Ignore undef values.
848 // Is this an identity shuffle of the LHS value?
849 isLHSID &= (Mask[i] == (int)i);
851 // Is this an identity shuffle of the RHS value?
852 isRHSID &= (Mask[i]-e == i);
856 // Returns true if the shuffle is extracting a contiguous range of values from
858 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
859 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
860 // Shuffles to: |EE|FF|GG|HH|
862 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
863 SmallVector<int, 16> &Mask) {
865 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
866 unsigned MaskElems = Mask.size();
867 unsigned BegIdx = Mask.front();
868 unsigned EndIdx = Mask.back();
869 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
871 for (unsigned I = 0; I != MaskElems; ++I)
872 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
877 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
878 Value *LHS = SVI.getOperand(0);
879 Value *RHS = SVI.getOperand(1);
880 SmallVector<int, 16> Mask = SVI.getShuffleMask();
881 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
883 bool MadeChange = false;
885 // Undefined shuffle mask -> undefined value.
886 if (isa<UndefValue>(SVI.getOperand(2)))
887 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
889 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
891 APInt UndefElts(VWidth, 0);
892 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
893 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
895 return ReplaceInstUsesWith(SVI, V);
896 LHS = SVI.getOperand(0);
897 RHS = SVI.getOperand(1);
901 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
903 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
904 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
905 if (LHS == RHS || isa<UndefValue>(LHS)) {
906 if (isa<UndefValue>(LHS) && LHS == RHS) {
907 // shuffle(undef,undef,mask) -> undef.
908 Value *Result = (VWidth == LHSWidth)
909 ? LHS : UndefValue::get(SVI.getType());
910 return ReplaceInstUsesWith(SVI, Result);
913 // Remap any references to RHS to use LHS.
914 SmallVector<Constant*, 16> Elts;
915 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
917 Elts.push_back(UndefValue::get(Int32Ty));
921 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
922 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
923 Mask[i] = -1; // Turn into undef.
924 Elts.push_back(UndefValue::get(Int32Ty));
926 Mask[i] = Mask[i] % e; // Force to LHS.
927 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
930 SVI.setOperand(0, SVI.getOperand(1));
931 SVI.setOperand(1, UndefValue::get(RHS->getType()));
932 SVI.setOperand(2, ConstantVector::get(Elts));
933 LHS = SVI.getOperand(0);
934 RHS = SVI.getOperand(1);
938 if (VWidth == LHSWidth) {
939 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
940 bool isLHSID, isRHSID;
941 recognizeIdentityMask(Mask, isLHSID, isRHSID);
943 // Eliminate identity shuffles.
944 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
945 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
948 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
949 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
950 return ReplaceInstUsesWith(SVI, V);
953 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
954 // a non-vector type. We can instead bitcast the original vector followed by
955 // an extract of the desired element:
957 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
958 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
959 // %1 = bitcast <4 x i8> %sroa to i32
961 // %bc = bitcast <16 x i8> %in to <4 x i32>
962 // %ext = extractelement <4 x i32> %bc, i32 0
964 // If the shuffle is extracting a contiguous range of values from the input
965 // vector then each use which is a bitcast of the extracted size can be
966 // replaced. This will work if the vector types are compatible, and the begin
967 // index is aligned to a value in the casted vector type. If the begin index
968 // isn't aligned then we can shuffle the original vector (keeping the same
969 // vector type) before extracting.
971 // This code will bail out if the target type is fundamentally incompatible
972 // with vectors of the source type.
974 // Example of <16 x i8>, target type i32:
975 // Index range [4,8): v-----------v Will work.
976 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
977 // <16 x i8>: | | | | | | | | | | | | | | | | |
978 // <4 x i32>: | | | | |
979 // +-----------+-----------+-----------+-----------+
980 // Index range [6,10): ^-----------^ Needs an extra shuffle.
981 // Target type i40: ^--------------^ Won't work, bail.
982 if (isShuffleExtractingFromLHS(SVI, Mask)) {
984 unsigned MaskElems = Mask.size();
985 unsigned BegIdx = Mask.front();
986 VectorType *SrcTy = cast<VectorType>(V->getType());
987 unsigned VecBitWidth = SrcTy->getBitWidth();
988 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
989 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
990 unsigned SrcNumElems = SrcTy->getNumElements();
991 SmallVector<BitCastInst *, 8> BCs;
992 DenseMap<Type *, Value *> NewBCs;
993 for (User *U : SVI.users())
994 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
995 if (!BC->use_empty())
996 // Only visit bitcasts that weren't previously handled.
998 for (BitCastInst *BC : BCs) {
999 Type *TgtTy = BC->getDestTy();
1000 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1001 if (!TgtElemBitWidth)
1003 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1004 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1005 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1006 if (!VecBitWidthsEqual)
1008 if (!VectorType::isValidElementType(TgtTy))
1010 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1011 if (!BegIsAligned) {
1012 // Shuffle the input so [0,NumElements) contains the output, and
1013 // [NumElems,SrcNumElems) is undef.
1014 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1015 UndefValue::get(Int32Ty));
1016 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1017 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1018 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1019 ConstantVector::get(ShuffleMask),
1020 SVI.getName() + ".extract");
1023 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1024 assert(SrcElemsPerTgtElem);
1025 BegIdx /= SrcElemsPerTgtElem;
1026 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1030 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1031 if (!BCAlreadyExists)
1032 NewBCs[CastSrcTy] = NewBC;
1033 auto *Ext = Builder->CreateExtractElement(
1034 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1035 // The shufflevector isn't being replaced: the bitcast that used it
1036 // is. InstCombine will visit the newly-created instructions.
1037 ReplaceInstUsesWith(*BC, Ext);
1042 // If the LHS is a shufflevector itself, see if we can combine it with this
1043 // one without producing an unusual shuffle.
1044 // Cases that might be simplified:
1046 // x1=shuffle(v1,v2,mask1)
1047 // x=shuffle(x1,undef,mask)
1049 // x=shuffle(v1,undef,newMask)
1050 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1052 // x1=shuffle(v1,undef,mask1)
1053 // x=shuffle(x1,x2,mask)
1054 // where v1.size() == mask1.size()
1056 // x=shuffle(v1,x2,newMask)
1057 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1059 // x2=shuffle(v2,undef,mask2)
1060 // x=shuffle(x1,x2,mask)
1061 // where v2.size() == mask2.size()
1063 // x=shuffle(x1,v2,newMask)
1064 // newMask[i] = (mask[i] < x1.size())
1065 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1067 // x1=shuffle(v1,undef,mask1)
1068 // x2=shuffle(v2,undef,mask2)
1069 // x=shuffle(x1,x2,mask)
1070 // where v1.size() == v2.size()
1072 // x=shuffle(v1,v2,newMask)
1073 // newMask[i] = (mask[i] < x1.size())
1074 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1076 // Here we are really conservative:
1077 // we are absolutely afraid of producing a shuffle mask not in the input
1078 // program, because the code gen may not be smart enough to turn a merged
1079 // shuffle into two specific shuffles: it may produce worse code. As such,
1080 // we only merge two shuffles if the result is either a splat or one of the
1081 // input shuffle masks. In this case, merging the shuffles just removes
1082 // one instruction, which we know is safe. This is good for things like
1083 // turning: (splat(splat)) -> splat, or
1084 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1085 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1086 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1088 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
1089 LHSShuffle = nullptr;
1091 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
1092 RHSShuffle = nullptr;
1093 if (!LHSShuffle && !RHSShuffle)
1094 return MadeChange ? &SVI : nullptr;
1096 Value* LHSOp0 = nullptr;
1097 Value* LHSOp1 = nullptr;
1098 Value* RHSOp0 = nullptr;
1099 unsigned LHSOp0Width = 0;
1100 unsigned RHSOp0Width = 0;
1102 LHSOp0 = LHSShuffle->getOperand(0);
1103 LHSOp1 = LHSShuffle->getOperand(1);
1104 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1107 RHSOp0 = RHSShuffle->getOperand(0);
1108 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1110 Value* newLHS = LHS;
1111 Value* newRHS = RHS;
1114 if (isa<UndefValue>(RHS)) {
1119 else if (LHSOp0Width == LHSWidth) {
1124 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1128 if (LHSOp0 == RHSOp0) {
1133 if (newLHS == LHS && newRHS == RHS)
1134 return MadeChange ? &SVI : nullptr;
1136 SmallVector<int, 16> LHSMask;
1137 SmallVector<int, 16> RHSMask;
1139 LHSMask = LHSShuffle->getShuffleMask();
1140 if (RHSShuffle && newRHS != RHS)
1141 RHSMask = RHSShuffle->getShuffleMask();
1143 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1144 SmallVector<int, 16> newMask;
1145 bool isSplat = true;
1147 // Create a new mask for the new ShuffleVectorInst so that the new
1148 // ShuffleVectorInst is equivalent to the original one.
1149 for (unsigned i = 0; i < VWidth; ++i) {
1152 // This element is an undef value.
1154 } else if (Mask[i] < (int)LHSWidth) {
1155 // This element is from left hand side vector operand.
1157 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1158 // new mask value for the element.
1159 if (newLHS != LHS) {
1160 eltMask = LHSMask[Mask[i]];
1161 // If the value selected is an undef value, explicitly specify it
1162 // with a -1 mask value.
1163 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1168 // This element is from right hand side vector operand
1170 // If the value selected is an undef value, explicitly specify it
1171 // with a -1 mask value. (case 1)
1172 if (isa<UndefValue>(RHS))
1174 // If RHS is going to be replaced (case 3 or 4), calculate the
1175 // new mask value for the element.
1176 else if (newRHS != RHS) {
1177 eltMask = RHSMask[Mask[i]-LHSWidth];
1178 // If the value selected is an undef value, explicitly specify it
1179 // with a -1 mask value.
1180 if (eltMask >= (int)RHSOp0Width) {
1181 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1182 && "should have been check above");
1186 eltMask = Mask[i]-LHSWidth;
1188 // If LHS's width is changed, shift the mask value accordingly.
1189 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1190 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1191 // If newRHS == newLHS, we want to remap any references from newRHS to
1192 // newLHS so that we can properly identify splats that may occur due to
1193 // obfuscation across the two vectors.
1194 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1195 eltMask += newLHSWidth;
1198 // Check if this could still be a splat.
1200 if (SplatElt >= 0 && SplatElt != eltMask)
1205 newMask.push_back(eltMask);
1208 // If the result mask is equal to one of the original shuffle masks,
1209 // or is a splat, do the replacement.
1210 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1211 SmallVector<Constant*, 16> Elts;
1212 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1213 if (newMask[i] < 0) {
1214 Elts.push_back(UndefValue::get(Int32Ty));
1216 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1220 newRHS = UndefValue::get(newLHS->getType());
1221 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1224 // If the result mask is an identity, replace uses of this instruction with
1225 // corresponding argument.
1226 bool isLHSID, isRHSID;
1227 recognizeIdentityMask(newMask, isLHSID, isRHSID);
1228 if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1229 if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
1231 return MadeChange ? &SVI : nullptr;