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 #define DEBUG_TYPE "instcombine"
16 #include "InstCombine.h"
17 #include "llvm/IR/PatternMatch.h"
19 using namespace PatternMatch;
21 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
22 /// is to leave as a vector operation. isConstant indicates whether we're
23 /// extracting one known element. If false we're extracting a variable index.
24 static bool CheapToScalarize(Value *V, bool isConstant) {
25 if (Constant *C = dyn_cast<Constant>(V)) {
26 if (isConstant) return true;
28 // If all elts are the same, we can extract it and use any of the values.
29 if (Constant *Op0 = C->getAggregateElement(0U)) {
30 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
32 if (C->getAggregateElement(i) != Op0)
37 Instruction *I = dyn_cast<Instruction>(V);
40 // Insert element gets simplified to the inserted element or is deleted if
41 // this is constant idx extract element and its a constant idx insertelt.
42 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
43 isa<ConstantInt>(I->getOperand(2)))
45 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
47 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
48 if (BO->hasOneUse() &&
49 (CheapToScalarize(BO->getOperand(0), isConstant) ||
50 CheapToScalarize(BO->getOperand(1), isConstant)))
52 if (CmpInst *CI = dyn_cast<CmpInst>(I))
53 if (CI->hasOneUse() &&
54 (CheapToScalarize(CI->getOperand(0), isConstant) ||
55 CheapToScalarize(CI->getOperand(1), isConstant)))
61 /// FindScalarElement - Given a vector and an element number, see if the scalar
62 /// value is already around as a register, for example if it were inserted then
63 /// extracted from the vector.
64 static Value *FindScalarElement(Value *V, unsigned EltNo) {
65 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
66 VectorType *VTy = cast<VectorType>(V->getType());
67 unsigned Width = VTy->getNumElements();
68 if (EltNo >= Width) // Out of range access.
69 return UndefValue::get(VTy->getElementType());
71 if (Constant *C = dyn_cast<Constant>(V))
72 return C->getAggregateElement(EltNo);
74 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
75 // If this is an insert to a variable element, we don't know what it is.
76 if (!isa<ConstantInt>(III->getOperand(2)))
78 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
80 // If this is an insert to the element we are looking for, return the
83 return III->getOperand(1);
85 // Otherwise, the insertelement doesn't modify the value, recurse on its
87 return FindScalarElement(III->getOperand(0), EltNo);
90 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
91 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
92 int InEl = SVI->getMaskValue(EltNo);
94 return UndefValue::get(VTy->getElementType());
95 if (InEl < (int)LHSWidth)
96 return FindScalarElement(SVI->getOperand(0), InEl);
97 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
100 // Extract a value from a vector add operation with a constant zero.
101 Value *Val = 0; Constant *Con = 0;
102 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
103 if (Con->getAggregateElement(EltNo)->isNullValue())
104 return FindScalarElement(Val, EltNo);
107 // Otherwise, we don't know.
111 // If we have a PHI node with a vector type that has only 2 uses: feed
112 // itself and be an operand of extractelement at a constant location,
113 // try to replace the PHI of the vector type with a PHI of a scalar type.
114 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
115 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
116 if (!PN->hasNUses(2))
119 // If so, it's known at this point that one operand is PHI and the other is
120 // an extractelement node. Find the PHI user that is not the extractelement
122 auto iu = PN->user_begin();
123 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
124 if (PHIUser == cast<Instruction>(&EI))
125 PHIUser = cast<Instruction>(*(++iu));
127 // Verify that this PHI user has one use, which is the PHI itself,
128 // and that it is a binary operation which is cheap to scalarize.
129 // otherwise return NULL.
130 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
131 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
134 // Create a scalar PHI node that will replace the vector PHI node
135 // just before the current PHI node.
136 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
137 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
138 // Scalarize each PHI operand.
139 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
140 Value *PHIInVal = PN->getIncomingValue(i);
141 BasicBlock *inBB = PN->getIncomingBlock(i);
142 Value *Elt = EI.getIndexOperand();
143 // If the operand is the PHI induction variable:
144 if (PHIInVal == PHIUser) {
145 // Scalarize the binary operation. Its first operand is the
146 // scalar PHI and the second operand is extracted from the other
148 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
149 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
150 Value *Op = InsertNewInstWith(
151 ExtractElementInst::Create(B0->getOperand(opId), Elt,
152 B0->getOperand(opId)->getName() + ".Elt"),
154 Value *newPHIUser = InsertNewInstWith(
155 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
156 scalarPHI->addIncoming(newPHIUser, inBB);
158 // Scalarize PHI input:
159 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
160 // Insert the new instruction into the predecessor basic block.
161 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
162 BasicBlock::iterator InsertPos;
163 if (pos && !isa<PHINode>(pos)) {
167 InsertPos = inBB->getFirstInsertionPt();
170 InsertNewInstWith(newEI, *InsertPos);
172 scalarPHI->addIncoming(newEI, inBB);
175 return ReplaceInstUsesWith(EI, scalarPHI);
178 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
179 // If vector val is constant with all elements the same, replace EI with
180 // that element. We handle a known element # below.
181 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
182 if (CheapToScalarize(C, false))
183 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
185 // If extracting a specified index from the vector, see if we can recursively
186 // find a previously computed scalar that was inserted into the vector.
187 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
188 unsigned IndexVal = IdxC->getZExtValue();
189 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
191 // If this is extracting an invalid index, turn this into undef, to avoid
192 // crashing the code below.
193 if (IndexVal >= VectorWidth)
194 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
196 // This instruction only demands the single element from the input vector.
197 // If the input vector has a single use, simplify it based on this use
199 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
200 APInt UndefElts(VectorWidth, 0);
201 APInt DemandedMask(VectorWidth, 0);
202 DemandedMask.setBit(IndexVal);
203 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
204 DemandedMask, UndefElts)) {
210 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
211 return ReplaceInstUsesWith(EI, Elt);
213 // If the this extractelement is directly using a bitcast from a vector of
214 // the same number of elements, see if we can find the source element from
215 // it. In this case, we will end up needing to bitcast the scalars.
216 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
217 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
218 if (VT->getNumElements() == VectorWidth)
219 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
220 return new BitCastInst(Elt, EI.getType());
223 // If there's a vector PHI feeding a scalar use through this extractelement
224 // instruction, try to scalarize the PHI.
225 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
226 Instruction *scalarPHI = scalarizePHI(EI, PN);
232 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
233 // Push extractelement into predecessor operation if legal and
234 // profitable to do so
235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
236 if (I->hasOneUse() &&
237 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
239 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
240 EI.getName()+".lhs");
242 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
243 EI.getName()+".rhs");
244 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
246 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
247 // Extracting the inserted element?
248 if (IE->getOperand(2) == EI.getOperand(1))
249 return ReplaceInstUsesWith(EI, IE->getOperand(1));
250 // If the inserted and extracted elements are constants, they must not
251 // be the same value, extract from the pre-inserted value instead.
252 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
253 Worklist.AddValue(EI.getOperand(0));
254 EI.setOperand(0, IE->getOperand(0));
257 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
258 // If this is extracting an element from a shufflevector, figure out where
259 // it came from and extract from the appropriate input element instead.
260 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
261 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
264 SVI->getOperand(0)->getType()->getVectorNumElements();
267 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
268 if (SrcIdx < (int)LHSWidth)
269 Src = SVI->getOperand(0);
272 Src = SVI->getOperand(1);
274 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
275 return ExtractElementInst::Create(Src,
276 ConstantInt::get(Int32Ty,
279 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
280 // Canonicalize extractelement(cast) -> cast(extractelement)
281 // bitcasts can change the number of vector elements and they cost nothing
282 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
283 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
284 EI.getIndexOperand());
285 Worklist.AddValue(EE);
286 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
288 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
289 if (SI->hasOneUse()) {
290 // TODO: For a select on vectors, it might be useful to do this if it
291 // has multiple extractelement uses. For vector select, that seems to
292 // fight the vectorizer.
294 // If we are extracting an element from a vector select or a select on
295 // vectors, a select on the scalars extracted from the vector arguments.
296 Value *TrueVal = SI->getTrueValue();
297 Value *FalseVal = SI->getFalseValue();
299 Value *Cond = SI->getCondition();
300 if (Cond->getType()->isVectorTy()) {
301 Cond = Builder->CreateExtractElement(Cond,
302 EI.getIndexOperand(),
303 Cond->getName() + ".elt");
307 = Builder->CreateExtractElement(TrueVal,
308 EI.getIndexOperand(),
309 TrueVal->getName() + ".elt");
312 = Builder->CreateExtractElement(FalseVal,
313 EI.getIndexOperand(),
314 FalseVal->getName() + ".elt");
315 return SelectInst::Create(Cond,
318 SI->getName() + ".elt");
325 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
326 /// elements from either LHS or RHS, return the shuffle mask and true.
327 /// Otherwise, return false.
328 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
329 SmallVectorImpl<Constant*> &Mask) {
330 assert(LHS->getType() == RHS->getType() &&
331 "Invalid CollectSingleShuffleElements");
332 unsigned NumElts = V->getType()->getVectorNumElements();
334 if (isa<UndefValue>(V)) {
335 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
340 for (unsigned i = 0; i != NumElts; ++i)
341 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
346 for (unsigned i = 0; i != NumElts; ++i)
347 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
352 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
353 // If this is an insert of an extract from some other vector, include it.
354 Value *VecOp = IEI->getOperand(0);
355 Value *ScalarOp = IEI->getOperand(1);
356 Value *IdxOp = IEI->getOperand(2);
358 if (!isa<ConstantInt>(IdxOp))
360 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
362 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
363 // Okay, we can handle this if the vector we are insertinting into is
365 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
366 // If so, update the mask to reflect the inserted undef.
367 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
370 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
371 if (isa<ConstantInt>(EI->getOperand(1))) {
372 unsigned ExtractedIdx =
373 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
374 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
376 // This must be extracting from either LHS or RHS.
377 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
378 // Okay, we can handle this if the vector we are insertinting into is
380 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
381 // If so, update the mask to reflect the inserted value.
382 if (EI->getOperand(0) == LHS) {
383 Mask[InsertedIdx % NumElts] =
384 ConstantInt::get(Type::getInt32Ty(V->getContext()),
387 assert(EI->getOperand(0) == RHS);
388 Mask[InsertedIdx % NumElts] =
389 ConstantInt::get(Type::getInt32Ty(V->getContext()),
390 ExtractedIdx + NumLHSElts);
403 /// We are building a shuffle to create V, which is a sequence of insertelement,
404 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
405 /// not rely on the second vector source. Return an std::pair containing the
406 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
407 /// parameter as required.
409 /// Note: we intentionally don't try to fold earlier shuffles since they have
410 /// often been chosen carefully to be efficiently implementable on the target.
411 typedef std::pair<Value *, Value *> ShuffleOps;
413 static ShuffleOps CollectShuffleElements(Value *V,
414 SmallVectorImpl<Constant *> &Mask,
415 Value *PermittedRHS) {
416 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
417 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
419 if (isa<UndefValue>(V)) {
420 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
421 return std::make_pair(
422 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
425 if (isa<ConstantAggregateZero>(V)) {
426 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
427 return std::make_pair(V, nullptr);
430 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
431 // If this is an insert of an extract from some other vector, include it.
432 Value *VecOp = IEI->getOperand(0);
433 Value *ScalarOp = IEI->getOperand(1);
434 Value *IdxOp = IEI->getOperand(2);
436 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
437 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
438 unsigned ExtractedIdx =
439 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
440 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
442 // Either the extracted from or inserted into vector must be RHSVec,
443 // otherwise we'd end up with a shuffle of three inputs.
444 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == 0) {
445 Value *RHS = EI->getOperand(0);
446 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
447 assert(LR.second == 0 || LR.second == RHS);
449 if (LR.first->getType() != RHS->getType()) {
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, 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 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
493 Value *VecOp = IE.getOperand(0);
494 Value *ScalarOp = IE.getOperand(1);
495 Value *IdxOp = IE.getOperand(2);
497 // Inserting an undef or into an undefined place, remove this.
498 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
499 ReplaceInstUsesWith(IE, VecOp);
501 // If the inserted element was extracted from some other vector, and if the
502 // indexes are constant, try to turn this into a shufflevector operation.
503 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
504 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
505 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
506 unsigned NumExtractVectorElts =
507 EI->getOperand(0)->getType()->getVectorNumElements();
508 unsigned ExtractedIdx =
509 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
510 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
512 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
513 return ReplaceInstUsesWith(IE, VecOp);
515 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
516 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
518 // If we are extracting a value from a vector, then inserting it right
519 // back into the same place, just use the input vector.
520 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
521 return ReplaceInstUsesWith(IE, VecOp);
523 // If this insertelement isn't used by some other insertelement, turn it
524 // (and any insertelements it points to), into one big shuffle.
525 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
526 SmallVector<Constant*, 16> Mask;
527 ShuffleOps LR = CollectShuffleElements(&IE, Mask, 0);
529 // The proposed shuffle may be trivial, in which case we shouldn't
530 // perform the combine.
531 if (LR.first != &IE && LR.second != &IE) {
532 // We now have a shuffle of LHS, RHS, Mask.
533 if (LR.second == 0) LR.second = UndefValue::get(LR.first->getType());
534 return new ShuffleVectorInst(LR.first, LR.second,
535 ConstantVector::get(Mask));
541 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
542 APInt UndefElts(VWidth, 0);
543 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
544 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
546 return ReplaceInstUsesWith(IE, V);
553 /// Return true if we can evaluate the specified expression tree if the vector
554 /// elements were shuffled in a different order.
555 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
556 unsigned Depth = 5) {
557 // We can always reorder the elements of a constant.
558 if (isa<Constant>(V))
561 // We won't reorder vector arguments. No IPO here.
562 Instruction *I = dyn_cast<Instruction>(V);
563 if (!I) return false;
565 // Two users may expect different orders of the elements. Don't try it.
569 if (Depth == 0) return false;
571 switch (I->getOpcode()) {
572 case Instruction::Add:
573 case Instruction::FAdd:
574 case Instruction::Sub:
575 case Instruction::FSub:
576 case Instruction::Mul:
577 case Instruction::FMul:
578 case Instruction::UDiv:
579 case Instruction::SDiv:
580 case Instruction::FDiv:
581 case Instruction::URem:
582 case Instruction::SRem:
583 case Instruction::FRem:
584 case Instruction::Shl:
585 case Instruction::LShr:
586 case Instruction::AShr:
587 case Instruction::And:
588 case Instruction::Or:
589 case Instruction::Xor:
590 case Instruction::ICmp:
591 case Instruction::FCmp:
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 case Instruction::FPToUI:
596 case Instruction::FPToSI:
597 case Instruction::UIToFP:
598 case Instruction::SIToFP:
599 case Instruction::FPTrunc:
600 case Instruction::FPExt:
601 case Instruction::GetElementPtr: {
602 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
603 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
608 case Instruction::InsertElement: {
609 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
610 if (!CI) return false;
611 int ElementNumber = CI->getLimitedValue();
613 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
614 // can't put an element into multiple indices.
615 bool SeenOnce = false;
616 for (int i = 0, e = Mask.size(); i != e; ++i) {
617 if (Mask[i] == ElementNumber) {
623 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
629 /// Rebuild a new instruction just like 'I' but with the new operands given.
630 /// In the event of type mismatch, the type of the operands is correct.
631 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
632 // We don't want to use the IRBuilder here because we want the replacement
633 // instructions to appear next to 'I', not the builder's insertion point.
634 switch (I->getOpcode()) {
635 case Instruction::Add:
636 case Instruction::FAdd:
637 case Instruction::Sub:
638 case Instruction::FSub:
639 case Instruction::Mul:
640 case Instruction::FMul:
641 case Instruction::UDiv:
642 case Instruction::SDiv:
643 case Instruction::FDiv:
644 case Instruction::URem:
645 case Instruction::SRem:
646 case Instruction::FRem:
647 case Instruction::Shl:
648 case Instruction::LShr:
649 case Instruction::AShr:
650 case Instruction::And:
651 case Instruction::Or:
652 case Instruction::Xor: {
653 BinaryOperator *BO = cast<BinaryOperator>(I);
654 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
655 BinaryOperator *New =
656 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
657 NewOps[0], NewOps[1], "", BO);
658 if (isa<OverflowingBinaryOperator>(BO)) {
659 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
660 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
662 if (isa<PossiblyExactOperator>(BO)) {
663 New->setIsExact(BO->isExact());
665 if (isa<FPMathOperator>(BO))
666 New->copyFastMathFlags(I);
669 case Instruction::ICmp:
670 assert(NewOps.size() == 2 && "icmp with #ops != 2");
671 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
672 NewOps[0], NewOps[1]);
673 case Instruction::FCmp:
674 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
675 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
676 NewOps[0], NewOps[1]);
677 case Instruction::Trunc:
678 case Instruction::ZExt:
679 case Instruction::SExt:
680 case Instruction::FPToUI:
681 case Instruction::FPToSI:
682 case Instruction::UIToFP:
683 case Instruction::SIToFP:
684 case Instruction::FPTrunc:
685 case Instruction::FPExt: {
686 // It's possible that the mask has a different number of elements from
687 // the original cast. We recompute the destination type to match the mask.
689 VectorType::get(I->getType()->getScalarType(),
690 NewOps[0]->getType()->getVectorNumElements());
691 assert(NewOps.size() == 1 && "cast with #ops != 1");
692 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
695 case Instruction::GetElementPtr: {
696 Value *Ptr = NewOps[0];
697 ArrayRef<Value*> Idx = NewOps.slice(1);
698 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
699 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
703 llvm_unreachable("failed to rebuild vector instructions");
707 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
708 // Mask.size() does not need to be equal to the number of vector elements.
710 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
711 if (isa<UndefValue>(V)) {
712 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
715 if (isa<ConstantAggregateZero>(V)) {
716 return ConstantAggregateZero::get(
717 VectorType::get(V->getType()->getScalarType(),
720 if (Constant *C = dyn_cast<Constant>(V)) {
721 SmallVector<Constant *, 16> MaskValues;
722 for (int i = 0, e = Mask.size(); i != e; ++i) {
724 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
726 MaskValues.push_back(Builder->getInt32(Mask[i]));
728 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
729 ConstantVector::get(MaskValues));
732 Instruction *I = cast<Instruction>(V);
733 switch (I->getOpcode()) {
734 case Instruction::Add:
735 case Instruction::FAdd:
736 case Instruction::Sub:
737 case Instruction::FSub:
738 case Instruction::Mul:
739 case Instruction::FMul:
740 case Instruction::UDiv:
741 case Instruction::SDiv:
742 case Instruction::FDiv:
743 case Instruction::URem:
744 case Instruction::SRem:
745 case Instruction::FRem:
746 case Instruction::Shl:
747 case Instruction::LShr:
748 case Instruction::AShr:
749 case Instruction::And:
750 case Instruction::Or:
751 case Instruction::Xor:
752 case Instruction::ICmp:
753 case Instruction::FCmp:
754 case Instruction::Trunc:
755 case Instruction::ZExt:
756 case Instruction::SExt:
757 case Instruction::FPToUI:
758 case Instruction::FPToSI:
759 case Instruction::UIToFP:
760 case Instruction::SIToFP:
761 case Instruction::FPTrunc:
762 case Instruction::FPExt:
763 case Instruction::Select:
764 case Instruction::GetElementPtr: {
765 SmallVector<Value*, 8> NewOps;
766 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
767 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
768 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
770 NeedsRebuild |= (V != I->getOperand(i));
773 return BuildNew(I, NewOps);
777 case Instruction::InsertElement: {
778 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
780 // The insertelement was inserting at Element. Figure out which element
781 // that becomes after shuffling. The answer is guaranteed to be unique
782 // by CanEvaluateShuffled.
785 for (int e = Mask.size(); Index != e; ++Index) {
786 if (Mask[Index] == Element) {
792 // If element is not in Mask, no need to handle the operand 1 (element to
793 // be inserted). Just evaluate values in operand 0 according to Mask.
795 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
797 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
798 return InsertElementInst::Create(V, I->getOperand(1),
799 Builder->getInt32(Index), "", I);
802 llvm_unreachable("failed to reorder elements of vector instruction!");
805 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
806 Value *LHS = SVI.getOperand(0);
807 Value *RHS = SVI.getOperand(1);
808 SmallVector<int, 16> Mask = SVI.getShuffleMask();
810 bool MadeChange = false;
812 // Undefined shuffle mask -> undefined value.
813 if (isa<UndefValue>(SVI.getOperand(2)))
814 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
816 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
818 APInt UndefElts(VWidth, 0);
819 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
820 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
822 return ReplaceInstUsesWith(SVI, V);
823 LHS = SVI.getOperand(0);
824 RHS = SVI.getOperand(1);
828 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
830 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
831 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
832 if (LHS == RHS || isa<UndefValue>(LHS)) {
833 if (isa<UndefValue>(LHS) && LHS == RHS) {
834 // shuffle(undef,undef,mask) -> undef.
835 Value *Result = (VWidth == LHSWidth)
836 ? LHS : UndefValue::get(SVI.getType());
837 return ReplaceInstUsesWith(SVI, Result);
840 // Remap any references to RHS to use LHS.
841 SmallVector<Constant*, 16> Elts;
842 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
844 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
848 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
849 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
850 Mask[i] = -1; // Turn into undef.
851 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
853 Mask[i] = Mask[i] % e; // Force to LHS.
854 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
858 SVI.setOperand(0, SVI.getOperand(1));
859 SVI.setOperand(1, UndefValue::get(RHS->getType()));
860 SVI.setOperand(2, ConstantVector::get(Elts));
861 LHS = SVI.getOperand(0);
862 RHS = SVI.getOperand(1);
866 if (VWidth == LHSWidth) {
867 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
868 bool isLHSID = true, isRHSID = true;
870 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
871 if (Mask[i] < 0) continue; // Ignore undef values.
872 // Is this an identity shuffle of the LHS value?
873 isLHSID &= (Mask[i] == (int)i);
875 // Is this an identity shuffle of the RHS value?
876 isRHSID &= (Mask[i]-e == i);
879 // Eliminate identity shuffles.
880 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
881 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
884 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
885 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
886 return ReplaceInstUsesWith(SVI, V);
889 // If the LHS is a shufflevector itself, see if we can combine it with this
890 // one without producing an unusual shuffle.
891 // Cases that might be simplified:
893 // x1=shuffle(v1,v2,mask1)
894 // x=shuffle(x1,undef,mask)
896 // x=shuffle(v1,undef,newMask)
897 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
899 // x1=shuffle(v1,undef,mask1)
900 // x=shuffle(x1,x2,mask)
901 // where v1.size() == mask1.size()
903 // x=shuffle(v1,x2,newMask)
904 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
906 // x2=shuffle(v2,undef,mask2)
907 // x=shuffle(x1,x2,mask)
908 // where v2.size() == mask2.size()
910 // x=shuffle(x1,v2,newMask)
911 // newMask[i] = (mask[i] < x1.size())
912 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
914 // x1=shuffle(v1,undef,mask1)
915 // x2=shuffle(v2,undef,mask2)
916 // x=shuffle(x1,x2,mask)
917 // where v1.size() == v2.size()
919 // x=shuffle(v1,v2,newMask)
920 // newMask[i] = (mask[i] < x1.size())
921 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
923 // Here we are really conservative:
924 // we are absolutely afraid of producing a shuffle mask not in the input
925 // program, because the code gen may not be smart enough to turn a merged
926 // shuffle into two specific shuffles: it may produce worse code. As such,
927 // we only merge two shuffles if the result is either a splat or one of the
928 // input shuffle masks. In this case, merging the shuffles just removes
929 // one instruction, which we know is safe. This is good for things like
930 // turning: (splat(splat)) -> splat, or
931 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
932 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
933 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
935 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
938 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
940 if (!LHSShuffle && !RHSShuffle)
941 return MadeChange ? &SVI : 0;
943 Value* LHSOp0 = NULL;
944 Value* LHSOp1 = NULL;
945 Value* RHSOp0 = NULL;
946 unsigned LHSOp0Width = 0;
947 unsigned RHSOp0Width = 0;
949 LHSOp0 = LHSShuffle->getOperand(0);
950 LHSOp1 = LHSShuffle->getOperand(1);
951 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
954 RHSOp0 = RHSShuffle->getOperand(0);
955 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
961 if (isa<UndefValue>(RHS)) {
966 else if (LHSOp0Width == LHSWidth) {
971 if (RHSShuffle && RHSOp0Width == LHSWidth) {
975 if (LHSOp0 == RHSOp0) {
980 if (newLHS == LHS && newRHS == RHS)
981 return MadeChange ? &SVI : 0;
983 SmallVector<int, 16> LHSMask;
984 SmallVector<int, 16> RHSMask;
986 LHSMask = LHSShuffle->getShuffleMask();
987 if (RHSShuffle && newRHS != RHS)
988 RHSMask = RHSShuffle->getShuffleMask();
990 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
991 SmallVector<int, 16> newMask;
994 // Create a new mask for the new ShuffleVectorInst so that the new
995 // ShuffleVectorInst is equivalent to the original one.
996 for (unsigned i = 0; i < VWidth; ++i) {
999 // This element is an undef value.
1001 } else if (Mask[i] < (int)LHSWidth) {
1002 // This element is from left hand side vector operand.
1004 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1005 // new mask value for the element.
1006 if (newLHS != LHS) {
1007 eltMask = LHSMask[Mask[i]];
1008 // If the value selected is an undef value, explicitly specify it
1009 // with a -1 mask value.
1010 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1015 // This element is from right hand side vector operand
1017 // If the value selected is an undef value, explicitly specify it
1018 // with a -1 mask value. (case 1)
1019 if (isa<UndefValue>(RHS))
1021 // If RHS is going to be replaced (case 3 or 4), calculate the
1022 // new mask value for the element.
1023 else if (newRHS != RHS) {
1024 eltMask = RHSMask[Mask[i]-LHSWidth];
1025 // If the value selected is an undef value, explicitly specify it
1026 // with a -1 mask value.
1027 if (eltMask >= (int)RHSOp0Width) {
1028 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1029 && "should have been check above");
1033 eltMask = Mask[i]-LHSWidth;
1035 // If LHS's width is changed, shift the mask value accordingly.
1036 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1037 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1038 // If newRHS == newLHS, we want to remap any references from newRHS to
1039 // newLHS so that we can properly identify splats that may occur due to
1040 // obfuscation across the two vectors.
1041 if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
1042 eltMask += newLHSWidth;
1045 // Check if this could still be a splat.
1047 if (SplatElt >= 0 && SplatElt != eltMask)
1052 newMask.push_back(eltMask);
1055 // If the result mask is equal to one of the original shuffle masks,
1056 // or is a splat, do the replacement.
1057 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1058 SmallVector<Constant*, 16> Elts;
1059 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1060 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1061 if (newMask[i] < 0) {
1062 Elts.push_back(UndefValue::get(Int32Ty));
1064 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1068 newRHS = UndefValue::get(newLHS->getType());
1069 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1072 return MadeChange ? &SVI : 0;