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 "InstCombine.h"
16 #include "llvm/IR/PatternMatch.h"
18 using namespace PatternMatch;
20 #define DEBUG_TYPE "instcombine"
22 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
23 /// is to leave as a vector operation. isConstant indicates whether we're
24 /// extracting one known element. If false we're extracting a variable index.
25 static bool CheapToScalarize(Value *V, bool isConstant) {
26 if (Constant *C = dyn_cast<Constant>(V)) {
27 if (isConstant) return true;
29 // If all elts are the same, we can extract it and use any of the values.
30 if (Constant *Op0 = C->getAggregateElement(0U)) {
31 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
33 if (C->getAggregateElement(i) != Op0)
38 Instruction *I = dyn_cast<Instruction>(V);
41 // Insert element gets simplified to the inserted element or is deleted if
42 // this is constant idx extract element and its a constant idx insertelt.
43 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
44 isa<ConstantInt>(I->getOperand(2)))
46 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
48 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
49 if (BO->hasOneUse() &&
50 (CheapToScalarize(BO->getOperand(0), isConstant) ||
51 CheapToScalarize(BO->getOperand(1), isConstant)))
53 if (CmpInst *CI = dyn_cast<CmpInst>(I))
54 if (CI->hasOneUse() &&
55 (CheapToScalarize(CI->getOperand(0), isConstant) ||
56 CheapToScalarize(CI->getOperand(1), isConstant)))
62 /// FindScalarElement - Given a vector and an element number, see if the scalar
63 /// value is already around as a register, for example if it were inserted then
64 /// extracted from the vector.
65 static Value *FindScalarElement(Value *V, unsigned EltNo) {
66 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
67 VectorType *VTy = cast<VectorType>(V->getType());
68 unsigned Width = VTy->getNumElements();
69 if (EltNo >= Width) // Out of range access.
70 return UndefValue::get(VTy->getElementType());
72 if (Constant *C = dyn_cast<Constant>(V))
73 return C->getAggregateElement(EltNo);
75 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
76 // If this is an insert to a variable element, we don't know what it is.
77 if (!isa<ConstantInt>(III->getOperand(2)))
79 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
81 // If this is an insert to the element we are looking for, return the
84 return III->getOperand(1);
86 // Otherwise, the insertelement doesn't modify the value, recurse on its
88 return FindScalarElement(III->getOperand(0), EltNo);
91 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
92 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
93 int InEl = SVI->getMaskValue(EltNo);
95 return UndefValue::get(VTy->getElementType());
96 if (InEl < (int)LHSWidth)
97 return FindScalarElement(SVI->getOperand(0), InEl);
98 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
101 // Extract a value from a vector add operation with a constant zero.
102 Value *Val = nullptr; Constant *Con = nullptr;
103 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
104 if (Con->getAggregateElement(EltNo)->isNullValue())
105 return FindScalarElement(Val, EltNo);
108 // Otherwise, we don't know.
112 // If we have a PHI node with a vector type that has only 2 uses: feed
113 // itself and be an operand of extractelement at a constant location,
114 // try to replace the PHI of the vector type with a PHI of a scalar type.
115 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
116 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
117 if (!PN->hasNUses(2))
120 // If so, it's known at this point that one operand is PHI and the other is
121 // an extractelement node. Find the PHI user that is not the extractelement
123 auto iu = PN->user_begin();
124 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
125 if (PHIUser == cast<Instruction>(&EI))
126 PHIUser = cast<Instruction>(*(++iu));
128 // Verify that this PHI user has one use, which is the PHI itself,
129 // and that it is a binary operation which is cheap to scalarize.
130 // otherwise return NULL.
131 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
132 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
135 // Create a scalar PHI node that will replace the vector PHI node
136 // just before the current PHI node.
137 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
138 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
139 // Scalarize each PHI operand.
140 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
141 Value *PHIInVal = PN->getIncomingValue(i);
142 BasicBlock *inBB = PN->getIncomingBlock(i);
143 Value *Elt = EI.getIndexOperand();
144 // If the operand is the PHI induction variable:
145 if (PHIInVal == PHIUser) {
146 // Scalarize the binary operation. Its first operand is the
147 // scalar PHI and the second operand is extracted from the other
149 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
150 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
151 Value *Op = InsertNewInstWith(
152 ExtractElementInst::Create(B0->getOperand(opId), Elt,
153 B0->getOperand(opId)->getName() + ".Elt"),
155 Value *newPHIUser = InsertNewInstWith(
156 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
157 scalarPHI->addIncoming(newPHIUser, inBB);
159 // Scalarize PHI input:
160 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
161 // Insert the new instruction into the predecessor basic block.
162 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
163 BasicBlock::iterator InsertPos;
164 if (pos && !isa<PHINode>(pos)) {
168 InsertPos = inBB->getFirstInsertionPt();
171 InsertNewInstWith(newEI, *InsertPos);
173 scalarPHI->addIncoming(newEI, inBB);
176 return ReplaceInstUsesWith(EI, scalarPHI);
179 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
180 // If vector val is constant with all elements the same, replace EI with
181 // that element. We handle a known element # below.
182 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
183 if (CheapToScalarize(C, false))
184 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
186 // If extracting a specified index from the vector, see if we can recursively
187 // find a previously computed scalar that was inserted into the vector.
188 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
189 unsigned IndexVal = IdxC->getZExtValue();
190 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
192 // If this is extracting an invalid index, turn this into undef, to avoid
193 // crashing the code below.
194 if (IndexVal >= VectorWidth)
195 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
197 // This instruction only demands the single element from the input vector.
198 // If the input vector has a single use, simplify it based on this use
200 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
201 APInt UndefElts(VectorWidth, 0);
202 APInt DemandedMask(VectorWidth, 0);
203 DemandedMask.setBit(IndexVal);
204 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
205 DemandedMask, UndefElts)) {
211 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
212 return ReplaceInstUsesWith(EI, Elt);
214 // If the this extractelement is directly using a bitcast from a vector of
215 // the same number of elements, see if we can find the source element from
216 // it. In this case, we will end up needing to bitcast the scalars.
217 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
218 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
219 if (VT->getNumElements() == VectorWidth)
220 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
221 return new BitCastInst(Elt, EI.getType());
224 // If there's a vector PHI feeding a scalar use through this extractelement
225 // instruction, try to scalarize the PHI.
226 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
227 Instruction *scalarPHI = scalarizePHI(EI, PN);
233 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
234 // Push extractelement into predecessor operation if legal and
235 // profitable to do so
236 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
237 if (I->hasOneUse() &&
238 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
240 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
241 EI.getName()+".lhs");
243 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
244 EI.getName()+".rhs");
245 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
247 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
248 // Extracting the inserted element?
249 if (IE->getOperand(2) == EI.getOperand(1))
250 return ReplaceInstUsesWith(EI, IE->getOperand(1));
251 // If the inserted and extracted elements are constants, they must not
252 // be the same value, extract from the pre-inserted value instead.
253 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
254 Worklist.AddValue(EI.getOperand(0));
255 EI.setOperand(0, IE->getOperand(0));
258 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
259 // If this is extracting an element from a shufflevector, figure out where
260 // it came from and extract from the appropriate input element instead.
261 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
262 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
265 SVI->getOperand(0)->getType()->getVectorNumElements();
268 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
269 if (SrcIdx < (int)LHSWidth)
270 Src = SVI->getOperand(0);
273 Src = SVI->getOperand(1);
275 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
276 return ExtractElementInst::Create(Src,
277 ConstantInt::get(Int32Ty,
280 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
281 // Canonicalize extractelement(cast) -> cast(extractelement)
282 // bitcasts can change the number of vector elements and they cost nothing
283 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
284 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
285 EI.getIndexOperand());
286 Worklist.AddValue(EE);
287 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
289 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
290 if (SI->hasOneUse()) {
291 // TODO: For a select on vectors, it might be useful to do this if it
292 // has multiple extractelement uses. For vector select, that seems to
293 // fight the vectorizer.
295 // If we are extracting an element from a vector select or a select on
296 // vectors, a select on the scalars extracted from the vector arguments.
297 Value *TrueVal = SI->getTrueValue();
298 Value *FalseVal = SI->getFalseValue();
300 Value *Cond = SI->getCondition();
301 if (Cond->getType()->isVectorTy()) {
302 Cond = Builder->CreateExtractElement(Cond,
303 EI.getIndexOperand(),
304 Cond->getName() + ".elt");
308 = Builder->CreateExtractElement(TrueVal,
309 EI.getIndexOperand(),
310 TrueVal->getName() + ".elt");
313 = Builder->CreateExtractElement(FalseVal,
314 EI.getIndexOperand(),
315 FalseVal->getName() + ".elt");
316 return SelectInst::Create(Cond,
319 SI->getName() + ".elt");
326 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
327 /// elements from either LHS or RHS, return the shuffle mask and true.
328 /// Otherwise, return false.
329 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
330 SmallVectorImpl<Constant*> &Mask) {
331 assert(LHS->getType() == RHS->getType() &&
332 "Invalid CollectSingleShuffleElements");
333 unsigned NumElts = V->getType()->getVectorNumElements();
335 if (isa<UndefValue>(V)) {
336 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
341 for (unsigned i = 0; i != NumElts; ++i)
342 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
347 for (unsigned i = 0; i != NumElts; ++i)
348 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
353 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
354 // If this is an insert of an extract from some other vector, include it.
355 Value *VecOp = IEI->getOperand(0);
356 Value *ScalarOp = IEI->getOperand(1);
357 Value *IdxOp = IEI->getOperand(2);
359 if (!isa<ConstantInt>(IdxOp))
361 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
363 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
364 // Okay, we can handle this if the vector we are insertinting into is
366 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
367 // If so, update the mask to reflect the inserted undef.
368 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
371 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
372 if (isa<ConstantInt>(EI->getOperand(1))) {
373 unsigned ExtractedIdx =
374 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
375 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
377 // This must be extracting from either LHS or RHS.
378 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
379 // Okay, we can handle this if the vector we are insertinting into is
381 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
382 // If so, update the mask to reflect the inserted value.
383 if (EI->getOperand(0) == LHS) {
384 Mask[InsertedIdx % NumElts] =
385 ConstantInt::get(Type::getInt32Ty(V->getContext()),
388 assert(EI->getOperand(0) == RHS);
389 Mask[InsertedIdx % NumElts] =
390 ConstantInt::get(Type::getInt32Ty(V->getContext()),
391 ExtractedIdx + NumLHSElts);
404 /// We are building a shuffle to create V, which is a sequence of insertelement,
405 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
406 /// not rely on the second vector source. Return an std::pair containing the
407 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
408 /// parameter as required.
410 /// Note: we intentionally don't try to fold earlier shuffles since they have
411 /// often been chosen carefully to be efficiently implementable on the target.
412 typedef std::pair<Value *, Value *> ShuffleOps;
414 static ShuffleOps CollectShuffleElements(Value *V,
415 SmallVectorImpl<Constant *> &Mask,
416 Value *PermittedRHS) {
417 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
418 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
420 if (isa<UndefValue>(V)) {
421 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
422 return std::make_pair(
423 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
426 if (isa<ConstantAggregateZero>(V)) {
427 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
428 return std::make_pair(V, nullptr);
431 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
432 // If this is an insert of an extract from some other vector, include it.
433 Value *VecOp = IEI->getOperand(0);
434 Value *ScalarOp = IEI->getOperand(1);
435 Value *IdxOp = IEI->getOperand(2);
437 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
438 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
439 unsigned ExtractedIdx =
440 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
441 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
443 // Either the extracted from or inserted into vector must be RHSVec,
444 // otherwise we'd end up with a shuffle of three inputs.
445 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
446 Value *RHS = EI->getOperand(0);
447 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
448 assert(LR.second == nullptr || LR.second == RHS);
450 if (LR.first->getType() != RHS->getType()) {
451 // We tried our best, but we can't find anything compatible with RHS
452 // further up the chain. Return a trivial shuffle.
453 for (unsigned i = 0; i < NumElts; ++i)
454 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
455 return std::make_pair(V, nullptr);
458 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
459 Mask[InsertedIdx % NumElts] =
460 ConstantInt::get(Type::getInt32Ty(V->getContext()),
461 NumLHSElts+ExtractedIdx);
462 return std::make_pair(LR.first, RHS);
465 if (VecOp == PermittedRHS) {
466 // We've gone as far as we can: anything on the other side of the
467 // extractelement will already have been converted into a shuffle.
468 unsigned NumLHSElts =
469 EI->getOperand(0)->getType()->getVectorNumElements();
470 for (unsigned i = 0; i != NumElts; ++i)
471 Mask.push_back(ConstantInt::get(
472 Type::getInt32Ty(V->getContext()),
473 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
474 return std::make_pair(EI->getOperand(0), PermittedRHS);
477 // If this insertelement is a chain that comes from exactly these two
478 // vectors, return the vector and the effective shuffle.
479 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
480 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
482 return std::make_pair(EI->getOperand(0), PermittedRHS);
487 // Otherwise, can't do anything fancy. Return an identity vector.
488 for (unsigned i = 0; i != NumElts; ++i)
489 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
490 return std::make_pair(V, nullptr);
493 /// Try to find redundant insertvalue instructions, like the following ones:
494 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
495 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
496 /// Here the second instruction inserts values at the same indices, as the
497 /// first one, making the first one redundant.
498 /// It should be transformed to:
499 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
500 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
501 bool IsRedundant = false;
502 ArrayRef<unsigned int> FirstIndices = I.getIndices();
504 // If there is a chain of insertvalue instructions (each of them except the
505 // last one has only one use and it's another insertvalue insn from this
506 // chain), check if any of the 'children' uses the same indices as the first
507 // instruction. In this case, the first one is redundant.
509 unsigned int Depth = 0;
510 while (V->hasOneUse() && Depth < 10) {
511 User *U = V->user_back();
512 InsertValueInst *UserInsInst = dyn_cast<InsertValueInst>(U);
513 if (!UserInsInst || U->getType() != I.getType()) {
516 if (UserInsInst->getIndices() == FirstIndices) {
525 return ReplaceInstUsesWith(I, I.getOperand(0));
529 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
530 Value *VecOp = IE.getOperand(0);
531 Value *ScalarOp = IE.getOperand(1);
532 Value *IdxOp = IE.getOperand(2);
534 // Inserting an undef or into an undefined place, remove this.
535 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
536 ReplaceInstUsesWith(IE, VecOp);
538 // If the inserted element was extracted from some other vector, and if the
539 // indexes are constant, try to turn this into a shufflevector operation.
540 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
541 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
542 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
543 unsigned NumExtractVectorElts =
544 EI->getOperand(0)->getType()->getVectorNumElements();
545 unsigned ExtractedIdx =
546 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
547 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
549 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
550 return ReplaceInstUsesWith(IE, VecOp);
552 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
553 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
555 // If we are extracting a value from a vector, then inserting it right
556 // back into the same place, just use the input vector.
557 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
558 return ReplaceInstUsesWith(IE, VecOp);
560 // If this insertelement isn't used by some other insertelement, turn it
561 // (and any insertelements it points to), into one big shuffle.
562 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
563 SmallVector<Constant*, 16> Mask;
564 ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
566 // The proposed shuffle may be trivial, in which case we shouldn't
567 // perform the combine.
568 if (LR.first != &IE && LR.second != &IE) {
569 // We now have a shuffle of LHS, RHS, Mask.
570 if (LR.second == nullptr)
571 LR.second = UndefValue::get(LR.first->getType());
572 return new ShuffleVectorInst(LR.first, LR.second,
573 ConstantVector::get(Mask));
579 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
580 APInt UndefElts(VWidth, 0);
581 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
582 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
584 return ReplaceInstUsesWith(IE, V);
591 /// Return true if we can evaluate the specified expression tree if the vector
592 /// elements were shuffled in a different order.
593 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
594 unsigned Depth = 5) {
595 // We can always reorder the elements of a constant.
596 if (isa<Constant>(V))
599 // We won't reorder vector arguments. No IPO here.
600 Instruction *I = dyn_cast<Instruction>(V);
601 if (!I) return false;
603 // Two users may expect different orders of the elements. Don't try it.
607 if (Depth == 0) return false;
609 switch (I->getOpcode()) {
610 case Instruction::Add:
611 case Instruction::FAdd:
612 case Instruction::Sub:
613 case Instruction::FSub:
614 case Instruction::Mul:
615 case Instruction::FMul:
616 case Instruction::UDiv:
617 case Instruction::SDiv:
618 case Instruction::FDiv:
619 case Instruction::URem:
620 case Instruction::SRem:
621 case Instruction::FRem:
622 case Instruction::Shl:
623 case Instruction::LShr:
624 case Instruction::AShr:
625 case Instruction::And:
626 case Instruction::Or:
627 case Instruction::Xor:
628 case Instruction::ICmp:
629 case Instruction::FCmp:
630 case Instruction::Trunc:
631 case Instruction::ZExt:
632 case Instruction::SExt:
633 case Instruction::FPToUI:
634 case Instruction::FPToSI:
635 case Instruction::UIToFP:
636 case Instruction::SIToFP:
637 case Instruction::FPTrunc:
638 case Instruction::FPExt:
639 case Instruction::GetElementPtr: {
640 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
641 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
646 case Instruction::InsertElement: {
647 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
648 if (!CI) return false;
649 int ElementNumber = CI->getLimitedValue();
651 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
652 // can't put an element into multiple indices.
653 bool SeenOnce = false;
654 for (int i = 0, e = Mask.size(); i != e; ++i) {
655 if (Mask[i] == ElementNumber) {
661 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
667 /// Rebuild a new instruction just like 'I' but with the new operands given.
668 /// In the event of type mismatch, the type of the operands is correct.
669 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
670 // We don't want to use the IRBuilder here because we want the replacement
671 // instructions to appear next to 'I', not the builder's insertion point.
672 switch (I->getOpcode()) {
673 case Instruction::Add:
674 case Instruction::FAdd:
675 case Instruction::Sub:
676 case Instruction::FSub:
677 case Instruction::Mul:
678 case Instruction::FMul:
679 case Instruction::UDiv:
680 case Instruction::SDiv:
681 case Instruction::FDiv:
682 case Instruction::URem:
683 case Instruction::SRem:
684 case Instruction::FRem:
685 case Instruction::Shl:
686 case Instruction::LShr:
687 case Instruction::AShr:
688 case Instruction::And:
689 case Instruction::Or:
690 case Instruction::Xor: {
691 BinaryOperator *BO = cast<BinaryOperator>(I);
692 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
693 BinaryOperator *New =
694 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
695 NewOps[0], NewOps[1], "", BO);
696 if (isa<OverflowingBinaryOperator>(BO)) {
697 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
698 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
700 if (isa<PossiblyExactOperator>(BO)) {
701 New->setIsExact(BO->isExact());
703 if (isa<FPMathOperator>(BO))
704 New->copyFastMathFlags(I);
707 case Instruction::ICmp:
708 assert(NewOps.size() == 2 && "icmp with #ops != 2");
709 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
710 NewOps[0], NewOps[1]);
711 case Instruction::FCmp:
712 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
713 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
714 NewOps[0], NewOps[1]);
715 case Instruction::Trunc:
716 case Instruction::ZExt:
717 case Instruction::SExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::UIToFP:
721 case Instruction::SIToFP:
722 case Instruction::FPTrunc:
723 case Instruction::FPExt: {
724 // It's possible that the mask has a different number of elements from
725 // the original cast. We recompute the destination type to match the mask.
727 VectorType::get(I->getType()->getScalarType(),
728 NewOps[0]->getType()->getVectorNumElements());
729 assert(NewOps.size() == 1 && "cast with #ops != 1");
730 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
733 case Instruction::GetElementPtr: {
734 Value *Ptr = NewOps[0];
735 ArrayRef<Value*> Idx = NewOps.slice(1);
736 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
737 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
741 llvm_unreachable("failed to rebuild vector instructions");
745 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
746 // Mask.size() does not need to be equal to the number of vector elements.
748 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
749 if (isa<UndefValue>(V)) {
750 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
753 if (isa<ConstantAggregateZero>(V)) {
754 return ConstantAggregateZero::get(
755 VectorType::get(V->getType()->getScalarType(),
758 if (Constant *C = dyn_cast<Constant>(V)) {
759 SmallVector<Constant *, 16> MaskValues;
760 for (int i = 0, e = Mask.size(); i != e; ++i) {
762 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
764 MaskValues.push_back(Builder->getInt32(Mask[i]));
766 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
767 ConstantVector::get(MaskValues));
770 Instruction *I = cast<Instruction>(V);
771 switch (I->getOpcode()) {
772 case Instruction::Add:
773 case Instruction::FAdd:
774 case Instruction::Sub:
775 case Instruction::FSub:
776 case Instruction::Mul:
777 case Instruction::FMul:
778 case Instruction::UDiv:
779 case Instruction::SDiv:
780 case Instruction::FDiv:
781 case Instruction::URem:
782 case Instruction::SRem:
783 case Instruction::FRem:
784 case Instruction::Shl:
785 case Instruction::LShr:
786 case Instruction::AShr:
787 case Instruction::And:
788 case Instruction::Or:
789 case Instruction::Xor:
790 case Instruction::ICmp:
791 case Instruction::FCmp:
792 case Instruction::Trunc:
793 case Instruction::ZExt:
794 case Instruction::SExt:
795 case Instruction::FPToUI:
796 case Instruction::FPToSI:
797 case Instruction::UIToFP:
798 case Instruction::SIToFP:
799 case Instruction::FPTrunc:
800 case Instruction::FPExt:
801 case Instruction::Select:
802 case Instruction::GetElementPtr: {
803 SmallVector<Value*, 8> NewOps;
804 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
805 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
806 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
808 NeedsRebuild |= (V != I->getOperand(i));
811 return BuildNew(I, NewOps);
815 case Instruction::InsertElement: {
816 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
818 // The insertelement was inserting at Element. Figure out which element
819 // that becomes after shuffling. The answer is guaranteed to be unique
820 // by CanEvaluateShuffled.
823 for (int e = Mask.size(); Index != e; ++Index) {
824 if (Mask[Index] == Element) {
830 // If element is not in Mask, no need to handle the operand 1 (element to
831 // be inserted). Just evaluate values in operand 0 according to Mask.
833 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
835 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
836 return InsertElementInst::Create(V, I->getOperand(1),
837 Builder->getInt32(Index), "", I);
840 llvm_unreachable("failed to reorder elements of vector instruction!");
843 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
844 Value *LHS = SVI.getOperand(0);
845 Value *RHS = SVI.getOperand(1);
846 SmallVector<int, 16> Mask = SVI.getShuffleMask();
848 bool MadeChange = false;
850 // Undefined shuffle mask -> undefined value.
851 if (isa<UndefValue>(SVI.getOperand(2)))
852 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
854 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
856 APInt UndefElts(VWidth, 0);
857 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
858 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
860 return ReplaceInstUsesWith(SVI, V);
861 LHS = SVI.getOperand(0);
862 RHS = SVI.getOperand(1);
866 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
868 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
869 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
870 if (LHS == RHS || isa<UndefValue>(LHS)) {
871 if (isa<UndefValue>(LHS) && LHS == RHS) {
872 // shuffle(undef,undef,mask) -> undef.
873 Value *Result = (VWidth == LHSWidth)
874 ? LHS : UndefValue::get(SVI.getType());
875 return ReplaceInstUsesWith(SVI, Result);
878 // Remap any references to RHS to use LHS.
879 SmallVector<Constant*, 16> Elts;
880 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
882 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
886 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
887 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
888 Mask[i] = -1; // Turn into undef.
889 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
891 Mask[i] = Mask[i] % e; // Force to LHS.
892 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
896 SVI.setOperand(0, SVI.getOperand(1));
897 SVI.setOperand(1, UndefValue::get(RHS->getType()));
898 SVI.setOperand(2, ConstantVector::get(Elts));
899 LHS = SVI.getOperand(0);
900 RHS = SVI.getOperand(1);
904 if (VWidth == LHSWidth) {
905 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
906 bool isLHSID = true, isRHSID = true;
908 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
909 if (Mask[i] < 0) continue; // Ignore undef values.
910 // Is this an identity shuffle of the LHS value?
911 isLHSID &= (Mask[i] == (int)i);
913 // Is this an identity shuffle of the RHS value?
914 isRHSID &= (Mask[i]-e == i);
917 // Eliminate identity shuffles.
918 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
919 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
922 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
923 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
924 return ReplaceInstUsesWith(SVI, V);
927 // If the LHS is a shufflevector itself, see if we can combine it with this
928 // one without producing an unusual shuffle.
929 // Cases that might be simplified:
931 // x1=shuffle(v1,v2,mask1)
932 // x=shuffle(x1,undef,mask)
934 // x=shuffle(v1,undef,newMask)
935 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
937 // x1=shuffle(v1,undef,mask1)
938 // x=shuffle(x1,x2,mask)
939 // where v1.size() == mask1.size()
941 // x=shuffle(v1,x2,newMask)
942 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
944 // x2=shuffle(v2,undef,mask2)
945 // x=shuffle(x1,x2,mask)
946 // where v2.size() == mask2.size()
948 // x=shuffle(x1,v2,newMask)
949 // newMask[i] = (mask[i] < x1.size())
950 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
952 // x1=shuffle(v1,undef,mask1)
953 // x2=shuffle(v2,undef,mask2)
954 // x=shuffle(x1,x2,mask)
955 // where v1.size() == v2.size()
957 // x=shuffle(v1,v2,newMask)
958 // newMask[i] = (mask[i] < x1.size())
959 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
961 // Here we are really conservative:
962 // we are absolutely afraid of producing a shuffle mask not in the input
963 // program, because the code gen may not be smart enough to turn a merged
964 // shuffle into two specific shuffles: it may produce worse code. As such,
965 // we only merge two shuffles if the result is either a splat or one of the
966 // input shuffle masks. In this case, merging the shuffles just removes
967 // one instruction, which we know is safe. This is good for things like
968 // turning: (splat(splat)) -> splat, or
969 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
970 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
971 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
973 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
974 LHSShuffle = nullptr;
976 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
977 RHSShuffle = nullptr;
978 if (!LHSShuffle && !RHSShuffle)
979 return MadeChange ? &SVI : nullptr;
981 Value* LHSOp0 = nullptr;
982 Value* LHSOp1 = nullptr;
983 Value* RHSOp0 = nullptr;
984 unsigned LHSOp0Width = 0;
985 unsigned RHSOp0Width = 0;
987 LHSOp0 = LHSShuffle->getOperand(0);
988 LHSOp1 = LHSShuffle->getOperand(1);
989 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
992 RHSOp0 = RHSShuffle->getOperand(0);
993 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
999 if (isa<UndefValue>(RHS)) {
1004 else if (LHSOp0Width == LHSWidth) {
1009 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1013 if (LHSOp0 == RHSOp0) {
1018 if (newLHS == LHS && newRHS == RHS)
1019 return MadeChange ? &SVI : nullptr;
1021 SmallVector<int, 16> LHSMask;
1022 SmallVector<int, 16> RHSMask;
1024 LHSMask = LHSShuffle->getShuffleMask();
1025 if (RHSShuffle && newRHS != RHS)
1026 RHSMask = RHSShuffle->getShuffleMask();
1028 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1029 SmallVector<int, 16> newMask;
1030 bool isSplat = true;
1032 // Create a new mask for the new ShuffleVectorInst so that the new
1033 // ShuffleVectorInst is equivalent to the original one.
1034 for (unsigned i = 0; i < VWidth; ++i) {
1037 // This element is an undef value.
1039 } else if (Mask[i] < (int)LHSWidth) {
1040 // This element is from left hand side vector operand.
1042 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1043 // new mask value for the element.
1044 if (newLHS != LHS) {
1045 eltMask = LHSMask[Mask[i]];
1046 // If the value selected is an undef value, explicitly specify it
1047 // with a -1 mask value.
1048 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1053 // This element is from right hand side vector operand
1055 // If the value selected is an undef value, explicitly specify it
1056 // with a -1 mask value. (case 1)
1057 if (isa<UndefValue>(RHS))
1059 // If RHS is going to be replaced (case 3 or 4), calculate the
1060 // new mask value for the element.
1061 else if (newRHS != RHS) {
1062 eltMask = RHSMask[Mask[i]-LHSWidth];
1063 // If the value selected is an undef value, explicitly specify it
1064 // with a -1 mask value.
1065 if (eltMask >= (int)RHSOp0Width) {
1066 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1067 && "should have been check above");
1071 eltMask = Mask[i]-LHSWidth;
1073 // If LHS's width is changed, shift the mask value accordingly.
1074 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1075 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1076 // If newRHS == newLHS, we want to remap any references from newRHS to
1077 // newLHS so that we can properly identify splats that may occur due to
1078 // obfuscation across the two vectors.
1079 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1080 eltMask += newLHSWidth;
1083 // Check if this could still be a splat.
1085 if (SplatElt >= 0 && SplatElt != eltMask)
1090 newMask.push_back(eltMask);
1093 // If the result mask is equal to one of the original shuffle masks,
1094 // or is a splat, do the replacement.
1095 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1096 SmallVector<Constant*, 16> Elts;
1097 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1098 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1099 if (newMask[i] < 0) {
1100 Elts.push_back(UndefValue::get(Int32Ty));
1102 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1106 newRHS = UndefValue::get(newLHS->getType());
1107 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1110 return MadeChange ? &SVI : nullptr;