1f22ef01cSRoman Divacky //===- InstCombineVectorOps.cpp -------------------------------------------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This file implements instcombine for ExtractElement, InsertElement and 11f22ef01cSRoman Divacky // ShuffleVector. 12f22ef01cSRoman Divacky // 13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 14f22ef01cSRoman Divacky 15ff0cc061SDimitry Andric #include "InstCombineInternal.h" 16ff0cc061SDimitry Andric #include "llvm/ADT/DenseMap.h" 17875ed548SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 18875ed548SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 1991bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h" 20f22ef01cSRoman Divacky using namespace llvm; 21139f7f9bSDimitry Andric using namespace PatternMatch; 22f22ef01cSRoman Divacky 2391bc56edSDimitry Andric #define DEBUG_TYPE "instcombine" 2491bc56edSDimitry Andric 257d523365SDimitry Andric /// Return true if the value is cheaper to scalarize than it is to leave as a 267d523365SDimitry Andric /// vector operation. isConstant indicates whether we're extracting one known 277d523365SDimitry Andric /// element. If false we're extracting a variable index. 287d523365SDimitry Andric static bool cheapToScalarize(Value *V, bool isConstant) { 29dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 30f22ef01cSRoman Divacky if (isConstant) return true; 31dff0c46cSDimitry Andric 32dff0c46cSDimitry Andric // If all elts are the same, we can extract it and use any of the values. 3385d60e68SDimitry Andric if (Constant *Op0 = C->getAggregateElement(0U)) { 3485d60e68SDimitry Andric for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; 3585d60e68SDimitry Andric ++i) 36dff0c46cSDimitry Andric if (C->getAggregateElement(i) != Op0) 37f22ef01cSRoman Divacky return false; 38f22ef01cSRoman Divacky return true; 39f22ef01cSRoman Divacky } 4085d60e68SDimitry Andric } 41f22ef01cSRoman Divacky Instruction *I = dyn_cast<Instruction>(V); 42f22ef01cSRoman Divacky if (!I) return false; 43f22ef01cSRoman Divacky 44f22ef01cSRoman Divacky // Insert element gets simplified to the inserted element or is deleted if 45f22ef01cSRoman Divacky // this is constant idx extract element and its a constant idx insertelt. 46f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::InsertElement && isConstant && 47f22ef01cSRoman Divacky isa<ConstantInt>(I->getOperand(2))) 48f22ef01cSRoman Divacky return true; 49f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::Load && I->hasOneUse()) 50f22ef01cSRoman Divacky return true; 51f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) 52f22ef01cSRoman Divacky if (BO->hasOneUse() && 537d523365SDimitry Andric (cheapToScalarize(BO->getOperand(0), isConstant) || 547d523365SDimitry Andric cheapToScalarize(BO->getOperand(1), isConstant))) 55f22ef01cSRoman Divacky return true; 56f22ef01cSRoman Divacky if (CmpInst *CI = dyn_cast<CmpInst>(I)) 57f22ef01cSRoman Divacky if (CI->hasOneUse() && 587d523365SDimitry Andric (cheapToScalarize(CI->getOperand(0), isConstant) || 597d523365SDimitry Andric cheapToScalarize(CI->getOperand(1), isConstant))) 60f22ef01cSRoman Divacky return true; 61f22ef01cSRoman Divacky 62f22ef01cSRoman Divacky return false; 63f22ef01cSRoman Divacky } 64f22ef01cSRoman Divacky 653ca95b02SDimitry Andric // If we have a PHI node with a vector type that is only used to feed 66f785676fSDimitry Andric // itself and be an operand of extractelement at a constant location, 67f785676fSDimitry Andric // try to replace the PHI of the vector type with a PHI of a scalar type. 68284c1978SDimitry Andric Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { 693ca95b02SDimitry Andric SmallVector<Instruction *, 2> Extracts; 703ca95b02SDimitry Andric // The users we want the PHI to have are: 713ca95b02SDimitry Andric // 1) The EI ExtractElement (we already know this) 723ca95b02SDimitry Andric // 2) Possibly more ExtractElements with the same index. 733ca95b02SDimitry Andric // 3) Another operand, which will feed back into the PHI. 743ca95b02SDimitry Andric Instruction *PHIUser = nullptr; 753ca95b02SDimitry Andric for (auto U : PN->users()) { 763ca95b02SDimitry Andric if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 773ca95b02SDimitry Andric if (EI.getIndexOperand() == EU->getIndexOperand()) 783ca95b02SDimitry Andric Extracts.push_back(EU); 793ca95b02SDimitry Andric else 8091bc56edSDimitry Andric return nullptr; 813ca95b02SDimitry Andric } else if (!PHIUser) { 823ca95b02SDimitry Andric PHIUser = cast<Instruction>(U); 833ca95b02SDimitry Andric } else { 843ca95b02SDimitry Andric return nullptr; 853ca95b02SDimitry Andric } 863ca95b02SDimitry Andric } 87284c1978SDimitry Andric 883ca95b02SDimitry Andric if (!PHIUser) 893ca95b02SDimitry Andric return nullptr; 90284c1978SDimitry Andric 91284c1978SDimitry Andric // Verify that this PHI user has one use, which is the PHI itself, 92284c1978SDimitry Andric // and that it is a binary operation which is cheap to scalarize. 93284c1978SDimitry Andric // otherwise return NULL. 9491bc56edSDimitry Andric if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 957d523365SDimitry Andric !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) 9691bc56edSDimitry Andric return nullptr; 97284c1978SDimitry Andric 98284c1978SDimitry Andric // Create a scalar PHI node that will replace the vector PHI node 99284c1978SDimitry Andric // just before the current PHI node. 100f785676fSDimitry Andric PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 101f785676fSDimitry Andric PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 102284c1978SDimitry Andric // Scalarize each PHI operand. 103284c1978SDimitry Andric for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 104284c1978SDimitry Andric Value *PHIInVal = PN->getIncomingValue(i); 105284c1978SDimitry Andric BasicBlock *inBB = PN->getIncomingBlock(i); 106284c1978SDimitry Andric Value *Elt = EI.getIndexOperand(); 107284c1978SDimitry Andric // If the operand is the PHI induction variable: 108284c1978SDimitry Andric if (PHIInVal == PHIUser) { 109284c1978SDimitry Andric // Scalarize the binary operation. Its first operand is the 11091bc56edSDimitry Andric // scalar PHI, and the second operand is extracted from the other 111284c1978SDimitry Andric // vector operand. 112284c1978SDimitry Andric BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 113284c1978SDimitry Andric unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 114f785676fSDimitry Andric Value *Op = InsertNewInstWith( 115f785676fSDimitry Andric ExtractElementInst::Create(B0->getOperand(opId), Elt, 116f785676fSDimitry Andric B0->getOperand(opId)->getName() + ".Elt"), 117284c1978SDimitry Andric *B0); 118f785676fSDimitry Andric Value *newPHIUser = InsertNewInstWith( 1193ca95b02SDimitry Andric BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 1203ca95b02SDimitry Andric scalarPHI, Op, B0), *B0); 121284c1978SDimitry Andric scalarPHI->addIncoming(newPHIUser, inBB); 122284c1978SDimitry Andric } else { 123284c1978SDimitry Andric // Scalarize PHI input: 124f785676fSDimitry Andric Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 125284c1978SDimitry Andric // Insert the new instruction into the predecessor basic block. 126284c1978SDimitry Andric Instruction *pos = dyn_cast<Instruction>(PHIInVal); 127284c1978SDimitry Andric BasicBlock::iterator InsertPos; 128284c1978SDimitry Andric if (pos && !isa<PHINode>(pos)) { 1297d523365SDimitry Andric InsertPos = ++pos->getIterator(); 130284c1978SDimitry Andric } else { 131284c1978SDimitry Andric InsertPos = inBB->getFirstInsertionPt(); 132284c1978SDimitry Andric } 133284c1978SDimitry Andric 134284c1978SDimitry Andric InsertNewInstWith(newEI, *InsertPos); 135284c1978SDimitry Andric 136284c1978SDimitry Andric scalarPHI->addIncoming(newEI, inBB); 137284c1978SDimitry Andric } 138284c1978SDimitry Andric } 1393ca95b02SDimitry Andric 1403ca95b02SDimitry Andric for (auto E : Extracts) 1413ca95b02SDimitry Andric replaceInstUsesWith(*E, scalarPHI); 1423ca95b02SDimitry Andric 1433ca95b02SDimitry Andric return &EI; 144284c1978SDimitry Andric } 145284c1978SDimitry Andric 146f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { 147875ed548SDimitry Andric if (Value *V = SimplifyExtractElementInst( 148d88c1a5aSDimitry Andric EI.getVectorOperand(), EI.getIndexOperand(), DL, &TLI, &DT, &AC)) 1493ca95b02SDimitry Andric return replaceInstUsesWith(EI, V); 150875ed548SDimitry Andric 151f22ef01cSRoman Divacky // If vector val is constant with all elements the same, replace EI with 152dff0c46cSDimitry Andric // that element. We handle a known element # below. 153dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 1547d523365SDimitry Andric if (cheapToScalarize(C, false)) 1553ca95b02SDimitry Andric return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 156f22ef01cSRoman Divacky 157f22ef01cSRoman Divacky // If extracting a specified index from the vector, see if we can recursively 158f22ef01cSRoman Divacky // find a previously computed scalar that was inserted into the vector. 159f22ef01cSRoman Divacky if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 160f22ef01cSRoman Divacky unsigned IndexVal = IdxC->getZExtValue(); 161f22ef01cSRoman Divacky unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 162f22ef01cSRoman Divacky 163875ed548SDimitry Andric // InstSimplify handles cases where the index is invalid. 164875ed548SDimitry Andric assert(IndexVal < VectorWidth); 165f22ef01cSRoman Divacky 166f22ef01cSRoman Divacky // This instruction only demands the single element from the input vector. 167f22ef01cSRoman Divacky // If the input vector has a single use, simplify it based on this use 168f22ef01cSRoman Divacky // property. 169f22ef01cSRoman Divacky if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 170f22ef01cSRoman Divacky APInt UndefElts(VectorWidth, 0); 171f22ef01cSRoman Divacky APInt DemandedMask(VectorWidth, 0); 1722754fe60SDimitry Andric DemandedMask.setBit(IndexVal); 173ff0cc061SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 174ff0cc061SDimitry Andric UndefElts)) { 175f22ef01cSRoman Divacky EI.setOperand(0, V); 176f22ef01cSRoman Divacky return &EI; 177f22ef01cSRoman Divacky } 178f22ef01cSRoman Divacky } 179f22ef01cSRoman Divacky 1807d523365SDimitry Andric // If this extractelement is directly using a bitcast from a vector of 181f22ef01cSRoman Divacky // the same number of elements, see if we can find the source element from 182f22ef01cSRoman Divacky // it. In this case, we will end up needing to bitcast the scalars. 183f22ef01cSRoman Divacky if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 184dff0c46cSDimitry Andric if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 185f22ef01cSRoman Divacky if (VT->getNumElements() == VectorWidth) 186875ed548SDimitry Andric if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 187f22ef01cSRoman Divacky return new BitCastInst(Elt, EI.getType()); 188f22ef01cSRoman Divacky } 189284c1978SDimitry Andric 190284c1978SDimitry Andric // If there's a vector PHI feeding a scalar use through this extractelement 191284c1978SDimitry Andric // instruction, try to scalarize the PHI. 192284c1978SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 193284c1978SDimitry Andric Instruction *scalarPHI = scalarizePHI(EI, PN); 194284c1978SDimitry Andric if (scalarPHI) 195f785676fSDimitry Andric return scalarPHI; 196284c1978SDimitry Andric } 197f22ef01cSRoman Divacky } 198f22ef01cSRoman Divacky 199f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 200f22ef01cSRoman Divacky // Push extractelement into predecessor operation if legal and 2017d523365SDimitry Andric // profitable to do so. 202f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 203f22ef01cSRoman Divacky if (I->hasOneUse() && 2047d523365SDimitry Andric cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 205f22ef01cSRoman Divacky Value *newEI0 = 206f22ef01cSRoman Divacky Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 207f22ef01cSRoman Divacky EI.getName()+".lhs"); 208f22ef01cSRoman Divacky Value *newEI1 = 209f22ef01cSRoman Divacky Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 210f22ef01cSRoman Divacky EI.getName()+".rhs"); 2113ca95b02SDimitry Andric return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 2123ca95b02SDimitry Andric newEI0, newEI1, BO); 213f22ef01cSRoman Divacky } 214f22ef01cSRoman Divacky } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 215f22ef01cSRoman Divacky // Extracting the inserted element? 216f22ef01cSRoman Divacky if (IE->getOperand(2) == EI.getOperand(1)) 2173ca95b02SDimitry Andric return replaceInstUsesWith(EI, IE->getOperand(1)); 218f22ef01cSRoman Divacky // If the inserted and extracted elements are constants, they must not 219f22ef01cSRoman Divacky // be the same value, extract from the pre-inserted value instead. 220f22ef01cSRoman Divacky if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 221f22ef01cSRoman Divacky Worklist.AddValue(EI.getOperand(0)); 222f22ef01cSRoman Divacky EI.setOperand(0, IE->getOperand(0)); 223f22ef01cSRoman Divacky return &EI; 224f22ef01cSRoman Divacky } 225f22ef01cSRoman Divacky } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 226f22ef01cSRoman Divacky // If this is extracting an element from a shufflevector, figure out where 227f22ef01cSRoman Divacky // it came from and extract from the appropriate input element instead. 228f22ef01cSRoman Divacky if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 229dff0c46cSDimitry Andric int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 230f22ef01cSRoman Divacky Value *Src; 231f22ef01cSRoman Divacky unsigned LHSWidth = 232dff0c46cSDimitry Andric SVI->getOperand(0)->getType()->getVectorNumElements(); 233f22ef01cSRoman Divacky 2342754fe60SDimitry Andric if (SrcIdx < 0) 2353ca95b02SDimitry Andric return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 2362754fe60SDimitry Andric if (SrcIdx < (int)LHSWidth) 237f22ef01cSRoman Divacky Src = SVI->getOperand(0); 2382754fe60SDimitry Andric else { 239f22ef01cSRoman Divacky SrcIdx -= LHSWidth; 240f22ef01cSRoman Divacky Src = SVI->getOperand(1); 241f22ef01cSRoman Divacky } 2426122f3e6SDimitry Andric Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 243f22ef01cSRoman Divacky return ExtractElementInst::Create(Src, 2442754fe60SDimitry Andric ConstantInt::get(Int32Ty, 245f22ef01cSRoman Divacky SrcIdx, false)); 246f22ef01cSRoman Divacky } 2473b0f4066SDimitry Andric } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 2487d523365SDimitry Andric // Canonicalize extractelement(cast) -> cast(extractelement). 2497d523365SDimitry Andric // Bitcasts can change the number of vector elements, and they cost 2507d523365SDimitry Andric // nothing. 251284c1978SDimitry Andric if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 2523b0f4066SDimitry Andric Value *EE = Builder->CreateExtractElement(CI->getOperand(0), 2533b0f4066SDimitry Andric EI.getIndexOperand()); 254284c1978SDimitry Andric Worklist.AddValue(EE); 2553b0f4066SDimitry Andric return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 256f22ef01cSRoman Divacky } 257f785676fSDimitry Andric } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 258f785676fSDimitry Andric if (SI->hasOneUse()) { 259f785676fSDimitry Andric // TODO: For a select on vectors, it might be useful to do this if it 260f785676fSDimitry Andric // has multiple extractelement uses. For vector select, that seems to 261f785676fSDimitry Andric // fight the vectorizer. 262f785676fSDimitry Andric 263f785676fSDimitry Andric // If we are extracting an element from a vector select or a select on 2647d523365SDimitry Andric // vectors, create a select on the scalars extracted from the vector 2657d523365SDimitry Andric // arguments. 266f785676fSDimitry Andric Value *TrueVal = SI->getTrueValue(); 267f785676fSDimitry Andric Value *FalseVal = SI->getFalseValue(); 268f785676fSDimitry Andric 269f785676fSDimitry Andric Value *Cond = SI->getCondition(); 270f785676fSDimitry Andric if (Cond->getType()->isVectorTy()) { 271f785676fSDimitry Andric Cond = Builder->CreateExtractElement(Cond, 272f785676fSDimitry Andric EI.getIndexOperand(), 273f785676fSDimitry Andric Cond->getName() + ".elt"); 274f785676fSDimitry Andric } 275f785676fSDimitry Andric 276f785676fSDimitry Andric Value *V1Elem 277f785676fSDimitry Andric = Builder->CreateExtractElement(TrueVal, 278f785676fSDimitry Andric EI.getIndexOperand(), 279f785676fSDimitry Andric TrueVal->getName() + ".elt"); 280f785676fSDimitry Andric 281f785676fSDimitry Andric Value *V2Elem 282f785676fSDimitry Andric = Builder->CreateExtractElement(FalseVal, 283f785676fSDimitry Andric EI.getIndexOperand(), 284f785676fSDimitry Andric FalseVal->getName() + ".elt"); 285f785676fSDimitry Andric return SelectInst::Create(Cond, 286f785676fSDimitry Andric V1Elem, 287f785676fSDimitry Andric V2Elem, 288f785676fSDimitry Andric SI->getName() + ".elt"); 289f785676fSDimitry Andric } 2903b0f4066SDimitry Andric } 291f22ef01cSRoman Divacky } 29291bc56edSDimitry Andric return nullptr; 293f22ef01cSRoman Divacky } 294f22ef01cSRoman Divacky 2957d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or 2967d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false. 2977d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 298dff0c46cSDimitry Andric SmallVectorImpl<Constant*> &Mask) { 29991bc56edSDimitry Andric assert(LHS->getType() == RHS->getType() && 300f22ef01cSRoman Divacky "Invalid CollectSingleShuffleElements"); 301f785676fSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 302f22ef01cSRoman Divacky 303f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 304f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 305f22ef01cSRoman Divacky return true; 306f22ef01cSRoman Divacky } 307f22ef01cSRoman Divacky 308f22ef01cSRoman Divacky if (V == LHS) { 309f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 310f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 311f22ef01cSRoman Divacky return true; 312f22ef01cSRoman Divacky } 313f22ef01cSRoman Divacky 314f22ef01cSRoman Divacky if (V == RHS) { 315f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 316f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 317f22ef01cSRoman Divacky i+NumElts)); 318f22ef01cSRoman Divacky return true; 319f22ef01cSRoman Divacky } 320f22ef01cSRoman Divacky 321f22ef01cSRoman Divacky if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 322f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 323f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 324f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 325f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 326f22ef01cSRoman Divacky 327f22ef01cSRoman Divacky if (!isa<ConstantInt>(IdxOp)) 328f22ef01cSRoman Divacky return false; 329f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 330f22ef01cSRoman Divacky 331f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 33291bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 333f22ef01cSRoman Divacky // transitively ok. 3347d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 335f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted undef. 336f22ef01cSRoman Divacky Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 337f22ef01cSRoman Divacky return true; 338f22ef01cSRoman Divacky } 339f22ef01cSRoman Divacky } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 34091bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1))) { 341f22ef01cSRoman Divacky unsigned ExtractedIdx = 342f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 34391bc56edSDimitry Andric unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 344f22ef01cSRoman Divacky 345f22ef01cSRoman Divacky // This must be extracting from either LHS or RHS. 346f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 34791bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 348f22ef01cSRoman Divacky // transitively ok. 3497d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 350f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted value. 351f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS) { 352f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 353f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 354f22ef01cSRoman Divacky ExtractedIdx); 355f22ef01cSRoman Divacky } else { 356f22ef01cSRoman Divacky assert(EI->getOperand(0) == RHS); 357f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 358f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 35991bc56edSDimitry Andric ExtractedIdx + NumLHSElts); 360f22ef01cSRoman Divacky } 361f22ef01cSRoman Divacky return true; 362f22ef01cSRoman Divacky } 363f22ef01cSRoman Divacky } 364f22ef01cSRoman Divacky } 365f22ef01cSRoman Divacky } 366f22ef01cSRoman Divacky } 367f22ef01cSRoman Divacky 368f22ef01cSRoman Divacky return false; 369f22ef01cSRoman Divacky } 370f22ef01cSRoman Divacky 3717d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we 3727d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single 3737d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs. 3747d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt, 3757d523365SDimitry Andric ExtractElementInst *ExtElt, 3767d523365SDimitry Andric InstCombiner &IC) { 3777d523365SDimitry Andric VectorType *InsVecType = InsElt->getType(); 3787d523365SDimitry Andric VectorType *ExtVecType = ExtElt->getVectorOperandType(); 3797d523365SDimitry Andric unsigned NumInsElts = InsVecType->getVectorNumElements(); 3807d523365SDimitry Andric unsigned NumExtElts = ExtVecType->getVectorNumElements(); 3817d523365SDimitry Andric 3827d523365SDimitry Andric // The inserted-to vector must be wider than the extracted-from vector. 3837d523365SDimitry Andric if (InsVecType->getElementType() != ExtVecType->getElementType() || 3847d523365SDimitry Andric NumExtElts >= NumInsElts) 3857d523365SDimitry Andric return; 3867d523365SDimitry Andric 3877d523365SDimitry Andric // Create a shuffle mask to widen the extended-from vector using undefined 3887d523365SDimitry Andric // values. The mask selects all of the values of the original vector followed 3897d523365SDimitry Andric // by as many undefined values as needed to create a vector of the same length 3907d523365SDimitry Andric // as the inserted-to vector. 3917d523365SDimitry Andric SmallVector<Constant *, 16> ExtendMask; 3927d523365SDimitry Andric IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 3937d523365SDimitry Andric for (unsigned i = 0; i < NumExtElts; ++i) 3947d523365SDimitry Andric ExtendMask.push_back(ConstantInt::get(IntType, i)); 3957d523365SDimitry Andric for (unsigned i = NumExtElts; i < NumInsElts; ++i) 3967d523365SDimitry Andric ExtendMask.push_back(UndefValue::get(IntType)); 3977d523365SDimitry Andric 3987d523365SDimitry Andric Value *ExtVecOp = ExtElt->getVectorOperand(); 399a8bcc4d8SDimitry Andric auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 400a8bcc4d8SDimitry Andric BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 401a8bcc4d8SDimitry Andric ? ExtVecOpInst->getParent() 402a8bcc4d8SDimitry Andric : ExtElt->getParent(); 403a8bcc4d8SDimitry Andric 404a8bcc4d8SDimitry Andric // TODO: This restriction matches the basic block check below when creating 405a8bcc4d8SDimitry Andric // new extractelement instructions. If that limitation is removed, this one 406a8bcc4d8SDimitry Andric // could also be removed. But for now, we just bail out to ensure that we 407a8bcc4d8SDimitry Andric // will replace the extractelement instruction that is feeding our 408a8bcc4d8SDimitry Andric // insertelement instruction. This allows the insertelement to then be 409a8bcc4d8SDimitry Andric // replaced by a shufflevector. If the insertelement is not replaced, we can 410a8bcc4d8SDimitry Andric // induce infinite looping because there's an optimization for extractelement 411a8bcc4d8SDimitry Andric // that will delete our widening shuffle. This would trigger another attempt 412a8bcc4d8SDimitry Andric // here to create that shuffle, and we spin forever. 413a8bcc4d8SDimitry Andric if (InsertionBlock != InsElt->getParent()) 414a8bcc4d8SDimitry Andric return; 415a8bcc4d8SDimitry Andric 416d88c1a5aSDimitry Andric // TODO: This restriction matches the check in visitInsertElementInst() and 417d88c1a5aSDimitry Andric // prevents an infinite loop caused by not turning the extract/insert pair 418d88c1a5aSDimitry Andric // into a shuffle. We really should not need either check, but we're lacking 419d88c1a5aSDimitry Andric // folds for shufflevectors because we're afraid to generate shuffle masks 420d88c1a5aSDimitry Andric // that the backend can't handle. 421d88c1a5aSDimitry Andric if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 422d88c1a5aSDimitry Andric return; 423d88c1a5aSDimitry Andric 4247d523365SDimitry Andric auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 4257d523365SDimitry Andric ConstantVector::get(ExtendMask)); 4267d523365SDimitry Andric 4274d0b32cdSDimitry Andric // Insert the new shuffle after the vector operand of the extract is defined 428444ed5c5SDimitry Andric // (as long as it's not a PHI) or at the start of the basic block of the 429444ed5c5SDimitry Andric // extract, so any subsequent extracts in the same basic block can use it. 430444ed5c5SDimitry Andric // TODO: Insert before the earliest ExtractElementInst that is replaced. 431444ed5c5SDimitry Andric if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 4324d0b32cdSDimitry Andric WideVec->insertAfter(ExtVecOpInst); 433444ed5c5SDimitry Andric else 4344d0b32cdSDimitry Andric IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 4354d0b32cdSDimitry Andric 4364d0b32cdSDimitry Andric // Replace extracts from the original narrow vector with extracts from the new 4374d0b32cdSDimitry Andric // wide vector. 4387d523365SDimitry Andric for (User *U : ExtVecOp->users()) { 4394d0b32cdSDimitry Andric ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 440444ed5c5SDimitry Andric if (!OldExt || OldExt->getParent() != WideVec->getParent()) 4414d0b32cdSDimitry Andric continue; 4427d523365SDimitry Andric auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 4437d523365SDimitry Andric NewExt->insertAfter(WideVec); 4443ca95b02SDimitry Andric IC.replaceInstUsesWith(*OldExt, NewExt); 4457d523365SDimitry Andric } 4467d523365SDimitry Andric } 44791bc56edSDimitry Andric 44891bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement, 44991bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or 45091bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the 45191bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask 45291bc56edSDimitry Andric /// parameter as required. 45391bc56edSDimitry Andric /// 45491bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have 45591bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target. 45691bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps; 45791bc56edSDimitry Andric 4587d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V, 45991bc56edSDimitry Andric SmallVectorImpl<Constant *> &Mask, 4607d523365SDimitry Andric Value *PermittedRHS, 4617d523365SDimitry Andric InstCombiner &IC) { 46291bc56edSDimitry Andric assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 463d88c1a5aSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 464f22ef01cSRoman Divacky 465f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 466f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 46791bc56edSDimitry Andric return std::make_pair( 46891bc56edSDimitry Andric PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 469dff0c46cSDimitry Andric } 470dff0c46cSDimitry Andric 471dff0c46cSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 472f22ef01cSRoman Divacky Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 47391bc56edSDimitry Andric return std::make_pair(V, nullptr); 474dff0c46cSDimitry Andric } 475dff0c46cSDimitry Andric 476dff0c46cSDimitry Andric if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 477f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 478f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 479f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 480f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 481f22ef01cSRoman Divacky 482f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 48391bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 484f22ef01cSRoman Divacky unsigned ExtractedIdx = 485f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 486f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 487f22ef01cSRoman Divacky 488f22ef01cSRoman Divacky // Either the extracted from or inserted into vector must be RHSVec, 489f22ef01cSRoman Divacky // otherwise we'd end up with a shuffle of three inputs. 49091bc56edSDimitry Andric if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 49191bc56edSDimitry Andric Value *RHS = EI->getOperand(0); 4927d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 49391bc56edSDimitry Andric assert(LR.second == nullptr || LR.second == RHS); 49491bc56edSDimitry Andric 49591bc56edSDimitry Andric if (LR.first->getType() != RHS->getType()) { 4967d523365SDimitry Andric // Although we are giving up for now, see if we can create extracts 4977d523365SDimitry Andric // that match the inserts for another round of combining. 4987d523365SDimitry Andric replaceExtractElements(IEI, EI, IC); 4997d523365SDimitry Andric 50091bc56edSDimitry Andric // We tried our best, but we can't find anything compatible with RHS 50191bc56edSDimitry Andric // further up the chain. Return a trivial shuffle. 50291bc56edSDimitry Andric for (unsigned i = 0; i < NumElts; ++i) 50391bc56edSDimitry Andric Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 50491bc56edSDimitry Andric return std::make_pair(V, nullptr); 50591bc56edSDimitry Andric } 50691bc56edSDimitry Andric 50791bc56edSDimitry Andric unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 508f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 509f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 51091bc56edSDimitry Andric NumLHSElts+ExtractedIdx); 51191bc56edSDimitry Andric return std::make_pair(LR.first, RHS); 512f22ef01cSRoman Divacky } 513f22ef01cSRoman Divacky 51491bc56edSDimitry Andric if (VecOp == PermittedRHS) { 51591bc56edSDimitry Andric // We've gone as far as we can: anything on the other side of the 51691bc56edSDimitry Andric // extractelement will already have been converted into a shuffle. 51791bc56edSDimitry Andric unsigned NumLHSElts = 51891bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 51991bc56edSDimitry Andric for (unsigned i = 0; i != NumElts; ++i) 52091bc56edSDimitry Andric Mask.push_back(ConstantInt::get( 52191bc56edSDimitry Andric Type::getInt32Ty(V->getContext()), 52291bc56edSDimitry Andric i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 52391bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 524f22ef01cSRoman Divacky } 525f22ef01cSRoman Divacky 526f22ef01cSRoman Divacky // If this insertelement is a chain that comes from exactly these two 527f22ef01cSRoman Divacky // vectors, return the vector and the effective shuffle. 52891bc56edSDimitry Andric if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 5297d523365SDimitry Andric collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 53091bc56edSDimitry Andric Mask)) 53191bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 532f22ef01cSRoman Divacky } 533f22ef01cSRoman Divacky } 534f22ef01cSRoman Divacky } 535f22ef01cSRoman Divacky 5367d523365SDimitry Andric // Otherwise, we can't do anything fancy. Return an identity vector. 537f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 538f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 53991bc56edSDimitry Andric return std::make_pair(V, nullptr); 54091bc56edSDimitry Andric } 54191bc56edSDimitry Andric 54291bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones: 54391bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 54491bc56edSDimitry Andric /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 54591bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the 54691bc56edSDimitry Andric /// first one, making the first one redundant. 54791bc56edSDimitry Andric /// It should be transformed to: 54891bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 54991bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 55091bc56edSDimitry Andric bool IsRedundant = false; 55191bc56edSDimitry Andric ArrayRef<unsigned int> FirstIndices = I.getIndices(); 55291bc56edSDimitry Andric 55391bc56edSDimitry Andric // If there is a chain of insertvalue instructions (each of them except the 55491bc56edSDimitry Andric // last one has only one use and it's another insertvalue insn from this 55591bc56edSDimitry Andric // chain), check if any of the 'children' uses the same indices as the first 55691bc56edSDimitry Andric // instruction. In this case, the first one is redundant. 55791bc56edSDimitry Andric Value *V = &I; 55891bc56edSDimitry Andric unsigned Depth = 0; 55991bc56edSDimitry Andric while (V->hasOneUse() && Depth < 10) { 56091bc56edSDimitry Andric User *U = V->user_back(); 56191bc56edSDimitry Andric auto UserInsInst = dyn_cast<InsertValueInst>(U); 56291bc56edSDimitry Andric if (!UserInsInst || U->getOperand(0) != V) 56391bc56edSDimitry Andric break; 56491bc56edSDimitry Andric if (UserInsInst->getIndices() == FirstIndices) { 56591bc56edSDimitry Andric IsRedundant = true; 56691bc56edSDimitry Andric break; 56791bc56edSDimitry Andric } 56891bc56edSDimitry Andric V = UserInsInst; 56991bc56edSDimitry Andric Depth++; 57091bc56edSDimitry Andric } 57191bc56edSDimitry Andric 57291bc56edSDimitry Andric if (IsRedundant) 5733ca95b02SDimitry Andric return replaceInstUsesWith(I, I.getOperand(0)); 57491bc56edSDimitry Andric return nullptr; 575f22ef01cSRoman Divacky } 576f22ef01cSRoman Divacky 577d88c1a5aSDimitry Andric static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 578d88c1a5aSDimitry Andric int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); 579d88c1a5aSDimitry Andric int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); 580d88c1a5aSDimitry Andric 581d88c1a5aSDimitry Andric // A vector select does not change the size of the operands. 582d88c1a5aSDimitry Andric if (MaskSize != VecSize) 583d88c1a5aSDimitry Andric return false; 584d88c1a5aSDimitry Andric 585d88c1a5aSDimitry Andric // Each mask element must be undefined or choose a vector element from one of 586d88c1a5aSDimitry Andric // the source operands without crossing vector lanes. 587d88c1a5aSDimitry Andric for (int i = 0; i != MaskSize; ++i) { 588d88c1a5aSDimitry Andric int Elt = Shuf.getMaskValue(i); 589d88c1a5aSDimitry Andric if (Elt != -1 && Elt != i && Elt != i + VecSize) 590d88c1a5aSDimitry Andric return false; 591d88c1a5aSDimitry Andric } 592d88c1a5aSDimitry Andric 593d88c1a5aSDimitry Andric return true; 594d88c1a5aSDimitry Andric } 595d88c1a5aSDimitry Andric 596d88c1a5aSDimitry Andric // Turn a chain of inserts that splats a value into a canonical insert + shuffle 597d88c1a5aSDimitry Andric // splat. That is: 598d88c1a5aSDimitry Andric // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> 599d88c1a5aSDimitry Andric // shufflevector(insertelt(X, %k, 0), undef, zero) 600d88c1a5aSDimitry Andric static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) { 601d88c1a5aSDimitry Andric // We are interested in the last insert in a chain. So, if this insert 602d88c1a5aSDimitry Andric // has a single user, and that user is an insert, bail. 603d88c1a5aSDimitry Andric if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) 604d88c1a5aSDimitry Andric return nullptr; 605d88c1a5aSDimitry Andric 606d88c1a5aSDimitry Andric VectorType *VT = cast<VectorType>(InsElt.getType()); 607d88c1a5aSDimitry Andric int NumElements = VT->getNumElements(); 608d88c1a5aSDimitry Andric 609d88c1a5aSDimitry Andric // Do not try to do this for a one-element vector, since that's a nop, 610d88c1a5aSDimitry Andric // and will cause an inf-loop. 611d88c1a5aSDimitry Andric if (NumElements == 1) 612d88c1a5aSDimitry Andric return nullptr; 613d88c1a5aSDimitry Andric 614d88c1a5aSDimitry Andric Value *SplatVal = InsElt.getOperand(1); 615d88c1a5aSDimitry Andric InsertElementInst *CurrIE = &InsElt; 616d88c1a5aSDimitry Andric SmallVector<bool, 16> ElementPresent(NumElements, false); 617d88c1a5aSDimitry Andric 618d88c1a5aSDimitry Andric // Walk the chain backwards, keeping track of which indices we inserted into, 619d88c1a5aSDimitry Andric // until we hit something that isn't an insert of the splatted value. 620d88c1a5aSDimitry Andric while (CurrIE) { 621d88c1a5aSDimitry Andric ConstantInt *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); 622d88c1a5aSDimitry Andric if (!Idx || CurrIE->getOperand(1) != SplatVal) 623d88c1a5aSDimitry Andric return nullptr; 624d88c1a5aSDimitry Andric 625d88c1a5aSDimitry Andric // Check none of the intermediate steps have any additional uses. 626d88c1a5aSDimitry Andric if ((CurrIE != &InsElt) && !CurrIE->hasOneUse()) 627d88c1a5aSDimitry Andric return nullptr; 628d88c1a5aSDimitry Andric 629d88c1a5aSDimitry Andric ElementPresent[Idx->getZExtValue()] = true; 630d88c1a5aSDimitry Andric CurrIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); 631d88c1a5aSDimitry Andric } 632d88c1a5aSDimitry Andric 633d88c1a5aSDimitry Andric // Make sure we've seen an insert into every element. 634d88c1a5aSDimitry Andric if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; })) 635d88c1a5aSDimitry Andric return nullptr; 636d88c1a5aSDimitry Andric 637d88c1a5aSDimitry Andric // All right, create the insert + shuffle. 638d88c1a5aSDimitry Andric Instruction *InsertFirst = InsertElementInst::Create( 639d88c1a5aSDimitry Andric UndefValue::get(VT), SplatVal, 640d88c1a5aSDimitry Andric ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), "", &InsElt); 641d88c1a5aSDimitry Andric 642d88c1a5aSDimitry Andric Constant *ZeroMask = ConstantAggregateZero::get( 643d88c1a5aSDimitry Andric VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements)); 644d88c1a5aSDimitry Andric 645d88c1a5aSDimitry Andric return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask); 646d88c1a5aSDimitry Andric } 647d88c1a5aSDimitry Andric 648d88c1a5aSDimitry Andric /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 649d88c1a5aSDimitry Andric /// --> shufflevector X, CVec', Mask' 650d88c1a5aSDimitry Andric static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 651d88c1a5aSDimitry Andric auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 652d88c1a5aSDimitry Andric // Bail out if the parent has more than one use. In that case, we'd be 653d88c1a5aSDimitry Andric // replacing the insertelt with a shuffle, and that's not a clear win. 654d88c1a5aSDimitry Andric if (!Inst || !Inst->hasOneUse()) 655d88c1a5aSDimitry Andric return nullptr; 656d88c1a5aSDimitry Andric if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 657d88c1a5aSDimitry Andric // The shuffle must have a constant vector operand. The insertelt must have 658d88c1a5aSDimitry Andric // a constant scalar being inserted at a constant position in the vector. 659d88c1a5aSDimitry Andric Constant *ShufConstVec, *InsEltScalar; 660d88c1a5aSDimitry Andric uint64_t InsEltIndex; 661d88c1a5aSDimitry Andric if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 662d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 663d88c1a5aSDimitry Andric !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 664d88c1a5aSDimitry Andric return nullptr; 665d88c1a5aSDimitry Andric 666d88c1a5aSDimitry Andric // Adding an element to an arbitrary shuffle could be expensive, but a 667d88c1a5aSDimitry Andric // shuffle that selects elements from vectors without crossing lanes is 668d88c1a5aSDimitry Andric // assumed cheap. 669d88c1a5aSDimitry Andric // If we're just adding a constant into that shuffle, it will still be 670d88c1a5aSDimitry Andric // cheap. 671d88c1a5aSDimitry Andric if (!isShuffleEquivalentToSelect(*Shuf)) 672d88c1a5aSDimitry Andric return nullptr; 673d88c1a5aSDimitry Andric 674d88c1a5aSDimitry Andric // From the above 'select' check, we know that the mask has the same number 675d88c1a5aSDimitry Andric // of elements as the vector input operands. We also know that each constant 676d88c1a5aSDimitry Andric // input element is used in its lane and can not be used more than once by 677d88c1a5aSDimitry Andric // the shuffle. Therefore, replace the constant in the shuffle's constant 678d88c1a5aSDimitry Andric // vector with the insertelt constant. Replace the constant in the shuffle's 679d88c1a5aSDimitry Andric // mask vector with the insertelt index plus the length of the vector 680d88c1a5aSDimitry Andric // (because the constant vector operand of a shuffle is always the 2nd 681d88c1a5aSDimitry Andric // operand). 682d88c1a5aSDimitry Andric Constant *Mask = Shuf->getMask(); 683d88c1a5aSDimitry Andric unsigned NumElts = Mask->getType()->getVectorNumElements(); 684d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewShufElts(NumElts); 685d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewMaskElts(NumElts); 686d88c1a5aSDimitry Andric for (unsigned I = 0; I != NumElts; ++I) { 687d88c1a5aSDimitry Andric if (I == InsEltIndex) { 688d88c1a5aSDimitry Andric NewShufElts[I] = InsEltScalar; 689d88c1a5aSDimitry Andric Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); 690d88c1a5aSDimitry Andric NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); 691d88c1a5aSDimitry Andric } else { 692d88c1a5aSDimitry Andric // Copy over the existing values. 693d88c1a5aSDimitry Andric NewShufElts[I] = ShufConstVec->getAggregateElement(I); 694d88c1a5aSDimitry Andric NewMaskElts[I] = Mask->getAggregateElement(I); 695d88c1a5aSDimitry Andric } 696d88c1a5aSDimitry Andric } 697d88c1a5aSDimitry Andric 698d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 699d88c1a5aSDimitry Andric // original insertelt. The old shuffle will be dead now. 700d88c1a5aSDimitry Andric return new ShuffleVectorInst(Shuf->getOperand(0), 701d88c1a5aSDimitry Andric ConstantVector::get(NewShufElts), 702d88c1a5aSDimitry Andric ConstantVector::get(NewMaskElts)); 703d88c1a5aSDimitry Andric } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 704d88c1a5aSDimitry Andric // Transform sequences of insertelements ops with constant data/indexes into 705d88c1a5aSDimitry Andric // a single shuffle op. 706d88c1a5aSDimitry Andric unsigned NumElts = InsElt.getType()->getNumElements(); 707d88c1a5aSDimitry Andric 708d88c1a5aSDimitry Andric uint64_t InsertIdx[2]; 709d88c1a5aSDimitry Andric Constant *Val[2]; 710d88c1a5aSDimitry Andric if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 711d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(Val[0])) || 712d88c1a5aSDimitry Andric !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 713d88c1a5aSDimitry Andric !match(IEI->getOperand(1), m_Constant(Val[1]))) 714d88c1a5aSDimitry Andric return nullptr; 715d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Values(NumElts); 716d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Mask(NumElts); 717d88c1a5aSDimitry Andric auto ValI = std::begin(Val); 718d88c1a5aSDimitry Andric // Generate new constant vector and mask. 719d88c1a5aSDimitry Andric // We have 2 values/masks from the insertelements instructions. Insert them 720d88c1a5aSDimitry Andric // into new value/mask vectors. 721d88c1a5aSDimitry Andric for (uint64_t I : InsertIdx) { 722d88c1a5aSDimitry Andric if (!Values[I]) { 723d88c1a5aSDimitry Andric assert(!Mask[I]); 724d88c1a5aSDimitry Andric Values[I] = *ValI; 725d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 726d88c1a5aSDimitry Andric NumElts + I); 727d88c1a5aSDimitry Andric } 728d88c1a5aSDimitry Andric ++ValI; 729d88c1a5aSDimitry Andric } 730d88c1a5aSDimitry Andric // Remaining values are filled with 'undef' values. 731d88c1a5aSDimitry Andric for (unsigned I = 0; I < NumElts; ++I) { 732d88c1a5aSDimitry Andric if (!Values[I]) { 733d88c1a5aSDimitry Andric assert(!Mask[I]); 734d88c1a5aSDimitry Andric Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 735d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); 736d88c1a5aSDimitry Andric } 737d88c1a5aSDimitry Andric } 738d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 739d88c1a5aSDimitry Andric // original insertelt. 740d88c1a5aSDimitry Andric return new ShuffleVectorInst(IEI->getOperand(0), 741d88c1a5aSDimitry Andric ConstantVector::get(Values), 742d88c1a5aSDimitry Andric ConstantVector::get(Mask)); 743d88c1a5aSDimitry Andric } 744d88c1a5aSDimitry Andric return nullptr; 745d88c1a5aSDimitry Andric } 746d88c1a5aSDimitry Andric 747f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 748f22ef01cSRoman Divacky Value *VecOp = IE.getOperand(0); 749f22ef01cSRoman Divacky Value *ScalarOp = IE.getOperand(1); 750f22ef01cSRoman Divacky Value *IdxOp = IE.getOperand(2); 751f22ef01cSRoman Divacky 752f22ef01cSRoman Divacky // Inserting an undef or into an undefined place, remove this. 753f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 7543ca95b02SDimitry Andric replaceInstUsesWith(IE, VecOp); 755f22ef01cSRoman Divacky 756f22ef01cSRoman Divacky // If the inserted element was extracted from some other vector, and if the 757f22ef01cSRoman Divacky // indexes are constant, try to turn this into a shufflevector operation. 758f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 75991bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 76091bc56edSDimitry Andric unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 76191bc56edSDimitry Andric unsigned NumExtractVectorElts = 76291bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 763f22ef01cSRoman Divacky unsigned ExtractedIdx = 764f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 765f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 766f22ef01cSRoman Divacky 76791bc56edSDimitry Andric if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 7683ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 769f22ef01cSRoman Divacky 77091bc56edSDimitry Andric if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 7713ca95b02SDimitry Andric return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 772f22ef01cSRoman Divacky 773f22ef01cSRoman Divacky // If we are extracting a value from a vector, then inserting it right 774f22ef01cSRoman Divacky // back into the same place, just use the input vector. 775f22ef01cSRoman Divacky if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 7763ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 777f22ef01cSRoman Divacky 778f22ef01cSRoman Divacky // If this insertelement isn't used by some other insertelement, turn it 779f22ef01cSRoman Divacky // (and any insertelements it points to), into one big shuffle. 78091bc56edSDimitry Andric if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 781dff0c46cSDimitry Andric SmallVector<Constant*, 16> Mask; 7827d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 78391bc56edSDimitry Andric 78491bc56edSDimitry Andric // The proposed shuffle may be trivial, in which case we shouldn't 78591bc56edSDimitry Andric // perform the combine. 78691bc56edSDimitry Andric if (LR.first != &IE && LR.second != &IE) { 787f22ef01cSRoman Divacky // We now have a shuffle of LHS, RHS, Mask. 78891bc56edSDimitry Andric if (LR.second == nullptr) 78991bc56edSDimitry Andric LR.second = UndefValue::get(LR.first->getType()); 79091bc56edSDimitry Andric return new ShuffleVectorInst(LR.first, LR.second, 79191bc56edSDimitry Andric ConstantVector::get(Mask)); 79291bc56edSDimitry Andric } 793f22ef01cSRoman Divacky } 794f22ef01cSRoman Divacky } 795f22ef01cSRoman Divacky } 796f22ef01cSRoman Divacky 797d88c1a5aSDimitry Andric unsigned VWidth = VecOp->getType()->getVectorNumElements(); 798f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 799f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 8002754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 8012754fe60SDimitry Andric if (V != &IE) 8023ca95b02SDimitry Andric return replaceInstUsesWith(IE, V); 803f22ef01cSRoman Divacky return &IE; 8042754fe60SDimitry Andric } 805f22ef01cSRoman Divacky 806d88c1a5aSDimitry Andric if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 807d88c1a5aSDimitry Andric return Shuf; 808d88c1a5aSDimitry Andric 809d88c1a5aSDimitry Andric // Turn a sequence of inserts that broadcasts a scalar into a single 810d88c1a5aSDimitry Andric // insert + shufflevector. 811d88c1a5aSDimitry Andric if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE)) 812d88c1a5aSDimitry Andric return Broadcast; 813d88c1a5aSDimitry Andric 81491bc56edSDimitry Andric return nullptr; 815f22ef01cSRoman Divacky } 816f22ef01cSRoman Divacky 817f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector 818f785676fSDimitry Andric /// elements were shuffled in a different order. 819f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 820f785676fSDimitry Andric unsigned Depth = 5) { 821f785676fSDimitry Andric // We can always reorder the elements of a constant. 822f785676fSDimitry Andric if (isa<Constant>(V)) 823f785676fSDimitry Andric return true; 824f785676fSDimitry Andric 825f785676fSDimitry Andric // We won't reorder vector arguments. No IPO here. 826f785676fSDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 827f785676fSDimitry Andric if (!I) return false; 828f785676fSDimitry Andric 829f785676fSDimitry Andric // Two users may expect different orders of the elements. Don't try it. 830f785676fSDimitry Andric if (!I->hasOneUse()) 831f785676fSDimitry Andric return false; 832f785676fSDimitry Andric 833f785676fSDimitry Andric if (Depth == 0) return false; 834f785676fSDimitry Andric 835f785676fSDimitry Andric switch (I->getOpcode()) { 836f785676fSDimitry Andric case Instruction::Add: 837f785676fSDimitry Andric case Instruction::FAdd: 838f785676fSDimitry Andric case Instruction::Sub: 839f785676fSDimitry Andric case Instruction::FSub: 840f785676fSDimitry Andric case Instruction::Mul: 841f785676fSDimitry Andric case Instruction::FMul: 842f785676fSDimitry Andric case Instruction::UDiv: 843f785676fSDimitry Andric case Instruction::SDiv: 844f785676fSDimitry Andric case Instruction::FDiv: 845f785676fSDimitry Andric case Instruction::URem: 846f785676fSDimitry Andric case Instruction::SRem: 847f785676fSDimitry Andric case Instruction::FRem: 848f785676fSDimitry Andric case Instruction::Shl: 849f785676fSDimitry Andric case Instruction::LShr: 850f785676fSDimitry Andric case Instruction::AShr: 851f785676fSDimitry Andric case Instruction::And: 852f785676fSDimitry Andric case Instruction::Or: 853f785676fSDimitry Andric case Instruction::Xor: 854f785676fSDimitry Andric case Instruction::ICmp: 855f785676fSDimitry Andric case Instruction::FCmp: 856f785676fSDimitry Andric case Instruction::Trunc: 857f785676fSDimitry Andric case Instruction::ZExt: 858f785676fSDimitry Andric case Instruction::SExt: 859f785676fSDimitry Andric case Instruction::FPToUI: 860f785676fSDimitry Andric case Instruction::FPToSI: 861f785676fSDimitry Andric case Instruction::UIToFP: 862f785676fSDimitry Andric case Instruction::SIToFP: 863f785676fSDimitry Andric case Instruction::FPTrunc: 864f785676fSDimitry Andric case Instruction::FPExt: 865f785676fSDimitry Andric case Instruction::GetElementPtr: { 8667d523365SDimitry Andric for (Value *Operand : I->operands()) { 8677d523365SDimitry Andric if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 868f785676fSDimitry Andric return false; 869f785676fSDimitry Andric } 870f785676fSDimitry Andric return true; 871f785676fSDimitry Andric } 872f785676fSDimitry Andric case Instruction::InsertElement: { 873f785676fSDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 874f785676fSDimitry Andric if (!CI) return false; 875f785676fSDimitry Andric int ElementNumber = CI->getLimitedValue(); 876f785676fSDimitry Andric 877f785676fSDimitry Andric // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 878f785676fSDimitry Andric // can't put an element into multiple indices. 879f785676fSDimitry Andric bool SeenOnce = false; 880f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 881f785676fSDimitry Andric if (Mask[i] == ElementNumber) { 882f785676fSDimitry Andric if (SeenOnce) 883f785676fSDimitry Andric return false; 884f785676fSDimitry Andric SeenOnce = true; 885f785676fSDimitry Andric } 886f785676fSDimitry Andric } 887f785676fSDimitry Andric return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 888f785676fSDimitry Andric } 889f785676fSDimitry Andric } 890f785676fSDimitry Andric return false; 891f785676fSDimitry Andric } 892f785676fSDimitry Andric 893f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given. 894f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct. 8957d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 896f785676fSDimitry Andric // We don't want to use the IRBuilder here because we want the replacement 897f785676fSDimitry Andric // instructions to appear next to 'I', not the builder's insertion point. 898f785676fSDimitry Andric switch (I->getOpcode()) { 899f785676fSDimitry Andric case Instruction::Add: 900f785676fSDimitry Andric case Instruction::FAdd: 901f785676fSDimitry Andric case Instruction::Sub: 902f785676fSDimitry Andric case Instruction::FSub: 903f785676fSDimitry Andric case Instruction::Mul: 904f785676fSDimitry Andric case Instruction::FMul: 905f785676fSDimitry Andric case Instruction::UDiv: 906f785676fSDimitry Andric case Instruction::SDiv: 907f785676fSDimitry Andric case Instruction::FDiv: 908f785676fSDimitry Andric case Instruction::URem: 909f785676fSDimitry Andric case Instruction::SRem: 910f785676fSDimitry Andric case Instruction::FRem: 911f785676fSDimitry Andric case Instruction::Shl: 912f785676fSDimitry Andric case Instruction::LShr: 913f785676fSDimitry Andric case Instruction::AShr: 914f785676fSDimitry Andric case Instruction::And: 915f785676fSDimitry Andric case Instruction::Or: 916f785676fSDimitry Andric case Instruction::Xor: { 917f785676fSDimitry Andric BinaryOperator *BO = cast<BinaryOperator>(I); 918f785676fSDimitry Andric assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 919f785676fSDimitry Andric BinaryOperator *New = 920f785676fSDimitry Andric BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 921f785676fSDimitry Andric NewOps[0], NewOps[1], "", BO); 922f785676fSDimitry Andric if (isa<OverflowingBinaryOperator>(BO)) { 923f785676fSDimitry Andric New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 924f785676fSDimitry Andric New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 925f785676fSDimitry Andric } 926f785676fSDimitry Andric if (isa<PossiblyExactOperator>(BO)) { 927f785676fSDimitry Andric New->setIsExact(BO->isExact()); 928f785676fSDimitry Andric } 92991bc56edSDimitry Andric if (isa<FPMathOperator>(BO)) 93091bc56edSDimitry Andric New->copyFastMathFlags(I); 931f785676fSDimitry Andric return New; 932f785676fSDimitry Andric } 933f785676fSDimitry Andric case Instruction::ICmp: 934f785676fSDimitry Andric assert(NewOps.size() == 2 && "icmp with #ops != 2"); 935f785676fSDimitry Andric return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 936f785676fSDimitry Andric NewOps[0], NewOps[1]); 937f785676fSDimitry Andric case Instruction::FCmp: 938f785676fSDimitry Andric assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 939f785676fSDimitry Andric return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 940f785676fSDimitry Andric NewOps[0], NewOps[1]); 941f785676fSDimitry Andric case Instruction::Trunc: 942f785676fSDimitry Andric case Instruction::ZExt: 943f785676fSDimitry Andric case Instruction::SExt: 944f785676fSDimitry Andric case Instruction::FPToUI: 945f785676fSDimitry Andric case Instruction::FPToSI: 946f785676fSDimitry Andric case Instruction::UIToFP: 947f785676fSDimitry Andric case Instruction::SIToFP: 948f785676fSDimitry Andric case Instruction::FPTrunc: 949f785676fSDimitry Andric case Instruction::FPExt: { 950f785676fSDimitry Andric // It's possible that the mask has a different number of elements from 951f785676fSDimitry Andric // the original cast. We recompute the destination type to match the mask. 952f785676fSDimitry Andric Type *DestTy = 953f785676fSDimitry Andric VectorType::get(I->getType()->getScalarType(), 954f785676fSDimitry Andric NewOps[0]->getType()->getVectorNumElements()); 955f785676fSDimitry Andric assert(NewOps.size() == 1 && "cast with #ops != 1"); 956f785676fSDimitry Andric return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 957f785676fSDimitry Andric "", I); 958f785676fSDimitry Andric } 959f785676fSDimitry Andric case Instruction::GetElementPtr: { 960f785676fSDimitry Andric Value *Ptr = NewOps[0]; 961f785676fSDimitry Andric ArrayRef<Value*> Idx = NewOps.slice(1); 962ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create( 963ff0cc061SDimitry Andric cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 964f785676fSDimitry Andric GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 965f785676fSDimitry Andric return GEP; 966f785676fSDimitry Andric } 967f785676fSDimitry Andric } 968f785676fSDimitry Andric llvm_unreachable("failed to rebuild vector instructions"); 969f785676fSDimitry Andric } 970f785676fSDimitry Andric 971f785676fSDimitry Andric Value * 972f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 973f785676fSDimitry Andric // Mask.size() does not need to be equal to the number of vector elements. 974f785676fSDimitry Andric 975f785676fSDimitry Andric assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 976f785676fSDimitry Andric if (isa<UndefValue>(V)) { 977f785676fSDimitry Andric return UndefValue::get(VectorType::get(V->getType()->getScalarType(), 978f785676fSDimitry Andric Mask.size())); 979f785676fSDimitry Andric } 980f785676fSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 981f785676fSDimitry Andric return ConstantAggregateZero::get( 982f785676fSDimitry Andric VectorType::get(V->getType()->getScalarType(), 983f785676fSDimitry Andric Mask.size())); 984f785676fSDimitry Andric } 985f785676fSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 986f785676fSDimitry Andric SmallVector<Constant *, 16> MaskValues; 987f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 988f785676fSDimitry Andric if (Mask[i] == -1) 989f785676fSDimitry Andric MaskValues.push_back(UndefValue::get(Builder->getInt32Ty())); 990f785676fSDimitry Andric else 991f785676fSDimitry Andric MaskValues.push_back(Builder->getInt32(Mask[i])); 992f785676fSDimitry Andric } 993f785676fSDimitry Andric return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 994f785676fSDimitry Andric ConstantVector::get(MaskValues)); 995f785676fSDimitry Andric } 996f785676fSDimitry Andric 997f785676fSDimitry Andric Instruction *I = cast<Instruction>(V); 998f785676fSDimitry Andric switch (I->getOpcode()) { 999f785676fSDimitry Andric case Instruction::Add: 1000f785676fSDimitry Andric case Instruction::FAdd: 1001f785676fSDimitry Andric case Instruction::Sub: 1002f785676fSDimitry Andric case Instruction::FSub: 1003f785676fSDimitry Andric case Instruction::Mul: 1004f785676fSDimitry Andric case Instruction::FMul: 1005f785676fSDimitry Andric case Instruction::UDiv: 1006f785676fSDimitry Andric case Instruction::SDiv: 1007f785676fSDimitry Andric case Instruction::FDiv: 1008f785676fSDimitry Andric case Instruction::URem: 1009f785676fSDimitry Andric case Instruction::SRem: 1010f785676fSDimitry Andric case Instruction::FRem: 1011f785676fSDimitry Andric case Instruction::Shl: 1012f785676fSDimitry Andric case Instruction::LShr: 1013f785676fSDimitry Andric case Instruction::AShr: 1014f785676fSDimitry Andric case Instruction::And: 1015f785676fSDimitry Andric case Instruction::Or: 1016f785676fSDimitry Andric case Instruction::Xor: 1017f785676fSDimitry Andric case Instruction::ICmp: 1018f785676fSDimitry Andric case Instruction::FCmp: 1019f785676fSDimitry Andric case Instruction::Trunc: 1020f785676fSDimitry Andric case Instruction::ZExt: 1021f785676fSDimitry Andric case Instruction::SExt: 1022f785676fSDimitry Andric case Instruction::FPToUI: 1023f785676fSDimitry Andric case Instruction::FPToSI: 1024f785676fSDimitry Andric case Instruction::UIToFP: 1025f785676fSDimitry Andric case Instruction::SIToFP: 1026f785676fSDimitry Andric case Instruction::FPTrunc: 1027f785676fSDimitry Andric case Instruction::FPExt: 1028f785676fSDimitry Andric case Instruction::Select: 1029f785676fSDimitry Andric case Instruction::GetElementPtr: { 1030f785676fSDimitry Andric SmallVector<Value*, 8> NewOps; 1031f785676fSDimitry Andric bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 1032f785676fSDimitry Andric for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 1033f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 1034f785676fSDimitry Andric NewOps.push_back(V); 1035f785676fSDimitry Andric NeedsRebuild |= (V != I->getOperand(i)); 1036f785676fSDimitry Andric } 1037f785676fSDimitry Andric if (NeedsRebuild) { 10387d523365SDimitry Andric return buildNew(I, NewOps); 1039f785676fSDimitry Andric } 1040f785676fSDimitry Andric return I; 1041f785676fSDimitry Andric } 1042f785676fSDimitry Andric case Instruction::InsertElement: { 1043f785676fSDimitry Andric int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 1044f785676fSDimitry Andric 1045f785676fSDimitry Andric // The insertelement was inserting at Element. Figure out which element 1046f785676fSDimitry Andric // that becomes after shuffling. The answer is guaranteed to be unique 1047f785676fSDimitry Andric // by CanEvaluateShuffled. 1048f785676fSDimitry Andric bool Found = false; 1049f785676fSDimitry Andric int Index = 0; 1050f785676fSDimitry Andric for (int e = Mask.size(); Index != e; ++Index) { 1051f785676fSDimitry Andric if (Mask[Index] == Element) { 1052f785676fSDimitry Andric Found = true; 1053f785676fSDimitry Andric break; 1054f785676fSDimitry Andric } 1055f785676fSDimitry Andric } 1056f785676fSDimitry Andric 105791bc56edSDimitry Andric // If element is not in Mask, no need to handle the operand 1 (element to 105891bc56edSDimitry Andric // be inserted). Just evaluate values in operand 0 according to Mask. 1059f785676fSDimitry Andric if (!Found) 106091bc56edSDimitry Andric return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1061f785676fSDimitry Andric 1062f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1063f785676fSDimitry Andric return InsertElementInst::Create(V, I->getOperand(1), 1064f785676fSDimitry Andric Builder->getInt32(Index), "", I); 1065f785676fSDimitry Andric } 1066f785676fSDimitry Andric } 1067f785676fSDimitry Andric llvm_unreachable("failed to reorder elements of vector instruction!"); 1068f785676fSDimitry Andric } 1069f22ef01cSRoman Divacky 10707d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 107191bc56edSDimitry Andric bool &isLHSID, bool &isRHSID) { 107291bc56edSDimitry Andric isLHSID = isRHSID = true; 107391bc56edSDimitry Andric 107491bc56edSDimitry Andric for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 107591bc56edSDimitry Andric if (Mask[i] < 0) continue; // Ignore undef values. 107691bc56edSDimitry Andric // Is this an identity shuffle of the LHS value? 107791bc56edSDimitry Andric isLHSID &= (Mask[i] == (int)i); 107891bc56edSDimitry Andric 107991bc56edSDimitry Andric // Is this an identity shuffle of the RHS value? 108091bc56edSDimitry Andric isRHSID &= (Mask[i]-e == i); 108191bc56edSDimitry Andric } 108291bc56edSDimitry Andric } 108391bc56edSDimitry Andric 1084ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from 1085ff0cc061SDimitry Andric // LHS, for example: 1086ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1087ff0cc061SDimitry Andric // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1088ff0cc061SDimitry Andric // Shuffles to: |EE|FF|GG|HH| 1089ff0cc061SDimitry Andric // +--+--+--+--+ 1090ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1091ff0cc061SDimitry Andric SmallVector<int, 16> &Mask) { 1092d88c1a5aSDimitry Andric unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements(); 1093ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1094ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 1095ff0cc061SDimitry Andric unsigned EndIdx = Mask.back(); 1096ff0cc061SDimitry Andric if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1097ff0cc061SDimitry Andric return false; 1098ff0cc061SDimitry Andric for (unsigned I = 0; I != MaskElems; ++I) 1099ff0cc061SDimitry Andric if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1100ff0cc061SDimitry Andric return false; 1101ff0cc061SDimitry Andric return true; 1102ff0cc061SDimitry Andric } 1103ff0cc061SDimitry Andric 1104f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 1105f22ef01cSRoman Divacky Value *LHS = SVI.getOperand(0); 1106f22ef01cSRoman Divacky Value *RHS = SVI.getOperand(1); 1107dff0c46cSDimitry Andric SmallVector<int, 16> Mask = SVI.getShuffleMask(); 1108ff0cc061SDimitry Andric Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 1109f22ef01cSRoman Divacky 1110f22ef01cSRoman Divacky bool MadeChange = false; 1111f22ef01cSRoman Divacky 1112f22ef01cSRoman Divacky // Undefined shuffle mask -> undefined value. 1113f22ef01cSRoman Divacky if (isa<UndefValue>(SVI.getOperand(2))) 11143ca95b02SDimitry Andric return replaceInstUsesWith(SVI, UndefValue::get(SVI.getType())); 1115f22ef01cSRoman Divacky 1116d88c1a5aSDimitry Andric unsigned VWidth = SVI.getType()->getVectorNumElements(); 1117f22ef01cSRoman Divacky 1118f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 1119f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 11202754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 11212754fe60SDimitry Andric if (V != &SVI) 11223ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 1123f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 1124f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 1125f22ef01cSRoman Divacky MadeChange = true; 1126f22ef01cSRoman Divacky } 1127f22ef01cSRoman Divacky 1128d88c1a5aSDimitry Andric unsigned LHSWidth = LHS->getType()->getVectorNumElements(); 1129dff0c46cSDimitry Andric 1130f22ef01cSRoman Divacky // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 1131f22ef01cSRoman Divacky // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 1132f22ef01cSRoman Divacky if (LHS == RHS || isa<UndefValue>(LHS)) { 1133f22ef01cSRoman Divacky if (isa<UndefValue>(LHS) && LHS == RHS) { 1134f22ef01cSRoman Divacky // shuffle(undef,undef,mask) -> undef. 1135f785676fSDimitry Andric Value *Result = (VWidth == LHSWidth) 1136dff0c46cSDimitry Andric ? LHS : UndefValue::get(SVI.getType()); 11373ca95b02SDimitry Andric return replaceInstUsesWith(SVI, Result); 1138f22ef01cSRoman Divacky } 1139f22ef01cSRoman Divacky 1140f22ef01cSRoman Divacky // Remap any references to RHS to use LHS. 1141dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1142dff0c46cSDimitry Andric for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 1143dff0c46cSDimitry Andric if (Mask[i] < 0) { 1144ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1145dff0c46cSDimitry Andric continue; 1146dff0c46cSDimitry Andric } 1147dff0c46cSDimitry Andric 11482754fe60SDimitry Andric if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 11492754fe60SDimitry Andric (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 11502754fe60SDimitry Andric Mask[i] = -1; // Turn into undef. 1151ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1152f22ef01cSRoman Divacky } else { 1153f22ef01cSRoman Divacky Mask[i] = Mask[i] % e; // Force to LHS. 1154ff0cc061SDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 1155f22ef01cSRoman Divacky } 1156f22ef01cSRoman Divacky } 1157f22ef01cSRoman Divacky SVI.setOperand(0, SVI.getOperand(1)); 1158f22ef01cSRoman Divacky SVI.setOperand(1, UndefValue::get(RHS->getType())); 1159f22ef01cSRoman Divacky SVI.setOperand(2, ConstantVector::get(Elts)); 1160f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 1161f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 1162f22ef01cSRoman Divacky MadeChange = true; 1163f22ef01cSRoman Divacky } 1164f22ef01cSRoman Divacky 1165dff0c46cSDimitry Andric if (VWidth == LHSWidth) { 1166f22ef01cSRoman Divacky // Analyze the shuffle, are the LHS or RHS and identity shuffles? 116791bc56edSDimitry Andric bool isLHSID, isRHSID; 11687d523365SDimitry Andric recognizeIdentityMask(Mask, isLHSID, isRHSID); 1169f22ef01cSRoman Divacky 1170f22ef01cSRoman Divacky // Eliminate identity shuffles. 11713ca95b02SDimitry Andric if (isLHSID) return replaceInstUsesWith(SVI, LHS); 11723ca95b02SDimitry Andric if (isRHSID) return replaceInstUsesWith(SVI, RHS); 1173dff0c46cSDimitry Andric } 1174f22ef01cSRoman Divacky 1175f785676fSDimitry Andric if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 1176f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 11773ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 1178f785676fSDimitry Andric } 1179f785676fSDimitry Andric 1180ff0cc061SDimitry Andric // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 1181ff0cc061SDimitry Andric // a non-vector type. We can instead bitcast the original vector followed by 1182ff0cc061SDimitry Andric // an extract of the desired element: 1183ff0cc061SDimitry Andric // 1184ff0cc061SDimitry Andric // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1185ff0cc061SDimitry Andric // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1186ff0cc061SDimitry Andric // %1 = bitcast <4 x i8> %sroa to i32 1187ff0cc061SDimitry Andric // Becomes: 1188ff0cc061SDimitry Andric // %bc = bitcast <16 x i8> %in to <4 x i32> 1189ff0cc061SDimitry Andric // %ext = extractelement <4 x i32> %bc, i32 0 1190ff0cc061SDimitry Andric // 1191ff0cc061SDimitry Andric // If the shuffle is extracting a contiguous range of values from the input 1192ff0cc061SDimitry Andric // vector then each use which is a bitcast of the extracted size can be 1193ff0cc061SDimitry Andric // replaced. This will work if the vector types are compatible, and the begin 1194ff0cc061SDimitry Andric // index is aligned to a value in the casted vector type. If the begin index 1195ff0cc061SDimitry Andric // isn't aligned then we can shuffle the original vector (keeping the same 1196ff0cc061SDimitry Andric // vector type) before extracting. 1197ff0cc061SDimitry Andric // 1198ff0cc061SDimitry Andric // This code will bail out if the target type is fundamentally incompatible 1199ff0cc061SDimitry Andric // with vectors of the source type. 1200ff0cc061SDimitry Andric // 1201ff0cc061SDimitry Andric // Example of <16 x i8>, target type i32: 1202ff0cc061SDimitry Andric // Index range [4,8): v-----------v Will work. 1203ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1204ff0cc061SDimitry Andric // <16 x i8>: | | | | | | | | | | | | | | | | | 1205ff0cc061SDimitry Andric // <4 x i32>: | | | | | 1206ff0cc061SDimitry Andric // +-----------+-----------+-----------+-----------+ 1207ff0cc061SDimitry Andric // Index range [6,10): ^-----------^ Needs an extra shuffle. 1208ff0cc061SDimitry Andric // Target type i40: ^--------------^ Won't work, bail. 1209ff0cc061SDimitry Andric if (isShuffleExtractingFromLHS(SVI, Mask)) { 1210ff0cc061SDimitry Andric Value *V = LHS; 1211ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1212ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 1213ff0cc061SDimitry Andric VectorType *SrcTy = cast<VectorType>(V->getType()); 1214ff0cc061SDimitry Andric unsigned VecBitWidth = SrcTy->getBitWidth(); 1215ff0cc061SDimitry Andric unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1216ff0cc061SDimitry Andric assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1217ff0cc061SDimitry Andric unsigned SrcNumElems = SrcTy->getNumElements(); 1218ff0cc061SDimitry Andric SmallVector<BitCastInst *, 8> BCs; 1219ff0cc061SDimitry Andric DenseMap<Type *, Value *> NewBCs; 1220ff0cc061SDimitry Andric for (User *U : SVI.users()) 1221ff0cc061SDimitry Andric if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1222ff0cc061SDimitry Andric if (!BC->use_empty()) 1223ff0cc061SDimitry Andric // Only visit bitcasts that weren't previously handled. 1224ff0cc061SDimitry Andric BCs.push_back(BC); 1225ff0cc061SDimitry Andric for (BitCastInst *BC : BCs) { 1226ff0cc061SDimitry Andric Type *TgtTy = BC->getDestTy(); 1227ff0cc061SDimitry Andric unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1228ff0cc061SDimitry Andric if (!TgtElemBitWidth) 1229ff0cc061SDimitry Andric continue; 1230ff0cc061SDimitry Andric unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1231ff0cc061SDimitry Andric bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1232ff0cc061SDimitry Andric bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1233ff0cc061SDimitry Andric if (!VecBitWidthsEqual) 1234ff0cc061SDimitry Andric continue; 1235ff0cc061SDimitry Andric if (!VectorType::isValidElementType(TgtTy)) 1236ff0cc061SDimitry Andric continue; 1237ff0cc061SDimitry Andric VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1238ff0cc061SDimitry Andric if (!BegIsAligned) { 1239ff0cc061SDimitry Andric // Shuffle the input so [0,NumElements) contains the output, and 1240ff0cc061SDimitry Andric // [NumElems,SrcNumElems) is undef. 1241ff0cc061SDimitry Andric SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1242ff0cc061SDimitry Andric UndefValue::get(Int32Ty)); 1243ff0cc061SDimitry Andric for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1244ff0cc061SDimitry Andric ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1245ff0cc061SDimitry Andric V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()), 1246ff0cc061SDimitry Andric ConstantVector::get(ShuffleMask), 1247ff0cc061SDimitry Andric SVI.getName() + ".extract"); 1248ff0cc061SDimitry Andric BegIdx = 0; 1249ff0cc061SDimitry Andric } 1250ff0cc061SDimitry Andric unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1251ff0cc061SDimitry Andric assert(SrcElemsPerTgtElem); 1252ff0cc061SDimitry Andric BegIdx /= SrcElemsPerTgtElem; 1253ff0cc061SDimitry Andric bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1254ff0cc061SDimitry Andric auto *NewBC = 1255ff0cc061SDimitry Andric BCAlreadyExists 1256ff0cc061SDimitry Andric ? NewBCs[CastSrcTy] 1257ff0cc061SDimitry Andric : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1258ff0cc061SDimitry Andric if (!BCAlreadyExists) 1259ff0cc061SDimitry Andric NewBCs[CastSrcTy] = NewBC; 1260ff0cc061SDimitry Andric auto *Ext = Builder->CreateExtractElement( 1261ff0cc061SDimitry Andric NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1262ff0cc061SDimitry Andric // The shufflevector isn't being replaced: the bitcast that used it 1263ff0cc061SDimitry Andric // is. InstCombine will visit the newly-created instructions. 12643ca95b02SDimitry Andric replaceInstUsesWith(*BC, Ext); 1265ff0cc061SDimitry Andric MadeChange = true; 1266ff0cc061SDimitry Andric } 1267ff0cc061SDimitry Andric } 1268ff0cc061SDimitry Andric 1269f22ef01cSRoman Divacky // If the LHS is a shufflevector itself, see if we can combine it with this 1270dff0c46cSDimitry Andric // one without producing an unusual shuffle. 1271dff0c46cSDimitry Andric // Cases that might be simplified: 1272dff0c46cSDimitry Andric // 1. 1273dff0c46cSDimitry Andric // x1=shuffle(v1,v2,mask1) 1274dff0c46cSDimitry Andric // x=shuffle(x1,undef,mask) 1275dff0c46cSDimitry Andric // ==> 1276dff0c46cSDimitry Andric // x=shuffle(v1,undef,newMask) 1277dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1278dff0c46cSDimitry Andric // 2. 1279dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1280dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1281dff0c46cSDimitry Andric // where v1.size() == mask1.size() 1282dff0c46cSDimitry Andric // ==> 1283dff0c46cSDimitry Andric // x=shuffle(v1,x2,newMask) 1284dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1285dff0c46cSDimitry Andric // 3. 1286dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1287dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1288dff0c46cSDimitry Andric // where v2.size() == mask2.size() 1289dff0c46cSDimitry Andric // ==> 1290dff0c46cSDimitry Andric // x=shuffle(x1,v2,newMask) 1291dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1292dff0c46cSDimitry Andric // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1293dff0c46cSDimitry Andric // 4. 1294dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1295dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1296dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1297dff0c46cSDimitry Andric // where v1.size() == v2.size() 1298dff0c46cSDimitry Andric // ==> 1299dff0c46cSDimitry Andric // x=shuffle(v1,v2,newMask) 1300dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1301dff0c46cSDimitry Andric // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1302dff0c46cSDimitry Andric // 1303dff0c46cSDimitry Andric // Here we are really conservative: 1304f22ef01cSRoman Divacky // we are absolutely afraid of producing a shuffle mask not in the input 1305f22ef01cSRoman Divacky // program, because the code gen may not be smart enough to turn a merged 1306f22ef01cSRoman Divacky // shuffle into two specific shuffles: it may produce worse code. As such, 13072754fe60SDimitry Andric // we only merge two shuffles if the result is either a splat or one of the 1308dff0c46cSDimitry Andric // input shuffle masks. In this case, merging the shuffles just removes 13092754fe60SDimitry Andric // one instruction, which we know is safe. This is good for things like 1310dff0c46cSDimitry Andric // turning: (splat(splat)) -> splat, or 1311dff0c46cSDimitry Andric // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1312dff0c46cSDimitry Andric ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1313dff0c46cSDimitry Andric ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1314dff0c46cSDimitry Andric if (LHSShuffle) 1315dff0c46cSDimitry Andric if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 131691bc56edSDimitry Andric LHSShuffle = nullptr; 1317dff0c46cSDimitry Andric if (RHSShuffle) 1318dff0c46cSDimitry Andric if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 131991bc56edSDimitry Andric RHSShuffle = nullptr; 1320dff0c46cSDimitry Andric if (!LHSShuffle && !RHSShuffle) 132191bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1322dff0c46cSDimitry Andric 132391bc56edSDimitry Andric Value* LHSOp0 = nullptr; 132491bc56edSDimitry Andric Value* LHSOp1 = nullptr; 132591bc56edSDimitry Andric Value* RHSOp0 = nullptr; 1326dff0c46cSDimitry Andric unsigned LHSOp0Width = 0; 1327dff0c46cSDimitry Andric unsigned RHSOp0Width = 0; 1328dff0c46cSDimitry Andric if (LHSShuffle) { 1329dff0c46cSDimitry Andric LHSOp0 = LHSShuffle->getOperand(0); 1330dff0c46cSDimitry Andric LHSOp1 = LHSShuffle->getOperand(1); 1331d88c1a5aSDimitry Andric LHSOp0Width = LHSOp0->getType()->getVectorNumElements(); 1332dff0c46cSDimitry Andric } 1333dff0c46cSDimitry Andric if (RHSShuffle) { 1334dff0c46cSDimitry Andric RHSOp0 = RHSShuffle->getOperand(0); 1335d88c1a5aSDimitry Andric RHSOp0Width = RHSOp0->getType()->getVectorNumElements(); 1336dff0c46cSDimitry Andric } 1337dff0c46cSDimitry Andric Value* newLHS = LHS; 1338dff0c46cSDimitry Andric Value* newRHS = RHS; 1339dff0c46cSDimitry Andric if (LHSShuffle) { 1340dff0c46cSDimitry Andric // case 1 1341f22ef01cSRoman Divacky if (isa<UndefValue>(RHS)) { 1342dff0c46cSDimitry Andric newLHS = LHSOp0; 1343dff0c46cSDimitry Andric newRHS = LHSOp1; 1344dff0c46cSDimitry Andric } 1345dff0c46cSDimitry Andric // case 2 or 4 1346dff0c46cSDimitry Andric else if (LHSOp0Width == LHSWidth) { 1347dff0c46cSDimitry Andric newLHS = LHSOp0; 1348dff0c46cSDimitry Andric } 1349dff0c46cSDimitry Andric } 1350dff0c46cSDimitry Andric // case 3 or 4 1351dff0c46cSDimitry Andric if (RHSShuffle && RHSOp0Width == LHSWidth) { 1352dff0c46cSDimitry Andric newRHS = RHSOp0; 1353dff0c46cSDimitry Andric } 1354dff0c46cSDimitry Andric // case 4 1355dff0c46cSDimitry Andric if (LHSOp0 == RHSOp0) { 1356dff0c46cSDimitry Andric newLHS = LHSOp0; 135791bc56edSDimitry Andric newRHS = nullptr; 1358dff0c46cSDimitry Andric } 1359f22ef01cSRoman Divacky 1360dff0c46cSDimitry Andric if (newLHS == LHS && newRHS == RHS) 136191bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1362dff0c46cSDimitry Andric 1363dff0c46cSDimitry Andric SmallVector<int, 16> LHSMask; 1364dff0c46cSDimitry Andric SmallVector<int, 16> RHSMask; 1365dff0c46cSDimitry Andric if (newLHS != LHS) 1366dff0c46cSDimitry Andric LHSMask = LHSShuffle->getShuffleMask(); 1367dff0c46cSDimitry Andric if (RHSShuffle && newRHS != RHS) 1368dff0c46cSDimitry Andric RHSMask = RHSShuffle->getShuffleMask(); 1369dff0c46cSDimitry Andric 1370dff0c46cSDimitry Andric unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1371dff0c46cSDimitry Andric SmallVector<int, 16> newMask; 13722754fe60SDimitry Andric bool isSplat = true; 1373dff0c46cSDimitry Andric int SplatElt = -1; 1374dff0c46cSDimitry Andric // Create a new mask for the new ShuffleVectorInst so that the new 1375dff0c46cSDimitry Andric // ShuffleVectorInst is equivalent to the original one. 1376dff0c46cSDimitry Andric for (unsigned i = 0; i < VWidth; ++i) { 1377dff0c46cSDimitry Andric int eltMask; 1378139f7f9bSDimitry Andric if (Mask[i] < 0) { 1379dff0c46cSDimitry Andric // This element is an undef value. 1380dff0c46cSDimitry Andric eltMask = -1; 1381dff0c46cSDimitry Andric } else if (Mask[i] < (int)LHSWidth) { 1382dff0c46cSDimitry Andric // This element is from left hand side vector operand. 1383dff0c46cSDimitry Andric // 1384dff0c46cSDimitry Andric // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1385dff0c46cSDimitry Andric // new mask value for the element. 1386dff0c46cSDimitry Andric if (newLHS != LHS) { 1387dff0c46cSDimitry Andric eltMask = LHSMask[Mask[i]]; 1388dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1389dff0c46cSDimitry Andric // with a -1 mask value. 1390dff0c46cSDimitry Andric if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1391dff0c46cSDimitry Andric eltMask = -1; 1392139f7f9bSDimitry Andric } else 1393dff0c46cSDimitry Andric eltMask = Mask[i]; 1394dff0c46cSDimitry Andric } else { 1395dff0c46cSDimitry Andric // This element is from right hand side vector operand 1396dff0c46cSDimitry Andric // 1397dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1398dff0c46cSDimitry Andric // with a -1 mask value. (case 1) 1399dff0c46cSDimitry Andric if (isa<UndefValue>(RHS)) 1400dff0c46cSDimitry Andric eltMask = -1; 1401dff0c46cSDimitry Andric // If RHS is going to be replaced (case 3 or 4), calculate the 1402dff0c46cSDimitry Andric // new mask value for the element. 1403dff0c46cSDimitry Andric else if (newRHS != RHS) { 1404dff0c46cSDimitry Andric eltMask = RHSMask[Mask[i]-LHSWidth]; 1405dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1406dff0c46cSDimitry Andric // with a -1 mask value. 1407dff0c46cSDimitry Andric if (eltMask >= (int)RHSOp0Width) { 1408dff0c46cSDimitry Andric assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1409dff0c46cSDimitry Andric && "should have been check above"); 1410dff0c46cSDimitry Andric eltMask = -1; 1411dff0c46cSDimitry Andric } 1412139f7f9bSDimitry Andric } else 1413dff0c46cSDimitry Andric eltMask = Mask[i]-LHSWidth; 1414dff0c46cSDimitry Andric 1415dff0c46cSDimitry Andric // If LHS's width is changed, shift the mask value accordingly. 1416dff0c46cSDimitry Andric // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any 14173861d79fSDimitry Andric // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 14183861d79fSDimitry Andric // If newRHS == newLHS, we want to remap any references from newRHS to 14193861d79fSDimitry Andric // newLHS so that we can properly identify splats that may occur due to 142091bc56edSDimitry Andric // obfuscation across the two vectors. 142191bc56edSDimitry Andric if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1422dff0c46cSDimitry Andric eltMask += newLHSWidth; 14232754fe60SDimitry Andric } 1424f22ef01cSRoman Divacky 1425dff0c46cSDimitry Andric // Check if this could still be a splat. 1426dff0c46cSDimitry Andric if (eltMask >= 0) { 1427dff0c46cSDimitry Andric if (SplatElt >= 0 && SplatElt != eltMask) 1428dff0c46cSDimitry Andric isSplat = false; 1429dff0c46cSDimitry Andric SplatElt = eltMask; 1430dff0c46cSDimitry Andric } 1431dff0c46cSDimitry Andric 1432dff0c46cSDimitry Andric newMask.push_back(eltMask); 1433dff0c46cSDimitry Andric } 1434dff0c46cSDimitry Andric 1435dff0c46cSDimitry Andric // If the result mask is equal to one of the original shuffle masks, 1436dff0c46cSDimitry Andric // or is a splat, do the replacement. 1437dff0c46cSDimitry Andric if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1438dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1439dff0c46cSDimitry Andric for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1440dff0c46cSDimitry Andric if (newMask[i] < 0) { 14412754fe60SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1442f22ef01cSRoman Divacky } else { 1443dff0c46cSDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1444f22ef01cSRoman Divacky } 1445f22ef01cSRoman Divacky } 144691bc56edSDimitry Andric if (!newRHS) 1447dff0c46cSDimitry Andric newRHS = UndefValue::get(newLHS->getType()); 1448dff0c46cSDimitry Andric return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1449f22ef01cSRoman Divacky } 1450f22ef01cSRoman Divacky 145191bc56edSDimitry Andric // If the result mask is an identity, replace uses of this instruction with 145291bc56edSDimitry Andric // corresponding argument. 145391bc56edSDimitry Andric bool isLHSID, isRHSID; 14547d523365SDimitry Andric recognizeIdentityMask(newMask, isLHSID, isRHSID); 14553ca95b02SDimitry Andric if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 14563ca95b02SDimitry Andric if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 145791bc56edSDimitry Andric 145891bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1459f22ef01cSRoman Divacky } 1460