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 is only used to 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 SmallVector<Instruction *, 2> Extracts;
70 // The users we want the PHI to have are:
71 // 1) The EI ExtractElement (we already know this)
72 // 2) Possibly more ExtractElements with the same index.
73 // 3) Another operand, which will feed back into the PHI.
74 Instruction *PHIUser = nullptr;
75 for (auto U : PN->users()) {
76 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
77 if (EI.getIndexOperand() == EU->getIndexOperand())
78 Extracts.push_back(EU);
81 } else if (!PHIUser) {
82 PHIUser = cast<Instruction>(U);
91 // Verify that this PHI user has one use, which is the PHI itself,
92 // and that it is a binary operation which is cheap to scalarize.
93 // otherwise return NULL.
94 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
95 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
98 // Create a scalar PHI node that will replace the vector PHI node
99 // just before the current PHI node.
100 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
101 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
102 // Scalarize each PHI operand.
103 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
104 Value *PHIInVal = PN->getIncomingValue(i);
105 BasicBlock *inBB = PN->getIncomingBlock(i);
106 Value *Elt = EI.getIndexOperand();
107 // If the operand is the PHI induction variable:
108 if (PHIInVal == PHIUser) {
109 // Scalarize the binary operation. Its first operand is the
110 // scalar PHI, and the second operand is extracted from the other
112 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
113 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
114 Value *Op = InsertNewInstWith(
115 ExtractElementInst::Create(B0->getOperand(opId), Elt,
116 B0->getOperand(opId)->getName() + ".Elt"),
118 Value *newPHIUser = InsertNewInstWith(
119 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
120 scalarPHI, Op, B0), *B0);
121 scalarPHI->addIncoming(newPHIUser, inBB);
123 // Scalarize PHI input:
124 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
125 // Insert the new instruction into the predecessor basic block.
126 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
127 BasicBlock::iterator InsertPos;
128 if (pos && !isa<PHINode>(pos)) {
129 InsertPos = ++pos->getIterator();
131 InsertPos = inBB->getFirstInsertionPt();
134 InsertNewInstWith(newEI, *InsertPos);
136 scalarPHI->addIncoming(newEI, inBB);
140 for (auto E : Extracts)
141 replaceInstUsesWith(*E, scalarPHI);
146 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
147 if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(),
148 EI.getIndexOperand(), SQ))
149 return replaceInstUsesWith(EI, V);
151 // If vector val is constant with all elements the same, replace EI with
152 // that element. We handle a known element # below.
153 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
154 if (cheapToScalarize(C, false))
155 return replaceInstUsesWith(EI, C->getAggregateElement(0U));
157 // If extracting a specified index from the vector, see if we can recursively
158 // find a previously computed scalar that was inserted into the vector.
159 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
160 unsigned IndexVal = IdxC->getZExtValue();
161 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
163 // InstSimplify handles cases where the index is invalid.
164 assert(IndexVal < VectorWidth);
166 // This instruction only demands the single element from the input vector.
167 // If the input vector has a single use, simplify it based on this use
169 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
170 APInt UndefElts(VectorWidth, 0);
171 APInt DemandedMask(VectorWidth, 0);
172 DemandedMask.setBit(IndexVal);
173 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
180 // If this extractelement is directly using a bitcast from a vector of
181 // the same number of elements, see if we can find the source element from
182 // it. In this case, we will end up needing to bitcast the scalars.
183 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
184 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
185 if (VT->getNumElements() == VectorWidth)
186 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
187 return new BitCastInst(Elt, EI.getType());
190 // If there's a vector PHI feeding a scalar use through this extractelement
191 // instruction, try to scalarize the PHI.
192 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
193 Instruction *scalarPHI = scalarizePHI(EI, PN);
199 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
200 // Push extractelement into predecessor operation if legal and
201 // profitable to do so.
202 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
203 if (I->hasOneUse() &&
204 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
206 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
207 EI.getName()+".lhs");
209 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
210 EI.getName()+".rhs");
211 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
214 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
215 // Extracting the inserted element?
216 if (IE->getOperand(2) == EI.getOperand(1))
217 return replaceInstUsesWith(EI, IE->getOperand(1));
218 // If the inserted and extracted elements are constants, they must not
219 // be the same value, extract from the pre-inserted value instead.
220 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
221 Worklist.AddValue(EI.getOperand(0));
222 EI.setOperand(0, IE->getOperand(0));
225 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
226 // If this is extracting an element from a shufflevector, figure out where
227 // it came from and extract from the appropriate input element instead.
228 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
229 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
232 SVI->getOperand(0)->getType()->getVectorNumElements();
235 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
236 if (SrcIdx < (int)LHSWidth)
237 Src = SVI->getOperand(0);
240 Src = SVI->getOperand(1);
242 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
243 return ExtractElementInst::Create(Src,
244 ConstantInt::get(Int32Ty,
247 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
248 // Canonicalize extractelement(cast) -> cast(extractelement).
249 // Bitcasts can change the number of vector elements, and they cost
251 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
252 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
253 EI.getIndexOperand());
254 Worklist.AddValue(EE);
255 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
257 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
258 if (SI->hasOneUse()) {
259 // TODO: For a select on vectors, it might be useful to do this if it
260 // has multiple extractelement uses. For vector select, that seems to
261 // fight the vectorizer.
263 // If we are extracting an element from a vector select or a select on
264 // vectors, create a select on the scalars extracted from the vector
266 Value *TrueVal = SI->getTrueValue();
267 Value *FalseVal = SI->getFalseValue();
269 Value *Cond = SI->getCondition();
270 if (Cond->getType()->isVectorTy()) {
271 Cond = Builder->CreateExtractElement(Cond,
272 EI.getIndexOperand(),
273 Cond->getName() + ".elt");
277 = Builder->CreateExtractElement(TrueVal,
278 EI.getIndexOperand(),
279 TrueVal->getName() + ".elt");
282 = Builder->CreateExtractElement(FalseVal,
283 EI.getIndexOperand(),
284 FalseVal->getName() + ".elt");
285 return SelectInst::Create(Cond,
288 SI->getName() + ".elt");
295 /// If V is a shuffle of values that ONLY returns elements from either LHS or
296 /// RHS, return the shuffle mask and true. Otherwise, return false.
297 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
298 SmallVectorImpl<Constant*> &Mask) {
299 assert(LHS->getType() == RHS->getType() &&
300 "Invalid CollectSingleShuffleElements");
301 unsigned NumElts = V->getType()->getVectorNumElements();
303 if (isa<UndefValue>(V)) {
304 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
309 for (unsigned i = 0; i != NumElts; ++i)
310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
315 for (unsigned i = 0; i != NumElts; ++i)
316 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
321 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
322 // If this is an insert of an extract from some other vector, include it.
323 Value *VecOp = IEI->getOperand(0);
324 Value *ScalarOp = IEI->getOperand(1);
325 Value *IdxOp = IEI->getOperand(2);
327 if (!isa<ConstantInt>(IdxOp))
329 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
331 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
332 // We can handle this if the vector we are inserting into is
334 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
335 // If so, update the mask to reflect the inserted undef.
336 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
339 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
340 if (isa<ConstantInt>(EI->getOperand(1))) {
341 unsigned ExtractedIdx =
342 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
343 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
345 // This must be extracting from either LHS or RHS.
346 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
347 // We can handle this if the vector we are inserting into is
349 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
350 // If so, update the mask to reflect the inserted value.
351 if (EI->getOperand(0) == LHS) {
352 Mask[InsertedIdx % NumElts] =
353 ConstantInt::get(Type::getInt32Ty(V->getContext()),
356 assert(EI->getOperand(0) == RHS);
357 Mask[InsertedIdx % NumElts] =
358 ConstantInt::get(Type::getInt32Ty(V->getContext()),
359 ExtractedIdx + NumLHSElts);
371 /// If we have insertion into a vector that is wider than the vector that we
372 /// are extracting from, try to widen the source vector to allow a single
373 /// shufflevector to replace one or more insert/extract pairs.
374 static void replaceExtractElements(InsertElementInst *InsElt,
375 ExtractElementInst *ExtElt,
377 VectorType *InsVecType = InsElt->getType();
378 VectorType *ExtVecType = ExtElt->getVectorOperandType();
379 unsigned NumInsElts = InsVecType->getVectorNumElements();
380 unsigned NumExtElts = ExtVecType->getVectorNumElements();
382 // The inserted-to vector must be wider than the extracted-from vector.
383 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
384 NumExtElts >= NumInsElts)
387 // Create a shuffle mask to widen the extended-from vector using undefined
388 // values. The mask selects all of the values of the original vector followed
389 // by as many undefined values as needed to create a vector of the same length
390 // as the inserted-to vector.
391 SmallVector<Constant *, 16> ExtendMask;
392 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
393 for (unsigned i = 0; i < NumExtElts; ++i)
394 ExtendMask.push_back(ConstantInt::get(IntType, i));
395 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
396 ExtendMask.push_back(UndefValue::get(IntType));
398 Value *ExtVecOp = ExtElt->getVectorOperand();
399 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
400 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
401 ? ExtVecOpInst->getParent()
402 : ExtElt->getParent();
404 // TODO: This restriction matches the basic block check below when creating
405 // new extractelement instructions. If that limitation is removed, this one
406 // could also be removed. But for now, we just bail out to ensure that we
407 // will replace the extractelement instruction that is feeding our
408 // insertelement instruction. This allows the insertelement to then be
409 // replaced by a shufflevector. If the insertelement is not replaced, we can
410 // induce infinite looping because there's an optimization for extractelement
411 // that will delete our widening shuffle. This would trigger another attempt
412 // here to create that shuffle, and we spin forever.
413 if (InsertionBlock != InsElt->getParent())
416 // TODO: This restriction matches the check in visitInsertElementInst() and
417 // prevents an infinite loop caused by not turning the extract/insert pair
418 // into a shuffle. We really should not need either check, but we're lacking
419 // folds for shufflevectors because we're afraid to generate shuffle masks
420 // that the backend can't handle.
421 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
424 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
425 ConstantVector::get(ExtendMask));
427 // Insert the new shuffle after the vector operand of the extract is defined
428 // (as long as it's not a PHI) or at the start of the basic block of the
429 // extract, so any subsequent extracts in the same basic block can use it.
430 // TODO: Insert before the earliest ExtractElementInst that is replaced.
431 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
432 WideVec->insertAfter(ExtVecOpInst);
434 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
436 // Replace extracts from the original narrow vector with extracts from the new
438 for (User *U : ExtVecOp->users()) {
439 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
440 if (!OldExt || OldExt->getParent() != WideVec->getParent())
442 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
443 NewExt->insertAfter(WideVec);
444 IC.replaceInstUsesWith(*OldExt, NewExt);
448 /// We are building a shuffle to create V, which is a sequence of insertelement,
449 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
450 /// not rely on the second vector source. Return a std::pair containing the
451 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
452 /// parameter as required.
454 /// Note: we intentionally don't try to fold earlier shuffles since they have
455 /// often been chosen carefully to be efficiently implementable on the target.
456 typedef std::pair<Value *, Value *> ShuffleOps;
458 static ShuffleOps collectShuffleElements(Value *V,
459 SmallVectorImpl<Constant *> &Mask,
462 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
463 unsigned NumElts = V->getType()->getVectorNumElements();
465 if (isa<UndefValue>(V)) {
466 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
467 return std::make_pair(
468 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
471 if (isa<ConstantAggregateZero>(V)) {
472 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
473 return std::make_pair(V, nullptr);
476 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
477 // If this is an insert of an extract from some other vector, include it.
478 Value *VecOp = IEI->getOperand(0);
479 Value *ScalarOp = IEI->getOperand(1);
480 Value *IdxOp = IEI->getOperand(2);
482 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
483 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
484 unsigned ExtractedIdx =
485 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
486 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
488 // Either the extracted from or inserted into vector must be RHSVec,
489 // otherwise we'd end up with a shuffle of three inputs.
490 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
491 Value *RHS = EI->getOperand(0);
492 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
493 assert(LR.second == nullptr || LR.second == RHS);
495 if (LR.first->getType() != RHS->getType()) {
496 // Although we are giving up for now, see if we can create extracts
497 // that match the inserts for another round of combining.
498 replaceExtractElements(IEI, EI, IC);
500 // We tried our best, but we can't find anything compatible with RHS
501 // further up the chain. Return a trivial shuffle.
502 for (unsigned i = 0; i < NumElts; ++i)
503 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
504 return std::make_pair(V, nullptr);
507 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
508 Mask[InsertedIdx % NumElts] =
509 ConstantInt::get(Type::getInt32Ty(V->getContext()),
510 NumLHSElts+ExtractedIdx);
511 return std::make_pair(LR.first, RHS);
514 if (VecOp == PermittedRHS) {
515 // We've gone as far as we can: anything on the other side of the
516 // extractelement will already have been converted into a shuffle.
517 unsigned NumLHSElts =
518 EI->getOperand(0)->getType()->getVectorNumElements();
519 for (unsigned i = 0; i != NumElts; ++i)
520 Mask.push_back(ConstantInt::get(
521 Type::getInt32Ty(V->getContext()),
522 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
523 return std::make_pair(EI->getOperand(0), PermittedRHS);
526 // If this insertelement is a chain that comes from exactly these two
527 // vectors, return the vector and the effective shuffle.
528 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
529 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
531 return std::make_pair(EI->getOperand(0), PermittedRHS);
536 // Otherwise, we can't do anything fancy. Return an identity vector.
537 for (unsigned i = 0; i != NumElts; ++i)
538 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
539 return std::make_pair(V, nullptr);
542 /// Try to find redundant insertvalue instructions, like the following ones:
543 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
544 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
545 /// Here the second instruction inserts values at the same indices, as the
546 /// first one, making the first one redundant.
547 /// It should be transformed to:
548 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
549 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
550 bool IsRedundant = false;
551 ArrayRef<unsigned int> FirstIndices = I.getIndices();
553 // If there is a chain of insertvalue instructions (each of them except the
554 // last one has only one use and it's another insertvalue insn from this
555 // chain), check if any of the 'children' uses the same indices as the first
556 // instruction. In this case, the first one is redundant.
559 while (V->hasOneUse() && Depth < 10) {
560 User *U = V->user_back();
561 auto UserInsInst = dyn_cast<InsertValueInst>(U);
562 if (!UserInsInst || U->getOperand(0) != V)
564 if (UserInsInst->getIndices() == FirstIndices) {
573 return replaceInstUsesWith(I, I.getOperand(0));
577 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
578 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
579 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
581 // A vector select does not change the size of the operands.
582 if (MaskSize != VecSize)
585 // Each mask element must be undefined or choose a vector element from one of
586 // the source operands without crossing vector lanes.
587 for (int i = 0; i != MaskSize; ++i) {
588 int Elt = Shuf.getMaskValue(i);
589 if (Elt != -1 && Elt != i && Elt != i + VecSize)
596 // Turn a chain of inserts that splats a value into a canonical insert + shuffle
598 // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
599 // shufflevector(insertelt(X, %k, 0), undef, zero)
600 static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
601 // We are interested in the last insert in a chain. So, if this insert
602 // has a single user, and that user is an insert, bail.
603 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
606 VectorType *VT = cast<VectorType>(InsElt.getType());
607 int NumElements = VT->getNumElements();
609 // Do not try to do this for a one-element vector, since that's a nop,
610 // and will cause an inf-loop.
611 if (NumElements == 1)
614 Value *SplatVal = InsElt.getOperand(1);
615 InsertElementInst *CurrIE = &InsElt;
616 SmallVector<bool, 16> ElementPresent(NumElements, false);
618 // Walk the chain backwards, keeping track of which indices we inserted into,
619 // until we hit something that isn't an insert of the splatted value.
621 ConstantInt *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
622 if (!Idx || CurrIE->getOperand(1) != SplatVal)
625 // Check none of the intermediate steps have any additional uses.
626 if ((CurrIE != &InsElt) && !CurrIE->hasOneUse())
629 ElementPresent[Idx->getZExtValue()] = true;
630 CurrIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
633 // Make sure we've seen an insert into every element.
634 if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
637 // All right, create the insert + shuffle.
638 Instruction *InsertFirst = InsertElementInst::Create(
639 UndefValue::get(VT), SplatVal,
640 ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), "", &InsElt);
642 Constant *ZeroMask = ConstantAggregateZero::get(
643 VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
645 return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
648 /// If we have an insertelement instruction feeding into another insertelement
649 /// and the 2nd is inserting a constant into the vector, canonicalize that
650 /// constant insertion before the insertion of a variable:
652 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
653 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
655 /// This has the potential of eliminating the 2nd insertelement instruction
656 /// via constant folding of the scalar constant into a vector constant.
657 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
658 InstCombiner::BuilderTy &Builder) {
659 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
660 if (!InsElt1 || !InsElt1->hasOneUse())
665 ConstantInt *IdxC1, *IdxC2;
666 if (match(InsElt1->getOperand(0), m_Value(X)) &&
667 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
668 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
669 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
670 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
671 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
672 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
678 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
679 /// --> shufflevector X, CVec', Mask'
680 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
681 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
682 // Bail out if the parent has more than one use. In that case, we'd be
683 // replacing the insertelt with a shuffle, and that's not a clear win.
684 if (!Inst || !Inst->hasOneUse())
686 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
687 // The shuffle must have a constant vector operand. The insertelt must have
688 // a constant scalar being inserted at a constant position in the vector.
689 Constant *ShufConstVec, *InsEltScalar;
690 uint64_t InsEltIndex;
691 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
692 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
693 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
696 // Adding an element to an arbitrary shuffle could be expensive, but a
697 // shuffle that selects elements from vectors without crossing lanes is
699 // If we're just adding a constant into that shuffle, it will still be
701 if (!isShuffleEquivalentToSelect(*Shuf))
704 // From the above 'select' check, we know that the mask has the same number
705 // of elements as the vector input operands. We also know that each constant
706 // input element is used in its lane and can not be used more than once by
707 // the shuffle. Therefore, replace the constant in the shuffle's constant
708 // vector with the insertelt constant. Replace the constant in the shuffle's
709 // mask vector with the insertelt index plus the length of the vector
710 // (because the constant vector operand of a shuffle is always the 2nd
712 Constant *Mask = Shuf->getMask();
713 unsigned NumElts = Mask->getType()->getVectorNumElements();
714 SmallVector<Constant *, 16> NewShufElts(NumElts);
715 SmallVector<Constant *, 16> NewMaskElts(NumElts);
716 for (unsigned I = 0; I != NumElts; ++I) {
717 if (I == InsEltIndex) {
718 NewShufElts[I] = InsEltScalar;
719 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
720 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
722 // Copy over the existing values.
723 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
724 NewMaskElts[I] = Mask->getAggregateElement(I);
728 // Create new operands for a shuffle that includes the constant of the
729 // original insertelt. The old shuffle will be dead now.
730 return new ShuffleVectorInst(Shuf->getOperand(0),
731 ConstantVector::get(NewShufElts),
732 ConstantVector::get(NewMaskElts));
733 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
734 // Transform sequences of insertelements ops with constant data/indexes into
735 // a single shuffle op.
736 unsigned NumElts = InsElt.getType()->getNumElements();
738 uint64_t InsertIdx[2];
740 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
741 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
742 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
743 !match(IEI->getOperand(1), m_Constant(Val[1])))
745 SmallVector<Constant *, 16> Values(NumElts);
746 SmallVector<Constant *, 16> Mask(NumElts);
747 auto ValI = std::begin(Val);
748 // Generate new constant vector and mask.
749 // We have 2 values/masks from the insertelements instructions. Insert them
750 // into new value/mask vectors.
751 for (uint64_t I : InsertIdx) {
755 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
760 // Remaining values are filled with 'undef' values.
761 for (unsigned I = 0; I < NumElts; ++I) {
764 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
765 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
768 // Create new operands for a shuffle that includes the constant of the
769 // original insertelt.
770 return new ShuffleVectorInst(IEI->getOperand(0),
771 ConstantVector::get(Values),
772 ConstantVector::get(Mask));
777 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
778 Value *VecOp = IE.getOperand(0);
779 Value *ScalarOp = IE.getOperand(1);
780 Value *IdxOp = IE.getOperand(2);
782 // Inserting an undef or into an undefined place, remove this.
783 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
784 replaceInstUsesWith(IE, VecOp);
786 // If the inserted element was extracted from some other vector, and if the
787 // indexes are constant, try to turn this into a shufflevector operation.
788 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
789 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
790 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
791 unsigned NumExtractVectorElts =
792 EI->getOperand(0)->getType()->getVectorNumElements();
793 unsigned ExtractedIdx =
794 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
795 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
797 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
798 return replaceInstUsesWith(IE, VecOp);
800 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
801 return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
803 // If we are extracting a value from a vector, then inserting it right
804 // back into the same place, just use the input vector.
805 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
806 return replaceInstUsesWith(IE, VecOp);
808 // If this insertelement isn't used by some other insertelement, turn it
809 // (and any insertelements it points to), into one big shuffle.
810 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
811 SmallVector<Constant*, 16> Mask;
812 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
814 // The proposed shuffle may be trivial, in which case we shouldn't
815 // perform the combine.
816 if (LR.first != &IE && LR.second != &IE) {
817 // We now have a shuffle of LHS, RHS, Mask.
818 if (LR.second == nullptr)
819 LR.second = UndefValue::get(LR.first->getType());
820 return new ShuffleVectorInst(LR.first, LR.second,
821 ConstantVector::get(Mask));
827 unsigned VWidth = VecOp->getType()->getVectorNumElements();
828 APInt UndefElts(VWidth, 0);
829 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
830 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
832 return replaceInstUsesWith(IE, V);
836 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
839 if (Instruction *NewInsElt = hoistInsEltConst(IE, *Builder))
842 // Turn a sequence of inserts that broadcasts a scalar into a single
843 // insert + shufflevector.
844 if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
850 /// Return true if we can evaluate the specified expression tree if the vector
851 /// elements were shuffled in a different order.
852 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
853 unsigned Depth = 5) {
854 // We can always reorder the elements of a constant.
855 if (isa<Constant>(V))
858 // We won't reorder vector arguments. No IPO here.
859 Instruction *I = dyn_cast<Instruction>(V);
860 if (!I) return false;
862 // Two users may expect different orders of the elements. Don't try it.
866 if (Depth == 0) return false;
868 switch (I->getOpcode()) {
869 case Instruction::Add:
870 case Instruction::FAdd:
871 case Instruction::Sub:
872 case Instruction::FSub:
873 case Instruction::Mul:
874 case Instruction::FMul:
875 case Instruction::UDiv:
876 case Instruction::SDiv:
877 case Instruction::FDiv:
878 case Instruction::URem:
879 case Instruction::SRem:
880 case Instruction::FRem:
881 case Instruction::Shl:
882 case Instruction::LShr:
883 case Instruction::AShr:
884 case Instruction::And:
885 case Instruction::Or:
886 case Instruction::Xor:
887 case Instruction::ICmp:
888 case Instruction::FCmp:
889 case Instruction::Trunc:
890 case Instruction::ZExt:
891 case Instruction::SExt:
892 case Instruction::FPToUI:
893 case Instruction::FPToSI:
894 case Instruction::UIToFP:
895 case Instruction::SIToFP:
896 case Instruction::FPTrunc:
897 case Instruction::FPExt:
898 case Instruction::GetElementPtr: {
899 for (Value *Operand : I->operands()) {
900 if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
905 case Instruction::InsertElement: {
906 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
907 if (!CI) return false;
908 int ElementNumber = CI->getLimitedValue();
910 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
911 // can't put an element into multiple indices.
912 bool SeenOnce = false;
913 for (int i = 0, e = Mask.size(); i != e; ++i) {
914 if (Mask[i] == ElementNumber) {
920 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
926 /// Rebuild a new instruction just like 'I' but with the new operands given.
927 /// In the event of type mismatch, the type of the operands is correct.
928 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
929 // We don't want to use the IRBuilder here because we want the replacement
930 // instructions to appear next to 'I', not the builder's insertion point.
931 switch (I->getOpcode()) {
932 case Instruction::Add:
933 case Instruction::FAdd:
934 case Instruction::Sub:
935 case Instruction::FSub:
936 case Instruction::Mul:
937 case Instruction::FMul:
938 case Instruction::UDiv:
939 case Instruction::SDiv:
940 case Instruction::FDiv:
941 case Instruction::URem:
942 case Instruction::SRem:
943 case Instruction::FRem:
944 case Instruction::Shl:
945 case Instruction::LShr:
946 case Instruction::AShr:
947 case Instruction::And:
948 case Instruction::Or:
949 case Instruction::Xor: {
950 BinaryOperator *BO = cast<BinaryOperator>(I);
951 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
952 BinaryOperator *New =
953 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
954 NewOps[0], NewOps[1], "", BO);
955 if (isa<OverflowingBinaryOperator>(BO)) {
956 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
957 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
959 if (isa<PossiblyExactOperator>(BO)) {
960 New->setIsExact(BO->isExact());
962 if (isa<FPMathOperator>(BO))
963 New->copyFastMathFlags(I);
966 case Instruction::ICmp:
967 assert(NewOps.size() == 2 && "icmp with #ops != 2");
968 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
969 NewOps[0], NewOps[1]);
970 case Instruction::FCmp:
971 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
972 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
973 NewOps[0], NewOps[1]);
974 case Instruction::Trunc:
975 case Instruction::ZExt:
976 case Instruction::SExt:
977 case Instruction::FPToUI:
978 case Instruction::FPToSI:
979 case Instruction::UIToFP:
980 case Instruction::SIToFP:
981 case Instruction::FPTrunc:
982 case Instruction::FPExt: {
983 // It's possible that the mask has a different number of elements from
984 // the original cast. We recompute the destination type to match the mask.
986 VectorType::get(I->getType()->getScalarType(),
987 NewOps[0]->getType()->getVectorNumElements());
988 assert(NewOps.size() == 1 && "cast with #ops != 1");
989 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
992 case Instruction::GetElementPtr: {
993 Value *Ptr = NewOps[0];
994 ArrayRef<Value*> Idx = NewOps.slice(1);
995 GetElementPtrInst *GEP = GetElementPtrInst::Create(
996 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
997 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1001 llvm_unreachable("failed to rebuild vector instructions");
1005 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1006 // Mask.size() does not need to be equal to the number of vector elements.
1008 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
1009 if (isa<UndefValue>(V)) {
1010 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
1013 if (isa<ConstantAggregateZero>(V)) {
1014 return ConstantAggregateZero::get(
1015 VectorType::get(V->getType()->getScalarType(),
1018 if (Constant *C = dyn_cast<Constant>(V)) {
1019 SmallVector<Constant *, 16> MaskValues;
1020 for (int i = 0, e = Mask.size(); i != e; ++i) {
1022 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
1024 MaskValues.push_back(Builder->getInt32(Mask[i]));
1026 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1027 ConstantVector::get(MaskValues));
1030 Instruction *I = cast<Instruction>(V);
1031 switch (I->getOpcode()) {
1032 case Instruction::Add:
1033 case Instruction::FAdd:
1034 case Instruction::Sub:
1035 case Instruction::FSub:
1036 case Instruction::Mul:
1037 case Instruction::FMul:
1038 case Instruction::UDiv:
1039 case Instruction::SDiv:
1040 case Instruction::FDiv:
1041 case Instruction::URem:
1042 case Instruction::SRem:
1043 case Instruction::FRem:
1044 case Instruction::Shl:
1045 case Instruction::LShr:
1046 case Instruction::AShr:
1047 case Instruction::And:
1048 case Instruction::Or:
1049 case Instruction::Xor:
1050 case Instruction::ICmp:
1051 case Instruction::FCmp:
1052 case Instruction::Trunc:
1053 case Instruction::ZExt:
1054 case Instruction::SExt:
1055 case Instruction::FPToUI:
1056 case Instruction::FPToSI:
1057 case Instruction::UIToFP:
1058 case Instruction::SIToFP:
1059 case Instruction::FPTrunc:
1060 case Instruction::FPExt:
1061 case Instruction::Select:
1062 case Instruction::GetElementPtr: {
1063 SmallVector<Value*, 8> NewOps;
1064 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1065 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1066 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
1067 NewOps.push_back(V);
1068 NeedsRebuild |= (V != I->getOperand(i));
1071 return buildNew(I, NewOps);
1075 case Instruction::InsertElement: {
1076 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1078 // The insertelement was inserting at Element. Figure out which element
1079 // that becomes after shuffling. The answer is guaranteed to be unique
1080 // by CanEvaluateShuffled.
1083 for (int e = Mask.size(); Index != e; ++Index) {
1084 if (Mask[Index] == Element) {
1090 // If element is not in Mask, no need to handle the operand 1 (element to
1091 // be inserted). Just evaluate values in operand 0 according to Mask.
1093 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1095 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1096 return InsertElementInst::Create(V, I->getOperand(1),
1097 Builder->getInt32(Index), "", I);
1100 llvm_unreachable("failed to reorder elements of vector instruction!");
1103 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
1104 bool &isLHSID, bool &isRHSID) {
1105 isLHSID = isRHSID = true;
1107 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
1108 if (Mask[i] < 0) continue; // Ignore undef values.
1109 // Is this an identity shuffle of the LHS value?
1110 isLHSID &= (Mask[i] == (int)i);
1112 // Is this an identity shuffle of the RHS value?
1113 isRHSID &= (Mask[i]-e == i);
1117 // Returns true if the shuffle is extracting a contiguous range of values from
1118 // LHS, for example:
1119 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1120 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1121 // Shuffles to: |EE|FF|GG|HH|
1123 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1124 SmallVector<int, 16> &Mask) {
1125 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
1126 unsigned MaskElems = Mask.size();
1127 unsigned BegIdx = Mask.front();
1128 unsigned EndIdx = Mask.back();
1129 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1131 for (unsigned I = 0; I != MaskElems; ++I)
1132 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1137 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1138 Value *LHS = SVI.getOperand(0);
1139 Value *RHS = SVI.getOperand(1);
1140 SmallVector<int, 16> Mask = SVI.getShuffleMask();
1141 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1144 SimplifyShuffleVectorInst(LHS, RHS, SVI.getMask(), SVI.getType(), SQ))
1145 return replaceInstUsesWith(SVI, V);
1147 bool MadeChange = false;
1148 unsigned VWidth = SVI.getType()->getVectorNumElements();
1150 APInt UndefElts(VWidth, 0);
1151 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1152 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1154 return replaceInstUsesWith(SVI, V);
1155 LHS = SVI.getOperand(0);
1156 RHS = SVI.getOperand(1);
1160 unsigned LHSWidth = LHS->getType()->getVectorNumElements();
1162 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
1163 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
1164 if (LHS == RHS || isa<UndefValue>(LHS)) {
1165 if (isa<UndefValue>(LHS) && LHS == RHS) {
1166 // shuffle(undef,undef,mask) -> undef.
1167 Value *Result = (VWidth == LHSWidth)
1168 ? LHS : UndefValue::get(SVI.getType());
1169 return replaceInstUsesWith(SVI, Result);
1172 // Remap any references to RHS to use LHS.
1173 SmallVector<Constant*, 16> Elts;
1174 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
1176 Elts.push_back(UndefValue::get(Int32Ty));
1180 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
1181 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
1182 Mask[i] = -1; // Turn into undef.
1183 Elts.push_back(UndefValue::get(Int32Ty));
1185 Mask[i] = Mask[i] % e; // Force to LHS.
1186 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
1189 SVI.setOperand(0, SVI.getOperand(1));
1190 SVI.setOperand(1, UndefValue::get(RHS->getType()));
1191 SVI.setOperand(2, ConstantVector::get(Elts));
1192 LHS = SVI.getOperand(0);
1193 RHS = SVI.getOperand(1);
1197 if (VWidth == LHSWidth) {
1198 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
1199 bool isLHSID, isRHSID;
1200 recognizeIdentityMask(Mask, isLHSID, isRHSID);
1202 // Eliminate identity shuffles.
1203 if (isLHSID) return replaceInstUsesWith(SVI, LHS);
1204 if (isRHSID) return replaceInstUsesWith(SVI, RHS);
1207 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
1208 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
1209 return replaceInstUsesWith(SVI, V);
1212 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1213 // a non-vector type. We can instead bitcast the original vector followed by
1214 // an extract of the desired element:
1216 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1217 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1218 // %1 = bitcast <4 x i8> %sroa to i32
1220 // %bc = bitcast <16 x i8> %in to <4 x i32>
1221 // %ext = extractelement <4 x i32> %bc, i32 0
1223 // If the shuffle is extracting a contiguous range of values from the input
1224 // vector then each use which is a bitcast of the extracted size can be
1225 // replaced. This will work if the vector types are compatible, and the begin
1226 // index is aligned to a value in the casted vector type. If the begin index
1227 // isn't aligned then we can shuffle the original vector (keeping the same
1228 // vector type) before extracting.
1230 // This code will bail out if the target type is fundamentally incompatible
1231 // with vectors of the source type.
1233 // Example of <16 x i8>, target type i32:
1234 // Index range [4,8): v-----------v Will work.
1235 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1236 // <16 x i8>: | | | | | | | | | | | | | | | | |
1237 // <4 x i32>: | | | | |
1238 // +-----------+-----------+-----------+-----------+
1239 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1240 // Target type i40: ^--------------^ Won't work, bail.
1241 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1243 unsigned MaskElems = Mask.size();
1244 VectorType *SrcTy = cast<VectorType>(V->getType());
1245 unsigned VecBitWidth = SrcTy->getBitWidth();
1246 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1247 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1248 unsigned SrcNumElems = SrcTy->getNumElements();
1249 SmallVector<BitCastInst *, 8> BCs;
1250 DenseMap<Type *, Value *> NewBCs;
1251 for (User *U : SVI.users())
1252 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1253 if (!BC->use_empty())
1254 // Only visit bitcasts that weren't previously handled.
1256 for (BitCastInst *BC : BCs) {
1257 unsigned BegIdx = Mask.front();
1258 Type *TgtTy = BC->getDestTy();
1259 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1260 if (!TgtElemBitWidth)
1262 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1263 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1264 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1265 if (!VecBitWidthsEqual)
1267 if (!VectorType::isValidElementType(TgtTy))
1269 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1270 if (!BegIsAligned) {
1271 // Shuffle the input so [0,NumElements) contains the output, and
1272 // [NumElems,SrcNumElems) is undef.
1273 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1274 UndefValue::get(Int32Ty));
1275 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1276 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1277 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1278 ConstantVector::get(ShuffleMask),
1279 SVI.getName() + ".extract");
1282 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1283 assert(SrcElemsPerTgtElem);
1284 BegIdx /= SrcElemsPerTgtElem;
1285 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1289 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1290 if (!BCAlreadyExists)
1291 NewBCs[CastSrcTy] = NewBC;
1292 auto *Ext = Builder->CreateExtractElement(
1293 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1294 // The shufflevector isn't being replaced: the bitcast that used it
1295 // is. InstCombine will visit the newly-created instructions.
1296 replaceInstUsesWith(*BC, Ext);
1301 // If the LHS is a shufflevector itself, see if we can combine it with this
1302 // one without producing an unusual shuffle.
1303 // Cases that might be simplified:
1305 // x1=shuffle(v1,v2,mask1)
1306 // x=shuffle(x1,undef,mask)
1308 // x=shuffle(v1,undef,newMask)
1309 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1311 // x1=shuffle(v1,undef,mask1)
1312 // x=shuffle(x1,x2,mask)
1313 // where v1.size() == mask1.size()
1315 // x=shuffle(v1,x2,newMask)
1316 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1318 // x2=shuffle(v2,undef,mask2)
1319 // x=shuffle(x1,x2,mask)
1320 // where v2.size() == mask2.size()
1322 // x=shuffle(x1,v2,newMask)
1323 // newMask[i] = (mask[i] < x1.size())
1324 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1326 // x1=shuffle(v1,undef,mask1)
1327 // x2=shuffle(v2,undef,mask2)
1328 // x=shuffle(x1,x2,mask)
1329 // where v1.size() == v2.size()
1331 // x=shuffle(v1,v2,newMask)
1332 // newMask[i] = (mask[i] < x1.size())
1333 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1335 // Here we are really conservative:
1336 // we are absolutely afraid of producing a shuffle mask not in the input
1337 // program, because the code gen may not be smart enough to turn a merged
1338 // shuffle into two specific shuffles: it may produce worse code. As such,
1339 // we only merge two shuffles if the result is either a splat or one of the
1340 // input shuffle masks. In this case, merging the shuffles just removes
1341 // one instruction, which we know is safe. This is good for things like
1342 // turning: (splat(splat)) -> splat, or
1343 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1344 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1345 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1347 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
1348 LHSShuffle = nullptr;
1350 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
1351 RHSShuffle = nullptr;
1352 if (!LHSShuffle && !RHSShuffle)
1353 return MadeChange ? &SVI : nullptr;
1355 Value* LHSOp0 = nullptr;
1356 Value* LHSOp1 = nullptr;
1357 Value* RHSOp0 = nullptr;
1358 unsigned LHSOp0Width = 0;
1359 unsigned RHSOp0Width = 0;
1361 LHSOp0 = LHSShuffle->getOperand(0);
1362 LHSOp1 = LHSShuffle->getOperand(1);
1363 LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
1366 RHSOp0 = RHSShuffle->getOperand(0);
1367 RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
1369 Value* newLHS = LHS;
1370 Value* newRHS = RHS;
1373 if (isa<UndefValue>(RHS)) {
1378 else if (LHSOp0Width == LHSWidth) {
1383 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1387 if (LHSOp0 == RHSOp0) {
1392 if (newLHS == LHS && newRHS == RHS)
1393 return MadeChange ? &SVI : nullptr;
1395 SmallVector<int, 16> LHSMask;
1396 SmallVector<int, 16> RHSMask;
1398 LHSMask = LHSShuffle->getShuffleMask();
1399 if (RHSShuffle && newRHS != RHS)
1400 RHSMask = RHSShuffle->getShuffleMask();
1402 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1403 SmallVector<int, 16> newMask;
1404 bool isSplat = true;
1406 // Create a new mask for the new ShuffleVectorInst so that the new
1407 // ShuffleVectorInst is equivalent to the original one.
1408 for (unsigned i = 0; i < VWidth; ++i) {
1411 // This element is an undef value.
1413 } else if (Mask[i] < (int)LHSWidth) {
1414 // This element is from left hand side vector operand.
1416 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1417 // new mask value for the element.
1418 if (newLHS != LHS) {
1419 eltMask = LHSMask[Mask[i]];
1420 // If the value selected is an undef value, explicitly specify it
1421 // with a -1 mask value.
1422 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1427 // This element is from right hand side vector operand
1429 // If the value selected is an undef value, explicitly specify it
1430 // with a -1 mask value. (case 1)
1431 if (isa<UndefValue>(RHS))
1433 // If RHS is going to be replaced (case 3 or 4), calculate the
1434 // new mask value for the element.
1435 else if (newRHS != RHS) {
1436 eltMask = RHSMask[Mask[i]-LHSWidth];
1437 // If the value selected is an undef value, explicitly specify it
1438 // with a -1 mask value.
1439 if (eltMask >= (int)RHSOp0Width) {
1440 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1441 && "should have been check above");
1445 eltMask = Mask[i]-LHSWidth;
1447 // If LHS's width is changed, shift the mask value accordingly.
1448 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1449 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1450 // If newRHS == newLHS, we want to remap any references from newRHS to
1451 // newLHS so that we can properly identify splats that may occur due to
1452 // obfuscation across the two vectors.
1453 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1454 eltMask += newLHSWidth;
1457 // Check if this could still be a splat.
1459 if (SplatElt >= 0 && SplatElt != eltMask)
1464 newMask.push_back(eltMask);
1467 // If the result mask is equal to one of the original shuffle masks,
1468 // or is a splat, do the replacement.
1469 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1470 SmallVector<Constant*, 16> Elts;
1471 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1472 if (newMask[i] < 0) {
1473 Elts.push_back(UndefValue::get(Int32Ty));
1475 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1479 newRHS = UndefValue::get(newLHS->getType());
1480 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1483 // If the result mask is an identity, replace uses of this instruction with
1484 // corresponding argument.
1485 bool isLHSID, isRHSID;
1486 recognizeIdentityMask(newMask, isLHSID, isRHSID);
1487 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1488 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
1490 return MadeChange ? &SVI : nullptr;