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) { 147f37b6182SDimitry Andric if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(), 148db17bf38SDimitry Andric EI.getIndexOperand(), 149db17bf38SDimitry Andric SQ.getWithInstruction(&EI))) 1503ca95b02SDimitry Andric return replaceInstUsesWith(EI, V); 151875ed548SDimitry Andric 152f22ef01cSRoman Divacky // If vector val is constant with all elements the same, replace EI with 153dff0c46cSDimitry Andric // that element. We handle a known element # below. 154dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 1557d523365SDimitry Andric if (cheapToScalarize(C, false)) 1563ca95b02SDimitry Andric return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 157f22ef01cSRoman Divacky 158f22ef01cSRoman Divacky // If extracting a specified index from the vector, see if we can recursively 159f22ef01cSRoman Divacky // find a previously computed scalar that was inserted into the vector. 160f22ef01cSRoman Divacky if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 161f22ef01cSRoman Divacky unsigned IndexVal = IdxC->getZExtValue(); 162f22ef01cSRoman Divacky unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 163f22ef01cSRoman Divacky 164875ed548SDimitry Andric // InstSimplify handles cases where the index is invalid. 165875ed548SDimitry Andric assert(IndexVal < VectorWidth); 166f22ef01cSRoman Divacky 167f22ef01cSRoman Divacky // This instruction only demands the single element from the input vector. 168f22ef01cSRoman Divacky // If the input vector has a single use, simplify it based on this use 169f22ef01cSRoman Divacky // property. 170f22ef01cSRoman Divacky if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 171f22ef01cSRoman Divacky APInt UndefElts(VectorWidth, 0); 172f22ef01cSRoman Divacky APInt DemandedMask(VectorWidth, 0); 1732754fe60SDimitry Andric DemandedMask.setBit(IndexVal); 174ff0cc061SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 175ff0cc061SDimitry Andric UndefElts)) { 176f22ef01cSRoman Divacky EI.setOperand(0, V); 177f22ef01cSRoman Divacky return &EI; 178f22ef01cSRoman Divacky } 179f22ef01cSRoman Divacky } 180f22ef01cSRoman Divacky 1817d523365SDimitry Andric // If this extractelement is directly using a bitcast from a vector of 182f22ef01cSRoman Divacky // the same number of elements, see if we can find the source element from 183f22ef01cSRoman Divacky // it. In this case, we will end up needing to bitcast the scalars. 184f22ef01cSRoman Divacky if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 185dff0c46cSDimitry Andric if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 186f22ef01cSRoman Divacky if (VT->getNumElements() == VectorWidth) 187875ed548SDimitry Andric if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 188f22ef01cSRoman Divacky return new BitCastInst(Elt, EI.getType()); 189f22ef01cSRoman Divacky } 190284c1978SDimitry Andric 191284c1978SDimitry Andric // If there's a vector PHI feeding a scalar use through this extractelement 192284c1978SDimitry Andric // instruction, try to scalarize the PHI. 193284c1978SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 194284c1978SDimitry Andric Instruction *scalarPHI = scalarizePHI(EI, PN); 195284c1978SDimitry Andric if (scalarPHI) 196f785676fSDimitry Andric return scalarPHI; 197284c1978SDimitry Andric } 198f22ef01cSRoman Divacky } 199f22ef01cSRoman Divacky 200f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 201f22ef01cSRoman Divacky // Push extractelement into predecessor operation if legal and 2027d523365SDimitry Andric // profitable to do so. 203f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 204f22ef01cSRoman Divacky if (I->hasOneUse() && 2057d523365SDimitry Andric cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 206f22ef01cSRoman Divacky Value *newEI0 = 207c4394386SDimitry Andric Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 208f22ef01cSRoman Divacky EI.getName()+".lhs"); 209f22ef01cSRoman Divacky Value *newEI1 = 210c4394386SDimitry Andric Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 211f22ef01cSRoman Divacky EI.getName()+".rhs"); 2123ca95b02SDimitry Andric return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 2133ca95b02SDimitry Andric newEI0, newEI1, BO); 214f22ef01cSRoman Divacky } 215f22ef01cSRoman Divacky } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 216f22ef01cSRoman Divacky // Extracting the inserted element? 217f22ef01cSRoman Divacky if (IE->getOperand(2) == EI.getOperand(1)) 2183ca95b02SDimitry Andric return replaceInstUsesWith(EI, IE->getOperand(1)); 219f22ef01cSRoman Divacky // If the inserted and extracted elements are constants, they must not 220f22ef01cSRoman Divacky // be the same value, extract from the pre-inserted value instead. 221f22ef01cSRoman Divacky if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 222f22ef01cSRoman Divacky Worklist.AddValue(EI.getOperand(0)); 223f22ef01cSRoman Divacky EI.setOperand(0, IE->getOperand(0)); 224f22ef01cSRoman Divacky return &EI; 225f22ef01cSRoman Divacky } 226f22ef01cSRoman Divacky } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 227f22ef01cSRoman Divacky // If this is extracting an element from a shufflevector, figure out where 228f22ef01cSRoman Divacky // it came from and extract from the appropriate input element instead. 229f22ef01cSRoman Divacky if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 230dff0c46cSDimitry Andric int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 231f22ef01cSRoman Divacky Value *Src; 232f22ef01cSRoman Divacky unsigned LHSWidth = 233dff0c46cSDimitry Andric SVI->getOperand(0)->getType()->getVectorNumElements(); 234f22ef01cSRoman Divacky 2352754fe60SDimitry Andric if (SrcIdx < 0) 2363ca95b02SDimitry Andric return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 2372754fe60SDimitry Andric if (SrcIdx < (int)LHSWidth) 238f22ef01cSRoman Divacky Src = SVI->getOperand(0); 2392754fe60SDimitry Andric else { 240f22ef01cSRoman Divacky SrcIdx -= LHSWidth; 241f22ef01cSRoman Divacky Src = SVI->getOperand(1); 242f22ef01cSRoman Divacky } 2436122f3e6SDimitry Andric Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 244f22ef01cSRoman Divacky return ExtractElementInst::Create(Src, 2452754fe60SDimitry Andric ConstantInt::get(Int32Ty, 246f22ef01cSRoman Divacky SrcIdx, false)); 247f22ef01cSRoman Divacky } 2483b0f4066SDimitry Andric } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 2497d523365SDimitry Andric // Canonicalize extractelement(cast) -> cast(extractelement). 2507d523365SDimitry Andric // Bitcasts can change the number of vector elements, and they cost 2517d523365SDimitry Andric // nothing. 252284c1978SDimitry Andric if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 253c4394386SDimitry Andric Value *EE = Builder.CreateExtractElement(CI->getOperand(0), 2543b0f4066SDimitry Andric EI.getIndexOperand()); 255284c1978SDimitry Andric Worklist.AddValue(EE); 2563b0f4066SDimitry Andric return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 257f22ef01cSRoman Divacky } 258f785676fSDimitry Andric } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 259f785676fSDimitry Andric if (SI->hasOneUse()) { 260f785676fSDimitry Andric // TODO: For a select on vectors, it might be useful to do this if it 261f785676fSDimitry Andric // has multiple extractelement uses. For vector select, that seems to 262f785676fSDimitry Andric // fight the vectorizer. 263f785676fSDimitry Andric 264f785676fSDimitry Andric // If we are extracting an element from a vector select or a select on 2657d523365SDimitry Andric // vectors, create a select on the scalars extracted from the vector 2667d523365SDimitry Andric // arguments. 267f785676fSDimitry Andric Value *TrueVal = SI->getTrueValue(); 268f785676fSDimitry Andric Value *FalseVal = SI->getFalseValue(); 269f785676fSDimitry Andric 270f785676fSDimitry Andric Value *Cond = SI->getCondition(); 271f785676fSDimitry Andric if (Cond->getType()->isVectorTy()) { 272c4394386SDimitry Andric Cond = Builder.CreateExtractElement(Cond, 273f785676fSDimitry Andric EI.getIndexOperand(), 274f785676fSDimitry Andric Cond->getName() + ".elt"); 275f785676fSDimitry Andric } 276f785676fSDimitry Andric 277f785676fSDimitry Andric Value *V1Elem 278c4394386SDimitry Andric = Builder.CreateExtractElement(TrueVal, 279f785676fSDimitry Andric EI.getIndexOperand(), 280f785676fSDimitry Andric TrueVal->getName() + ".elt"); 281f785676fSDimitry Andric 282f785676fSDimitry Andric Value *V2Elem 283c4394386SDimitry Andric = Builder.CreateExtractElement(FalseVal, 284f785676fSDimitry Andric EI.getIndexOperand(), 285f785676fSDimitry Andric FalseVal->getName() + ".elt"); 286f785676fSDimitry Andric return SelectInst::Create(Cond, 287f785676fSDimitry Andric V1Elem, 288f785676fSDimitry Andric V2Elem, 289f785676fSDimitry Andric SI->getName() + ".elt"); 290f785676fSDimitry Andric } 2913b0f4066SDimitry Andric } 292f22ef01cSRoman Divacky } 29391bc56edSDimitry Andric return nullptr; 294f22ef01cSRoman Divacky } 295f22ef01cSRoman Divacky 2967d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or 2977d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false. 2987d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 299dff0c46cSDimitry Andric SmallVectorImpl<Constant*> &Mask) { 30091bc56edSDimitry Andric assert(LHS->getType() == RHS->getType() && 301f22ef01cSRoman Divacky "Invalid CollectSingleShuffleElements"); 302f785676fSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 303f22ef01cSRoman Divacky 304f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 305f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 306f22ef01cSRoman Divacky return true; 307f22ef01cSRoman Divacky } 308f22ef01cSRoman Divacky 309f22ef01cSRoman Divacky if (V == LHS) { 310f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 311f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 312f22ef01cSRoman Divacky return true; 313f22ef01cSRoman Divacky } 314f22ef01cSRoman Divacky 315f22ef01cSRoman Divacky if (V == RHS) { 316f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 317f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 318f22ef01cSRoman Divacky i+NumElts)); 319f22ef01cSRoman Divacky return true; 320f22ef01cSRoman Divacky } 321f22ef01cSRoman Divacky 322f22ef01cSRoman Divacky if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 323f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 324f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 325f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 326f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 327f22ef01cSRoman Divacky 328f22ef01cSRoman Divacky if (!isa<ConstantInt>(IdxOp)) 329f22ef01cSRoman Divacky return false; 330f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 331f22ef01cSRoman Divacky 332f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 33391bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 334f22ef01cSRoman Divacky // transitively ok. 3357d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 336f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted undef. 337f22ef01cSRoman Divacky Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 338f22ef01cSRoman Divacky return true; 339f22ef01cSRoman Divacky } 340f22ef01cSRoman Divacky } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 34191bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1))) { 342f22ef01cSRoman Divacky unsigned ExtractedIdx = 343f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 34491bc56edSDimitry Andric unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 345f22ef01cSRoman Divacky 346f22ef01cSRoman Divacky // This must be extracting from either LHS or RHS. 347f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 34891bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 349f22ef01cSRoman Divacky // transitively ok. 3507d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 351f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted value. 352f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS) { 353f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 354f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 355f22ef01cSRoman Divacky ExtractedIdx); 356f22ef01cSRoman Divacky } else { 357f22ef01cSRoman Divacky assert(EI->getOperand(0) == RHS); 358f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 359f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 36091bc56edSDimitry Andric ExtractedIdx + NumLHSElts); 361f22ef01cSRoman Divacky } 362f22ef01cSRoman Divacky return true; 363f22ef01cSRoman Divacky } 364f22ef01cSRoman Divacky } 365f22ef01cSRoman Divacky } 366f22ef01cSRoman Divacky } 367f22ef01cSRoman Divacky } 368f22ef01cSRoman Divacky 369f22ef01cSRoman Divacky return false; 370f22ef01cSRoman Divacky } 371f22ef01cSRoman Divacky 3727d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we 3737d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single 3747d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs. 3757d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt, 3767d523365SDimitry Andric ExtractElementInst *ExtElt, 3777d523365SDimitry Andric InstCombiner &IC) { 3787d523365SDimitry Andric VectorType *InsVecType = InsElt->getType(); 3797d523365SDimitry Andric VectorType *ExtVecType = ExtElt->getVectorOperandType(); 3807d523365SDimitry Andric unsigned NumInsElts = InsVecType->getVectorNumElements(); 3817d523365SDimitry Andric unsigned NumExtElts = ExtVecType->getVectorNumElements(); 3827d523365SDimitry Andric 3837d523365SDimitry Andric // The inserted-to vector must be wider than the extracted-from vector. 3847d523365SDimitry Andric if (InsVecType->getElementType() != ExtVecType->getElementType() || 3857d523365SDimitry Andric NumExtElts >= NumInsElts) 3867d523365SDimitry Andric return; 3877d523365SDimitry Andric 3887d523365SDimitry Andric // Create a shuffle mask to widen the extended-from vector using undefined 3897d523365SDimitry Andric // values. The mask selects all of the values of the original vector followed 3907d523365SDimitry Andric // by as many undefined values as needed to create a vector of the same length 3917d523365SDimitry Andric // as the inserted-to vector. 3927d523365SDimitry Andric SmallVector<Constant *, 16> ExtendMask; 3937d523365SDimitry Andric IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 3947d523365SDimitry Andric for (unsigned i = 0; i < NumExtElts; ++i) 3957d523365SDimitry Andric ExtendMask.push_back(ConstantInt::get(IntType, i)); 3967d523365SDimitry Andric for (unsigned i = NumExtElts; i < NumInsElts; ++i) 3977d523365SDimitry Andric ExtendMask.push_back(UndefValue::get(IntType)); 3987d523365SDimitry Andric 3997d523365SDimitry Andric Value *ExtVecOp = ExtElt->getVectorOperand(); 400a8bcc4d8SDimitry Andric auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 401a8bcc4d8SDimitry Andric BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 402a8bcc4d8SDimitry Andric ? ExtVecOpInst->getParent() 403a8bcc4d8SDimitry Andric : ExtElt->getParent(); 404a8bcc4d8SDimitry Andric 405a8bcc4d8SDimitry Andric // TODO: This restriction matches the basic block check below when creating 406a8bcc4d8SDimitry Andric // new extractelement instructions. If that limitation is removed, this one 407a8bcc4d8SDimitry Andric // could also be removed. But for now, we just bail out to ensure that we 408a8bcc4d8SDimitry Andric // will replace the extractelement instruction that is feeding our 409a8bcc4d8SDimitry Andric // insertelement instruction. This allows the insertelement to then be 410a8bcc4d8SDimitry Andric // replaced by a shufflevector. If the insertelement is not replaced, we can 411a8bcc4d8SDimitry Andric // induce infinite looping because there's an optimization for extractelement 412a8bcc4d8SDimitry Andric // that will delete our widening shuffle. This would trigger another attempt 413a8bcc4d8SDimitry Andric // here to create that shuffle, and we spin forever. 414a8bcc4d8SDimitry Andric if (InsertionBlock != InsElt->getParent()) 415a8bcc4d8SDimitry Andric return; 416a8bcc4d8SDimitry Andric 417d88c1a5aSDimitry Andric // TODO: This restriction matches the check in visitInsertElementInst() and 418d88c1a5aSDimitry Andric // prevents an infinite loop caused by not turning the extract/insert pair 419d88c1a5aSDimitry Andric // into a shuffle. We really should not need either check, but we're lacking 420d88c1a5aSDimitry Andric // folds for shufflevectors because we're afraid to generate shuffle masks 421d88c1a5aSDimitry Andric // that the backend can't handle. 422d88c1a5aSDimitry Andric if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 423d88c1a5aSDimitry Andric return; 424d88c1a5aSDimitry Andric 4257d523365SDimitry Andric auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 4267d523365SDimitry Andric ConstantVector::get(ExtendMask)); 4277d523365SDimitry Andric 4284d0b32cdSDimitry Andric // Insert the new shuffle after the vector operand of the extract is defined 429444ed5c5SDimitry Andric // (as long as it's not a PHI) or at the start of the basic block of the 430444ed5c5SDimitry Andric // extract, so any subsequent extracts in the same basic block can use it. 431444ed5c5SDimitry Andric // TODO: Insert before the earliest ExtractElementInst that is replaced. 432444ed5c5SDimitry Andric if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 4334d0b32cdSDimitry Andric WideVec->insertAfter(ExtVecOpInst); 434444ed5c5SDimitry Andric else 4354d0b32cdSDimitry Andric IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 4364d0b32cdSDimitry Andric 4374d0b32cdSDimitry Andric // Replace extracts from the original narrow vector with extracts from the new 4384d0b32cdSDimitry Andric // wide vector. 4397d523365SDimitry Andric for (User *U : ExtVecOp->users()) { 4404d0b32cdSDimitry Andric ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 441444ed5c5SDimitry Andric if (!OldExt || OldExt->getParent() != WideVec->getParent()) 4424d0b32cdSDimitry Andric continue; 4437d523365SDimitry Andric auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 444db17bf38SDimitry Andric NewExt->insertAfter(OldExt); 4453ca95b02SDimitry Andric IC.replaceInstUsesWith(*OldExt, NewExt); 4467d523365SDimitry Andric } 4477d523365SDimitry Andric } 44891bc56edSDimitry Andric 44991bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement, 45091bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or 45191bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the 45291bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask 45391bc56edSDimitry Andric /// parameter as required. 45491bc56edSDimitry Andric /// 45591bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have 45691bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target. 45791bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps; 45891bc56edSDimitry Andric 4597d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V, 46091bc56edSDimitry Andric SmallVectorImpl<Constant *> &Mask, 4617d523365SDimitry Andric Value *PermittedRHS, 4627d523365SDimitry Andric InstCombiner &IC) { 46391bc56edSDimitry Andric assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 464d88c1a5aSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 465f22ef01cSRoman Divacky 466f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 467f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 46891bc56edSDimitry Andric return std::make_pair( 46991bc56edSDimitry Andric PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 470dff0c46cSDimitry Andric } 471dff0c46cSDimitry Andric 472dff0c46cSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 473f22ef01cSRoman Divacky Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 47491bc56edSDimitry Andric return std::make_pair(V, nullptr); 475dff0c46cSDimitry Andric } 476dff0c46cSDimitry Andric 477dff0c46cSDimitry Andric if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 478f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 479f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 480f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 481f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 482f22ef01cSRoman Divacky 483f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 48491bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 485f22ef01cSRoman Divacky unsigned ExtractedIdx = 486f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 487f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 488f22ef01cSRoman Divacky 489f22ef01cSRoman Divacky // Either the extracted from or inserted into vector must be RHSVec, 490f22ef01cSRoman Divacky // otherwise we'd end up with a shuffle of three inputs. 49191bc56edSDimitry Andric if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 49291bc56edSDimitry Andric Value *RHS = EI->getOperand(0); 4937d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 49491bc56edSDimitry Andric assert(LR.second == nullptr || LR.second == RHS); 49591bc56edSDimitry Andric 49691bc56edSDimitry Andric if (LR.first->getType() != RHS->getType()) { 4977d523365SDimitry Andric // Although we are giving up for now, see if we can create extracts 4987d523365SDimitry Andric // that match the inserts for another round of combining. 4997d523365SDimitry Andric replaceExtractElements(IEI, EI, IC); 5007d523365SDimitry Andric 50191bc56edSDimitry Andric // We tried our best, but we can't find anything compatible with RHS 50291bc56edSDimitry Andric // further up the chain. Return a trivial shuffle. 50391bc56edSDimitry Andric for (unsigned i = 0; i < NumElts; ++i) 50491bc56edSDimitry Andric Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 50591bc56edSDimitry Andric return std::make_pair(V, nullptr); 50691bc56edSDimitry Andric } 50791bc56edSDimitry Andric 50891bc56edSDimitry Andric unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 509f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 510f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 51191bc56edSDimitry Andric NumLHSElts+ExtractedIdx); 51291bc56edSDimitry Andric return std::make_pair(LR.first, RHS); 513f22ef01cSRoman Divacky } 514f22ef01cSRoman Divacky 51591bc56edSDimitry Andric if (VecOp == PermittedRHS) { 51691bc56edSDimitry Andric // We've gone as far as we can: anything on the other side of the 51791bc56edSDimitry Andric // extractelement will already have been converted into a shuffle. 51891bc56edSDimitry Andric unsigned NumLHSElts = 51991bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 52091bc56edSDimitry Andric for (unsigned i = 0; i != NumElts; ++i) 52191bc56edSDimitry Andric Mask.push_back(ConstantInt::get( 52291bc56edSDimitry Andric Type::getInt32Ty(V->getContext()), 52391bc56edSDimitry Andric i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 52491bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 525f22ef01cSRoman Divacky } 526f22ef01cSRoman Divacky 527f22ef01cSRoman Divacky // If this insertelement is a chain that comes from exactly these two 528f22ef01cSRoman Divacky // vectors, return the vector and the effective shuffle. 52991bc56edSDimitry Andric if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 5307d523365SDimitry Andric collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 53191bc56edSDimitry Andric Mask)) 53291bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 533f22ef01cSRoman Divacky } 534f22ef01cSRoman Divacky } 535f22ef01cSRoman Divacky } 536f22ef01cSRoman Divacky 5377d523365SDimitry Andric // Otherwise, we can't do anything fancy. Return an identity vector. 538f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 539f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 54091bc56edSDimitry Andric return std::make_pair(V, nullptr); 54191bc56edSDimitry Andric } 54291bc56edSDimitry Andric 54391bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones: 54491bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 54591bc56edSDimitry Andric /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 54691bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the 54791bc56edSDimitry Andric /// first one, making the first one redundant. 54891bc56edSDimitry Andric /// It should be transformed to: 54991bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 55091bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 55191bc56edSDimitry Andric bool IsRedundant = false; 55291bc56edSDimitry Andric ArrayRef<unsigned int> FirstIndices = I.getIndices(); 55391bc56edSDimitry Andric 55491bc56edSDimitry Andric // If there is a chain of insertvalue instructions (each of them except the 55591bc56edSDimitry Andric // last one has only one use and it's another insertvalue insn from this 55691bc56edSDimitry Andric // chain), check if any of the 'children' uses the same indices as the first 55791bc56edSDimitry Andric // instruction. In this case, the first one is redundant. 55891bc56edSDimitry Andric Value *V = &I; 55991bc56edSDimitry Andric unsigned Depth = 0; 56091bc56edSDimitry Andric while (V->hasOneUse() && Depth < 10) { 56191bc56edSDimitry Andric User *U = V->user_back(); 56291bc56edSDimitry Andric auto UserInsInst = dyn_cast<InsertValueInst>(U); 56391bc56edSDimitry Andric if (!UserInsInst || U->getOperand(0) != V) 56491bc56edSDimitry Andric break; 56591bc56edSDimitry Andric if (UserInsInst->getIndices() == FirstIndices) { 56691bc56edSDimitry Andric IsRedundant = true; 56791bc56edSDimitry Andric break; 56891bc56edSDimitry Andric } 56991bc56edSDimitry Andric V = UserInsInst; 57091bc56edSDimitry Andric Depth++; 57191bc56edSDimitry Andric } 57291bc56edSDimitry Andric 57391bc56edSDimitry Andric if (IsRedundant) 5743ca95b02SDimitry Andric return replaceInstUsesWith(I, I.getOperand(0)); 57591bc56edSDimitry Andric return nullptr; 576f22ef01cSRoman Divacky } 577f22ef01cSRoman Divacky 578d88c1a5aSDimitry Andric static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 579d88c1a5aSDimitry Andric int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); 580d88c1a5aSDimitry Andric int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); 581d88c1a5aSDimitry Andric 582d88c1a5aSDimitry Andric // A vector select does not change the size of the operands. 583d88c1a5aSDimitry Andric if (MaskSize != VecSize) 584d88c1a5aSDimitry Andric return false; 585d88c1a5aSDimitry Andric 586d88c1a5aSDimitry Andric // Each mask element must be undefined or choose a vector element from one of 587d88c1a5aSDimitry Andric // the source operands without crossing vector lanes. 588d88c1a5aSDimitry Andric for (int i = 0; i != MaskSize; ++i) { 589d88c1a5aSDimitry Andric int Elt = Shuf.getMaskValue(i); 590d88c1a5aSDimitry Andric if (Elt != -1 && Elt != i && Elt != i + VecSize) 591d88c1a5aSDimitry Andric return false; 592d88c1a5aSDimitry Andric } 593d88c1a5aSDimitry Andric 594d88c1a5aSDimitry Andric return true; 595d88c1a5aSDimitry Andric } 596d88c1a5aSDimitry Andric 597d88c1a5aSDimitry Andric // Turn a chain of inserts that splats a value into a canonical insert + shuffle 598d88c1a5aSDimitry Andric // splat. That is: 599d88c1a5aSDimitry Andric // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> 600d88c1a5aSDimitry Andric // shufflevector(insertelt(X, %k, 0), undef, zero) 601d88c1a5aSDimitry Andric static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) { 602d88c1a5aSDimitry Andric // We are interested in the last insert in a chain. So, if this insert 603d88c1a5aSDimitry Andric // has a single user, and that user is an insert, bail. 604d88c1a5aSDimitry Andric if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) 605d88c1a5aSDimitry Andric return nullptr; 606d88c1a5aSDimitry Andric 607d88c1a5aSDimitry Andric VectorType *VT = cast<VectorType>(InsElt.getType()); 608d88c1a5aSDimitry Andric int NumElements = VT->getNumElements(); 609d88c1a5aSDimitry Andric 610d88c1a5aSDimitry Andric // Do not try to do this for a one-element vector, since that's a nop, 611d88c1a5aSDimitry Andric // and will cause an inf-loop. 612d88c1a5aSDimitry Andric if (NumElements == 1) 613d88c1a5aSDimitry Andric return nullptr; 614d88c1a5aSDimitry Andric 615d88c1a5aSDimitry Andric Value *SplatVal = InsElt.getOperand(1); 616d88c1a5aSDimitry Andric InsertElementInst *CurrIE = &InsElt; 617d88c1a5aSDimitry Andric SmallVector<bool, 16> ElementPresent(NumElements, false); 618d88c1a5aSDimitry Andric 619d88c1a5aSDimitry Andric // Walk the chain backwards, keeping track of which indices we inserted into, 620d88c1a5aSDimitry Andric // until we hit something that isn't an insert of the splatted value. 621d88c1a5aSDimitry Andric while (CurrIE) { 622d88c1a5aSDimitry Andric ConstantInt *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); 623d88c1a5aSDimitry Andric if (!Idx || CurrIE->getOperand(1) != SplatVal) 624d88c1a5aSDimitry Andric return nullptr; 625d88c1a5aSDimitry Andric 626d88c1a5aSDimitry Andric // Check none of the intermediate steps have any additional uses. 627d88c1a5aSDimitry Andric if ((CurrIE != &InsElt) && !CurrIE->hasOneUse()) 628d88c1a5aSDimitry Andric return nullptr; 629d88c1a5aSDimitry Andric 630d88c1a5aSDimitry Andric ElementPresent[Idx->getZExtValue()] = true; 631d88c1a5aSDimitry Andric CurrIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); 632d88c1a5aSDimitry Andric } 633d88c1a5aSDimitry Andric 634d88c1a5aSDimitry Andric // Make sure we've seen an insert into every element. 635d88c1a5aSDimitry Andric if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; })) 636d88c1a5aSDimitry Andric return nullptr; 637d88c1a5aSDimitry Andric 638d88c1a5aSDimitry Andric // All right, create the insert + shuffle. 639d88c1a5aSDimitry Andric Instruction *InsertFirst = InsertElementInst::Create( 640d88c1a5aSDimitry Andric UndefValue::get(VT), SplatVal, 641d88c1a5aSDimitry Andric ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), "", &InsElt); 642d88c1a5aSDimitry Andric 643d88c1a5aSDimitry Andric Constant *ZeroMask = ConstantAggregateZero::get( 644d88c1a5aSDimitry Andric VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements)); 645d88c1a5aSDimitry Andric 646d88c1a5aSDimitry Andric return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask); 647d88c1a5aSDimitry Andric } 648d88c1a5aSDimitry Andric 6497a7e6055SDimitry Andric /// If we have an insertelement instruction feeding into another insertelement 6507a7e6055SDimitry Andric /// and the 2nd is inserting a constant into the vector, canonicalize that 6517a7e6055SDimitry Andric /// constant insertion before the insertion of a variable: 6527a7e6055SDimitry Andric /// 6537a7e6055SDimitry Andric /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> 6547a7e6055SDimitry Andric /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 6557a7e6055SDimitry Andric /// 6567a7e6055SDimitry Andric /// This has the potential of eliminating the 2nd insertelement instruction 6577a7e6055SDimitry Andric /// via constant folding of the scalar constant into a vector constant. 6587a7e6055SDimitry Andric static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, 6597a7e6055SDimitry Andric InstCombiner::BuilderTy &Builder) { 6607a7e6055SDimitry Andric auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); 6617a7e6055SDimitry Andric if (!InsElt1 || !InsElt1->hasOneUse()) 6627a7e6055SDimitry Andric return nullptr; 6637a7e6055SDimitry Andric 6647a7e6055SDimitry Andric Value *X, *Y; 6657a7e6055SDimitry Andric Constant *ScalarC; 6667a7e6055SDimitry Andric ConstantInt *IdxC1, *IdxC2; 6677a7e6055SDimitry Andric if (match(InsElt1->getOperand(0), m_Value(X)) && 6687a7e6055SDimitry Andric match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && 6697a7e6055SDimitry Andric match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && 6707a7e6055SDimitry Andric match(InsElt2.getOperand(1), m_Constant(ScalarC)) && 6717a7e6055SDimitry Andric match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { 6727a7e6055SDimitry Andric Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); 6737a7e6055SDimitry Andric return InsertElementInst::Create(NewInsElt1, Y, IdxC1); 6747a7e6055SDimitry Andric } 6757a7e6055SDimitry Andric 6767a7e6055SDimitry Andric return nullptr; 6777a7e6055SDimitry Andric } 6787a7e6055SDimitry Andric 679d88c1a5aSDimitry Andric /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 680d88c1a5aSDimitry Andric /// --> shufflevector X, CVec', Mask' 681d88c1a5aSDimitry Andric static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 682d88c1a5aSDimitry Andric auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 683d88c1a5aSDimitry Andric // Bail out if the parent has more than one use. In that case, we'd be 684d88c1a5aSDimitry Andric // replacing the insertelt with a shuffle, and that's not a clear win. 685d88c1a5aSDimitry Andric if (!Inst || !Inst->hasOneUse()) 686d88c1a5aSDimitry Andric return nullptr; 687d88c1a5aSDimitry Andric if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 688d88c1a5aSDimitry Andric // The shuffle must have a constant vector operand. The insertelt must have 689d88c1a5aSDimitry Andric // a constant scalar being inserted at a constant position in the vector. 690d88c1a5aSDimitry Andric Constant *ShufConstVec, *InsEltScalar; 691d88c1a5aSDimitry Andric uint64_t InsEltIndex; 692d88c1a5aSDimitry Andric if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 693d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 694d88c1a5aSDimitry Andric !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 695d88c1a5aSDimitry Andric return nullptr; 696d88c1a5aSDimitry Andric 697d88c1a5aSDimitry Andric // Adding an element to an arbitrary shuffle could be expensive, but a 698d88c1a5aSDimitry Andric // shuffle that selects elements from vectors without crossing lanes is 699d88c1a5aSDimitry Andric // assumed cheap. 700d88c1a5aSDimitry Andric // If we're just adding a constant into that shuffle, it will still be 701d88c1a5aSDimitry Andric // cheap. 702d88c1a5aSDimitry Andric if (!isShuffleEquivalentToSelect(*Shuf)) 703d88c1a5aSDimitry Andric return nullptr; 704d88c1a5aSDimitry Andric 705d88c1a5aSDimitry Andric // From the above 'select' check, we know that the mask has the same number 706d88c1a5aSDimitry Andric // of elements as the vector input operands. We also know that each constant 707d88c1a5aSDimitry Andric // input element is used in its lane and can not be used more than once by 708d88c1a5aSDimitry Andric // the shuffle. Therefore, replace the constant in the shuffle's constant 709d88c1a5aSDimitry Andric // vector with the insertelt constant. Replace the constant in the shuffle's 710d88c1a5aSDimitry Andric // mask vector with the insertelt index plus the length of the vector 711d88c1a5aSDimitry Andric // (because the constant vector operand of a shuffle is always the 2nd 712d88c1a5aSDimitry Andric // operand). 713d88c1a5aSDimitry Andric Constant *Mask = Shuf->getMask(); 714d88c1a5aSDimitry Andric unsigned NumElts = Mask->getType()->getVectorNumElements(); 715d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewShufElts(NumElts); 716d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewMaskElts(NumElts); 717d88c1a5aSDimitry Andric for (unsigned I = 0; I != NumElts; ++I) { 718d88c1a5aSDimitry Andric if (I == InsEltIndex) { 719d88c1a5aSDimitry Andric NewShufElts[I] = InsEltScalar; 720d88c1a5aSDimitry Andric Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); 721d88c1a5aSDimitry Andric NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); 722d88c1a5aSDimitry Andric } else { 723d88c1a5aSDimitry Andric // Copy over the existing values. 724d88c1a5aSDimitry Andric NewShufElts[I] = ShufConstVec->getAggregateElement(I); 725d88c1a5aSDimitry Andric NewMaskElts[I] = Mask->getAggregateElement(I); 726d88c1a5aSDimitry Andric } 727d88c1a5aSDimitry Andric } 728d88c1a5aSDimitry Andric 729d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 730d88c1a5aSDimitry Andric // original insertelt. The old shuffle will be dead now. 731d88c1a5aSDimitry Andric return new ShuffleVectorInst(Shuf->getOperand(0), 732d88c1a5aSDimitry Andric ConstantVector::get(NewShufElts), 733d88c1a5aSDimitry Andric ConstantVector::get(NewMaskElts)); 734d88c1a5aSDimitry Andric } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 735d88c1a5aSDimitry Andric // Transform sequences of insertelements ops with constant data/indexes into 736d88c1a5aSDimitry Andric // a single shuffle op. 737d88c1a5aSDimitry Andric unsigned NumElts = InsElt.getType()->getNumElements(); 738d88c1a5aSDimitry Andric 739d88c1a5aSDimitry Andric uint64_t InsertIdx[2]; 740d88c1a5aSDimitry Andric Constant *Val[2]; 741d88c1a5aSDimitry Andric if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 742d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(Val[0])) || 743d88c1a5aSDimitry Andric !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 744d88c1a5aSDimitry Andric !match(IEI->getOperand(1), m_Constant(Val[1]))) 745d88c1a5aSDimitry Andric return nullptr; 746d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Values(NumElts); 747d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Mask(NumElts); 748d88c1a5aSDimitry Andric auto ValI = std::begin(Val); 749d88c1a5aSDimitry Andric // Generate new constant vector and mask. 750d88c1a5aSDimitry Andric // We have 2 values/masks from the insertelements instructions. Insert them 751d88c1a5aSDimitry Andric // into new value/mask vectors. 752d88c1a5aSDimitry Andric for (uint64_t I : InsertIdx) { 753d88c1a5aSDimitry Andric if (!Values[I]) { 754d88c1a5aSDimitry Andric assert(!Mask[I]); 755d88c1a5aSDimitry Andric Values[I] = *ValI; 756d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 757d88c1a5aSDimitry Andric NumElts + I); 758d88c1a5aSDimitry Andric } 759d88c1a5aSDimitry Andric ++ValI; 760d88c1a5aSDimitry Andric } 761d88c1a5aSDimitry Andric // Remaining values are filled with 'undef' values. 762d88c1a5aSDimitry Andric for (unsigned I = 0; I < NumElts; ++I) { 763d88c1a5aSDimitry Andric if (!Values[I]) { 764d88c1a5aSDimitry Andric assert(!Mask[I]); 765d88c1a5aSDimitry Andric Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 766d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); 767d88c1a5aSDimitry Andric } 768d88c1a5aSDimitry Andric } 769d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 770d88c1a5aSDimitry Andric // original insertelt. 771d88c1a5aSDimitry Andric return new ShuffleVectorInst(IEI->getOperand(0), 772d88c1a5aSDimitry Andric ConstantVector::get(Values), 773d88c1a5aSDimitry Andric ConstantVector::get(Mask)); 774d88c1a5aSDimitry Andric } 775d88c1a5aSDimitry Andric return nullptr; 776d88c1a5aSDimitry Andric } 777d88c1a5aSDimitry Andric 778f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 779f22ef01cSRoman Divacky Value *VecOp = IE.getOperand(0); 780f22ef01cSRoman Divacky Value *ScalarOp = IE.getOperand(1); 781f22ef01cSRoman Divacky Value *IdxOp = IE.getOperand(2); 782f22ef01cSRoman Divacky 783f22ef01cSRoman Divacky // Inserting an undef or into an undefined place, remove this. 784f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 7853ca95b02SDimitry Andric replaceInstUsesWith(IE, VecOp); 786f22ef01cSRoman Divacky 787f22ef01cSRoman Divacky // If the inserted element was extracted from some other vector, and if the 788f22ef01cSRoman Divacky // indexes are constant, try to turn this into a shufflevector operation. 789f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 79091bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 79191bc56edSDimitry Andric unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 79291bc56edSDimitry Andric unsigned NumExtractVectorElts = 79391bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 794f22ef01cSRoman Divacky unsigned ExtractedIdx = 795f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 796f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 797f22ef01cSRoman Divacky 79891bc56edSDimitry Andric if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 7993ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 800f22ef01cSRoman Divacky 80191bc56edSDimitry Andric if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 8023ca95b02SDimitry Andric return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 803f22ef01cSRoman Divacky 804f22ef01cSRoman Divacky // If we are extracting a value from a vector, then inserting it right 805f22ef01cSRoman Divacky // back into the same place, just use the input vector. 806f22ef01cSRoman Divacky if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 8073ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 808f22ef01cSRoman Divacky 809f22ef01cSRoman Divacky // If this insertelement isn't used by some other insertelement, turn it 810f22ef01cSRoman Divacky // (and any insertelements it points to), into one big shuffle. 81191bc56edSDimitry Andric if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 812dff0c46cSDimitry Andric SmallVector<Constant*, 16> Mask; 8137d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 81491bc56edSDimitry Andric 81591bc56edSDimitry Andric // The proposed shuffle may be trivial, in which case we shouldn't 81691bc56edSDimitry Andric // perform the combine. 81791bc56edSDimitry Andric if (LR.first != &IE && LR.second != &IE) { 818f22ef01cSRoman Divacky // We now have a shuffle of LHS, RHS, Mask. 81991bc56edSDimitry Andric if (LR.second == nullptr) 82091bc56edSDimitry Andric LR.second = UndefValue::get(LR.first->getType()); 82191bc56edSDimitry Andric return new ShuffleVectorInst(LR.first, LR.second, 82291bc56edSDimitry Andric ConstantVector::get(Mask)); 82391bc56edSDimitry Andric } 824f22ef01cSRoman Divacky } 825f22ef01cSRoman Divacky } 826f22ef01cSRoman Divacky } 827f22ef01cSRoman Divacky 828d88c1a5aSDimitry Andric unsigned VWidth = VecOp->getType()->getVectorNumElements(); 829f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 830f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 8312754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 8322754fe60SDimitry Andric if (V != &IE) 8333ca95b02SDimitry Andric return replaceInstUsesWith(IE, V); 834f22ef01cSRoman Divacky return &IE; 8352754fe60SDimitry Andric } 836f22ef01cSRoman Divacky 837d88c1a5aSDimitry Andric if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 838d88c1a5aSDimitry Andric return Shuf; 839d88c1a5aSDimitry Andric 840c4394386SDimitry Andric if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) 8417a7e6055SDimitry Andric return NewInsElt; 8427a7e6055SDimitry Andric 843d88c1a5aSDimitry Andric // Turn a sequence of inserts that broadcasts a scalar into a single 844d88c1a5aSDimitry Andric // insert + shufflevector. 845d88c1a5aSDimitry Andric if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE)) 846d88c1a5aSDimitry Andric return Broadcast; 847d88c1a5aSDimitry Andric 84891bc56edSDimitry Andric return nullptr; 849f22ef01cSRoman Divacky } 850f22ef01cSRoman Divacky 851f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector 852f785676fSDimitry Andric /// elements were shuffled in a different order. 853f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 854f785676fSDimitry Andric unsigned Depth = 5) { 855f785676fSDimitry Andric // We can always reorder the elements of a constant. 856f785676fSDimitry Andric if (isa<Constant>(V)) 857f785676fSDimitry Andric return true; 858f785676fSDimitry Andric 859f785676fSDimitry Andric // We won't reorder vector arguments. No IPO here. 860f785676fSDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 861f785676fSDimitry Andric if (!I) return false; 862f785676fSDimitry Andric 863f785676fSDimitry Andric // Two users may expect different orders of the elements. Don't try it. 864f785676fSDimitry Andric if (!I->hasOneUse()) 865f785676fSDimitry Andric return false; 866f785676fSDimitry Andric 867f785676fSDimitry Andric if (Depth == 0) return false; 868f785676fSDimitry Andric 869f785676fSDimitry Andric switch (I->getOpcode()) { 870f785676fSDimitry Andric case Instruction::Add: 871f785676fSDimitry Andric case Instruction::FAdd: 872f785676fSDimitry Andric case Instruction::Sub: 873f785676fSDimitry Andric case Instruction::FSub: 874f785676fSDimitry Andric case Instruction::Mul: 875f785676fSDimitry Andric case Instruction::FMul: 876f785676fSDimitry Andric case Instruction::UDiv: 877f785676fSDimitry Andric case Instruction::SDiv: 878f785676fSDimitry Andric case Instruction::FDiv: 879f785676fSDimitry Andric case Instruction::URem: 880f785676fSDimitry Andric case Instruction::SRem: 881f785676fSDimitry Andric case Instruction::FRem: 882f785676fSDimitry Andric case Instruction::Shl: 883f785676fSDimitry Andric case Instruction::LShr: 884f785676fSDimitry Andric case Instruction::AShr: 885f785676fSDimitry Andric case Instruction::And: 886f785676fSDimitry Andric case Instruction::Or: 887f785676fSDimitry Andric case Instruction::Xor: 888f785676fSDimitry Andric case Instruction::ICmp: 889f785676fSDimitry Andric case Instruction::FCmp: 890f785676fSDimitry Andric case Instruction::Trunc: 891f785676fSDimitry Andric case Instruction::ZExt: 892f785676fSDimitry Andric case Instruction::SExt: 893f785676fSDimitry Andric case Instruction::FPToUI: 894f785676fSDimitry Andric case Instruction::FPToSI: 895f785676fSDimitry Andric case Instruction::UIToFP: 896f785676fSDimitry Andric case Instruction::SIToFP: 897f785676fSDimitry Andric case Instruction::FPTrunc: 898f785676fSDimitry Andric case Instruction::FPExt: 899f785676fSDimitry Andric case Instruction::GetElementPtr: { 9007d523365SDimitry Andric for (Value *Operand : I->operands()) { 9017d523365SDimitry Andric if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 902f785676fSDimitry Andric return false; 903f785676fSDimitry Andric } 904f785676fSDimitry Andric return true; 905f785676fSDimitry Andric } 906f785676fSDimitry Andric case Instruction::InsertElement: { 907f785676fSDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 908f785676fSDimitry Andric if (!CI) return false; 909f785676fSDimitry Andric int ElementNumber = CI->getLimitedValue(); 910f785676fSDimitry Andric 911f785676fSDimitry Andric // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 912f785676fSDimitry Andric // can't put an element into multiple indices. 913f785676fSDimitry Andric bool SeenOnce = false; 914f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 915f785676fSDimitry Andric if (Mask[i] == ElementNumber) { 916f785676fSDimitry Andric if (SeenOnce) 917f785676fSDimitry Andric return false; 918f785676fSDimitry Andric SeenOnce = true; 919f785676fSDimitry Andric } 920f785676fSDimitry Andric } 921f785676fSDimitry Andric return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 922f785676fSDimitry Andric } 923f785676fSDimitry Andric } 924f785676fSDimitry Andric return false; 925f785676fSDimitry Andric } 926f785676fSDimitry Andric 927f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given. 928f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct. 9297d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 930f785676fSDimitry Andric // We don't want to use the IRBuilder here because we want the replacement 931f785676fSDimitry Andric // instructions to appear next to 'I', not the builder's insertion point. 932f785676fSDimitry Andric switch (I->getOpcode()) { 933f785676fSDimitry Andric case Instruction::Add: 934f785676fSDimitry Andric case Instruction::FAdd: 935f785676fSDimitry Andric case Instruction::Sub: 936f785676fSDimitry Andric case Instruction::FSub: 937f785676fSDimitry Andric case Instruction::Mul: 938f785676fSDimitry Andric case Instruction::FMul: 939f785676fSDimitry Andric case Instruction::UDiv: 940f785676fSDimitry Andric case Instruction::SDiv: 941f785676fSDimitry Andric case Instruction::FDiv: 942f785676fSDimitry Andric case Instruction::URem: 943f785676fSDimitry Andric case Instruction::SRem: 944f785676fSDimitry Andric case Instruction::FRem: 945f785676fSDimitry Andric case Instruction::Shl: 946f785676fSDimitry Andric case Instruction::LShr: 947f785676fSDimitry Andric case Instruction::AShr: 948f785676fSDimitry Andric case Instruction::And: 949f785676fSDimitry Andric case Instruction::Or: 950f785676fSDimitry Andric case Instruction::Xor: { 951f785676fSDimitry Andric BinaryOperator *BO = cast<BinaryOperator>(I); 952f785676fSDimitry Andric assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 953f785676fSDimitry Andric BinaryOperator *New = 954f785676fSDimitry Andric BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 955f785676fSDimitry Andric NewOps[0], NewOps[1], "", BO); 956f785676fSDimitry Andric if (isa<OverflowingBinaryOperator>(BO)) { 957f785676fSDimitry Andric New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 958f785676fSDimitry Andric New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 959f785676fSDimitry Andric } 960f785676fSDimitry Andric if (isa<PossiblyExactOperator>(BO)) { 961f785676fSDimitry Andric New->setIsExact(BO->isExact()); 962f785676fSDimitry Andric } 96391bc56edSDimitry Andric if (isa<FPMathOperator>(BO)) 96491bc56edSDimitry Andric New->copyFastMathFlags(I); 965f785676fSDimitry Andric return New; 966f785676fSDimitry Andric } 967f785676fSDimitry Andric case Instruction::ICmp: 968f785676fSDimitry Andric assert(NewOps.size() == 2 && "icmp with #ops != 2"); 969f785676fSDimitry Andric return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 970f785676fSDimitry Andric NewOps[0], NewOps[1]); 971f785676fSDimitry Andric case Instruction::FCmp: 972f785676fSDimitry Andric assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 973f785676fSDimitry Andric return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 974f785676fSDimitry Andric NewOps[0], NewOps[1]); 975f785676fSDimitry Andric case Instruction::Trunc: 976f785676fSDimitry Andric case Instruction::ZExt: 977f785676fSDimitry Andric case Instruction::SExt: 978f785676fSDimitry Andric case Instruction::FPToUI: 979f785676fSDimitry Andric case Instruction::FPToSI: 980f785676fSDimitry Andric case Instruction::UIToFP: 981f785676fSDimitry Andric case Instruction::SIToFP: 982f785676fSDimitry Andric case Instruction::FPTrunc: 983f785676fSDimitry Andric case Instruction::FPExt: { 984f785676fSDimitry Andric // It's possible that the mask has a different number of elements from 985f785676fSDimitry Andric // the original cast. We recompute the destination type to match the mask. 986f785676fSDimitry Andric Type *DestTy = 987f785676fSDimitry Andric VectorType::get(I->getType()->getScalarType(), 988f785676fSDimitry Andric NewOps[0]->getType()->getVectorNumElements()); 989f785676fSDimitry Andric assert(NewOps.size() == 1 && "cast with #ops != 1"); 990f785676fSDimitry Andric return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 991f785676fSDimitry Andric "", I); 992f785676fSDimitry Andric } 993f785676fSDimitry Andric case Instruction::GetElementPtr: { 994f785676fSDimitry Andric Value *Ptr = NewOps[0]; 995f785676fSDimitry Andric ArrayRef<Value*> Idx = NewOps.slice(1); 996ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create( 997ff0cc061SDimitry Andric cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 998f785676fSDimitry Andric GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 999f785676fSDimitry Andric return GEP; 1000f785676fSDimitry Andric } 1001f785676fSDimitry Andric } 1002f785676fSDimitry Andric llvm_unreachable("failed to rebuild vector instructions"); 1003f785676fSDimitry Andric } 1004f785676fSDimitry Andric 1005f785676fSDimitry Andric Value * 1006f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 1007f785676fSDimitry Andric // Mask.size() does not need to be equal to the number of vector elements. 1008f785676fSDimitry Andric 1009f785676fSDimitry Andric assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 1010f785676fSDimitry Andric if (isa<UndefValue>(V)) { 1011f785676fSDimitry Andric return UndefValue::get(VectorType::get(V->getType()->getScalarType(), 1012f785676fSDimitry Andric Mask.size())); 1013f785676fSDimitry Andric } 1014f785676fSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 1015f785676fSDimitry Andric return ConstantAggregateZero::get( 1016f785676fSDimitry Andric VectorType::get(V->getType()->getScalarType(), 1017f785676fSDimitry Andric Mask.size())); 1018f785676fSDimitry Andric } 1019f785676fSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 1020f785676fSDimitry Andric SmallVector<Constant *, 16> MaskValues; 1021f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 1022f785676fSDimitry Andric if (Mask[i] == -1) 1023c4394386SDimitry Andric MaskValues.push_back(UndefValue::get(Builder.getInt32Ty())); 1024f785676fSDimitry Andric else 1025c4394386SDimitry Andric MaskValues.push_back(Builder.getInt32(Mask[i])); 1026f785676fSDimitry Andric } 1027f785676fSDimitry Andric return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 1028f785676fSDimitry Andric ConstantVector::get(MaskValues)); 1029f785676fSDimitry Andric } 1030f785676fSDimitry Andric 1031f785676fSDimitry Andric Instruction *I = cast<Instruction>(V); 1032f785676fSDimitry Andric switch (I->getOpcode()) { 1033f785676fSDimitry Andric case Instruction::Add: 1034f785676fSDimitry Andric case Instruction::FAdd: 1035f785676fSDimitry Andric case Instruction::Sub: 1036f785676fSDimitry Andric case Instruction::FSub: 1037f785676fSDimitry Andric case Instruction::Mul: 1038f785676fSDimitry Andric case Instruction::FMul: 1039f785676fSDimitry Andric case Instruction::UDiv: 1040f785676fSDimitry Andric case Instruction::SDiv: 1041f785676fSDimitry Andric case Instruction::FDiv: 1042f785676fSDimitry Andric case Instruction::URem: 1043f785676fSDimitry Andric case Instruction::SRem: 1044f785676fSDimitry Andric case Instruction::FRem: 1045f785676fSDimitry Andric case Instruction::Shl: 1046f785676fSDimitry Andric case Instruction::LShr: 1047f785676fSDimitry Andric case Instruction::AShr: 1048f785676fSDimitry Andric case Instruction::And: 1049f785676fSDimitry Andric case Instruction::Or: 1050f785676fSDimitry Andric case Instruction::Xor: 1051f785676fSDimitry Andric case Instruction::ICmp: 1052f785676fSDimitry Andric case Instruction::FCmp: 1053f785676fSDimitry Andric case Instruction::Trunc: 1054f785676fSDimitry Andric case Instruction::ZExt: 1055f785676fSDimitry Andric case Instruction::SExt: 1056f785676fSDimitry Andric case Instruction::FPToUI: 1057f785676fSDimitry Andric case Instruction::FPToSI: 1058f785676fSDimitry Andric case Instruction::UIToFP: 1059f785676fSDimitry Andric case Instruction::SIToFP: 1060f785676fSDimitry Andric case Instruction::FPTrunc: 1061f785676fSDimitry Andric case Instruction::FPExt: 1062f785676fSDimitry Andric case Instruction::Select: 1063f785676fSDimitry Andric case Instruction::GetElementPtr: { 1064f785676fSDimitry Andric SmallVector<Value*, 8> NewOps; 1065f785676fSDimitry Andric bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 1066f785676fSDimitry Andric for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 1067f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 1068f785676fSDimitry Andric NewOps.push_back(V); 1069f785676fSDimitry Andric NeedsRebuild |= (V != I->getOperand(i)); 1070f785676fSDimitry Andric } 1071f785676fSDimitry Andric if (NeedsRebuild) { 10727d523365SDimitry Andric return buildNew(I, NewOps); 1073f785676fSDimitry Andric } 1074f785676fSDimitry Andric return I; 1075f785676fSDimitry Andric } 1076f785676fSDimitry Andric case Instruction::InsertElement: { 1077f785676fSDimitry Andric int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 1078f785676fSDimitry Andric 1079f785676fSDimitry Andric // The insertelement was inserting at Element. Figure out which element 1080f785676fSDimitry Andric // that becomes after shuffling. The answer is guaranteed to be unique 1081f785676fSDimitry Andric // by CanEvaluateShuffled. 1082f785676fSDimitry Andric bool Found = false; 1083f785676fSDimitry Andric int Index = 0; 1084f785676fSDimitry Andric for (int e = Mask.size(); Index != e; ++Index) { 1085f785676fSDimitry Andric if (Mask[Index] == Element) { 1086f785676fSDimitry Andric Found = true; 1087f785676fSDimitry Andric break; 1088f785676fSDimitry Andric } 1089f785676fSDimitry Andric } 1090f785676fSDimitry Andric 109191bc56edSDimitry Andric // If element is not in Mask, no need to handle the operand 1 (element to 109291bc56edSDimitry Andric // be inserted). Just evaluate values in operand 0 according to Mask. 1093f785676fSDimitry Andric if (!Found) 109491bc56edSDimitry Andric return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1095f785676fSDimitry Andric 1096f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1097f785676fSDimitry Andric return InsertElementInst::Create(V, I->getOperand(1), 1098c4394386SDimitry Andric Builder.getInt32(Index), "", I); 1099f785676fSDimitry Andric } 1100f785676fSDimitry Andric } 1101f785676fSDimitry Andric llvm_unreachable("failed to reorder elements of vector instruction!"); 1102f785676fSDimitry Andric } 1103f22ef01cSRoman Divacky 11047d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 110591bc56edSDimitry Andric bool &isLHSID, bool &isRHSID) { 110691bc56edSDimitry Andric isLHSID = isRHSID = true; 110791bc56edSDimitry Andric 110891bc56edSDimitry Andric for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 110991bc56edSDimitry Andric if (Mask[i] < 0) continue; // Ignore undef values. 111091bc56edSDimitry Andric // Is this an identity shuffle of the LHS value? 111191bc56edSDimitry Andric isLHSID &= (Mask[i] == (int)i); 111291bc56edSDimitry Andric 111391bc56edSDimitry Andric // Is this an identity shuffle of the RHS value? 111491bc56edSDimitry Andric isRHSID &= (Mask[i]-e == i); 111591bc56edSDimitry Andric } 111691bc56edSDimitry Andric } 111791bc56edSDimitry Andric 1118ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from 1119ff0cc061SDimitry Andric // LHS, for example: 1120ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1121ff0cc061SDimitry Andric // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1122ff0cc061SDimitry Andric // Shuffles to: |EE|FF|GG|HH| 1123ff0cc061SDimitry Andric // +--+--+--+--+ 1124ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1125ff0cc061SDimitry Andric SmallVector<int, 16> &Mask) { 1126d88c1a5aSDimitry Andric unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements(); 1127ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1128ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 1129ff0cc061SDimitry Andric unsigned EndIdx = Mask.back(); 1130ff0cc061SDimitry Andric if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1131ff0cc061SDimitry Andric return false; 1132ff0cc061SDimitry Andric for (unsigned I = 0; I != MaskElems; ++I) 1133ff0cc061SDimitry Andric if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1134ff0cc061SDimitry Andric return false; 1135ff0cc061SDimitry Andric return true; 1136ff0cc061SDimitry Andric } 1137ff0cc061SDimitry Andric 1138f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 1139f22ef01cSRoman Divacky Value *LHS = SVI.getOperand(0); 1140f22ef01cSRoman Divacky Value *RHS = SVI.getOperand(1); 1141dff0c46cSDimitry Andric SmallVector<int, 16> Mask = SVI.getShuffleMask(); 1142ff0cc061SDimitry Andric Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 1143f22ef01cSRoman Divacky 1144db17bf38SDimitry Andric if (auto *V = SimplifyShuffleVectorInst( 1145db17bf38SDimitry Andric LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI))) 11467a7e6055SDimitry Andric return replaceInstUsesWith(SVI, V); 11477a7e6055SDimitry Andric 1148f22ef01cSRoman Divacky bool MadeChange = false; 1149d88c1a5aSDimitry Andric unsigned VWidth = SVI.getType()->getVectorNumElements(); 1150f22ef01cSRoman Divacky 1151f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 1152f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 11532754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 11542754fe60SDimitry Andric if (V != &SVI) 11553ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 1156f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 1157f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 1158f22ef01cSRoman Divacky MadeChange = true; 1159f22ef01cSRoman Divacky } 1160f22ef01cSRoman Divacky 1161d88c1a5aSDimitry Andric unsigned LHSWidth = LHS->getType()->getVectorNumElements(); 1162dff0c46cSDimitry Andric 1163f22ef01cSRoman Divacky // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 1164f22ef01cSRoman Divacky // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 1165f22ef01cSRoman Divacky if (LHS == RHS || isa<UndefValue>(LHS)) { 1166f22ef01cSRoman Divacky if (isa<UndefValue>(LHS) && LHS == RHS) { 1167f22ef01cSRoman Divacky // shuffle(undef,undef,mask) -> undef. 1168f785676fSDimitry Andric Value *Result = (VWidth == LHSWidth) 1169dff0c46cSDimitry Andric ? LHS : UndefValue::get(SVI.getType()); 11703ca95b02SDimitry Andric return replaceInstUsesWith(SVI, Result); 1171f22ef01cSRoman Divacky } 1172f22ef01cSRoman Divacky 1173f22ef01cSRoman Divacky // Remap any references to RHS to use LHS. 1174dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1175dff0c46cSDimitry Andric for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 1176dff0c46cSDimitry Andric if (Mask[i] < 0) { 1177ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1178dff0c46cSDimitry Andric continue; 1179dff0c46cSDimitry Andric } 1180dff0c46cSDimitry Andric 11812754fe60SDimitry Andric if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 11822754fe60SDimitry Andric (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 11832754fe60SDimitry Andric Mask[i] = -1; // Turn into undef. 1184ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1185f22ef01cSRoman Divacky } else { 1186f22ef01cSRoman Divacky Mask[i] = Mask[i] % e; // Force to LHS. 1187ff0cc061SDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 1188f22ef01cSRoman Divacky } 1189f22ef01cSRoman Divacky } 1190f22ef01cSRoman Divacky SVI.setOperand(0, SVI.getOperand(1)); 1191f22ef01cSRoman Divacky SVI.setOperand(1, UndefValue::get(RHS->getType())); 1192f22ef01cSRoman Divacky SVI.setOperand(2, ConstantVector::get(Elts)); 1193f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 1194f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 1195f22ef01cSRoman Divacky MadeChange = true; 1196f22ef01cSRoman Divacky } 1197f22ef01cSRoman Divacky 1198dff0c46cSDimitry Andric if (VWidth == LHSWidth) { 1199f22ef01cSRoman Divacky // Analyze the shuffle, are the LHS or RHS and identity shuffles? 120091bc56edSDimitry Andric bool isLHSID, isRHSID; 12017d523365SDimitry Andric recognizeIdentityMask(Mask, isLHSID, isRHSID); 1202f22ef01cSRoman Divacky 1203f22ef01cSRoman Divacky // Eliminate identity shuffles. 12043ca95b02SDimitry Andric if (isLHSID) return replaceInstUsesWith(SVI, LHS); 12053ca95b02SDimitry Andric if (isRHSID) return replaceInstUsesWith(SVI, RHS); 1206dff0c46cSDimitry Andric } 1207f22ef01cSRoman Divacky 1208f785676fSDimitry Andric if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 1209f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 12103ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 1211f785676fSDimitry Andric } 1212f785676fSDimitry Andric 1213ff0cc061SDimitry Andric // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 1214ff0cc061SDimitry Andric // a non-vector type. We can instead bitcast the original vector followed by 1215ff0cc061SDimitry Andric // an extract of the desired element: 1216ff0cc061SDimitry Andric // 1217ff0cc061SDimitry Andric // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1218ff0cc061SDimitry Andric // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1219ff0cc061SDimitry Andric // %1 = bitcast <4 x i8> %sroa to i32 1220ff0cc061SDimitry Andric // Becomes: 1221ff0cc061SDimitry Andric // %bc = bitcast <16 x i8> %in to <4 x i32> 1222ff0cc061SDimitry Andric // %ext = extractelement <4 x i32> %bc, i32 0 1223ff0cc061SDimitry Andric // 1224ff0cc061SDimitry Andric // If the shuffle is extracting a contiguous range of values from the input 1225ff0cc061SDimitry Andric // vector then each use which is a bitcast of the extracted size can be 1226ff0cc061SDimitry Andric // replaced. This will work if the vector types are compatible, and the begin 1227ff0cc061SDimitry Andric // index is aligned to a value in the casted vector type. If the begin index 1228ff0cc061SDimitry Andric // isn't aligned then we can shuffle the original vector (keeping the same 1229ff0cc061SDimitry Andric // vector type) before extracting. 1230ff0cc061SDimitry Andric // 1231ff0cc061SDimitry Andric // This code will bail out if the target type is fundamentally incompatible 1232ff0cc061SDimitry Andric // with vectors of the source type. 1233ff0cc061SDimitry Andric // 1234ff0cc061SDimitry Andric // Example of <16 x i8>, target type i32: 1235ff0cc061SDimitry Andric // Index range [4,8): v-----------v Will work. 1236ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1237ff0cc061SDimitry Andric // <16 x i8>: | | | | | | | | | | | | | | | | | 1238ff0cc061SDimitry Andric // <4 x i32>: | | | | | 1239ff0cc061SDimitry Andric // +-----------+-----------+-----------+-----------+ 1240ff0cc061SDimitry Andric // Index range [6,10): ^-----------^ Needs an extra shuffle. 1241ff0cc061SDimitry Andric // Target type i40: ^--------------^ Won't work, bail. 1242ff0cc061SDimitry Andric if (isShuffleExtractingFromLHS(SVI, Mask)) { 1243ff0cc061SDimitry Andric Value *V = LHS; 1244ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1245ff0cc061SDimitry Andric VectorType *SrcTy = cast<VectorType>(V->getType()); 1246ff0cc061SDimitry Andric unsigned VecBitWidth = SrcTy->getBitWidth(); 1247ff0cc061SDimitry Andric unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1248ff0cc061SDimitry Andric assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1249ff0cc061SDimitry Andric unsigned SrcNumElems = SrcTy->getNumElements(); 1250ff0cc061SDimitry Andric SmallVector<BitCastInst *, 8> BCs; 1251ff0cc061SDimitry Andric DenseMap<Type *, Value *> NewBCs; 1252ff0cc061SDimitry Andric for (User *U : SVI.users()) 1253ff0cc061SDimitry Andric if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1254ff0cc061SDimitry Andric if (!BC->use_empty()) 1255ff0cc061SDimitry Andric // Only visit bitcasts that weren't previously handled. 1256ff0cc061SDimitry Andric BCs.push_back(BC); 1257ff0cc061SDimitry Andric for (BitCastInst *BC : BCs) { 12587a7e6055SDimitry Andric unsigned BegIdx = Mask.front(); 1259ff0cc061SDimitry Andric Type *TgtTy = BC->getDestTy(); 1260ff0cc061SDimitry Andric unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1261ff0cc061SDimitry Andric if (!TgtElemBitWidth) 1262ff0cc061SDimitry Andric continue; 1263ff0cc061SDimitry Andric unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1264ff0cc061SDimitry Andric bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1265ff0cc061SDimitry Andric bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1266ff0cc061SDimitry Andric if (!VecBitWidthsEqual) 1267ff0cc061SDimitry Andric continue; 1268ff0cc061SDimitry Andric if (!VectorType::isValidElementType(TgtTy)) 1269ff0cc061SDimitry Andric continue; 1270ff0cc061SDimitry Andric VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1271ff0cc061SDimitry Andric if (!BegIsAligned) { 1272ff0cc061SDimitry Andric // Shuffle the input so [0,NumElements) contains the output, and 1273ff0cc061SDimitry Andric // [NumElems,SrcNumElems) is undef. 1274ff0cc061SDimitry Andric SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1275ff0cc061SDimitry Andric UndefValue::get(Int32Ty)); 1276ff0cc061SDimitry Andric for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1277ff0cc061SDimitry Andric ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1278c4394386SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), 1279ff0cc061SDimitry Andric ConstantVector::get(ShuffleMask), 1280ff0cc061SDimitry Andric SVI.getName() + ".extract"); 1281ff0cc061SDimitry Andric BegIdx = 0; 1282ff0cc061SDimitry Andric } 1283ff0cc061SDimitry Andric unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1284ff0cc061SDimitry Andric assert(SrcElemsPerTgtElem); 1285ff0cc061SDimitry Andric BegIdx /= SrcElemsPerTgtElem; 1286ff0cc061SDimitry Andric bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1287ff0cc061SDimitry Andric auto *NewBC = 1288ff0cc061SDimitry Andric BCAlreadyExists 1289ff0cc061SDimitry Andric ? NewBCs[CastSrcTy] 1290c4394386SDimitry Andric : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1291ff0cc061SDimitry Andric if (!BCAlreadyExists) 1292ff0cc061SDimitry Andric NewBCs[CastSrcTy] = NewBC; 1293c4394386SDimitry Andric auto *Ext = Builder.CreateExtractElement( 1294ff0cc061SDimitry Andric NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1295ff0cc061SDimitry Andric // The shufflevector isn't being replaced: the bitcast that used it 1296ff0cc061SDimitry Andric // is. InstCombine will visit the newly-created instructions. 12973ca95b02SDimitry Andric replaceInstUsesWith(*BC, Ext); 1298ff0cc061SDimitry Andric MadeChange = true; 1299ff0cc061SDimitry Andric } 1300ff0cc061SDimitry Andric } 1301ff0cc061SDimitry Andric 1302f22ef01cSRoman Divacky // If the LHS is a shufflevector itself, see if we can combine it with this 1303dff0c46cSDimitry Andric // one without producing an unusual shuffle. 1304dff0c46cSDimitry Andric // Cases that might be simplified: 1305dff0c46cSDimitry Andric // 1. 1306dff0c46cSDimitry Andric // x1=shuffle(v1,v2,mask1) 1307dff0c46cSDimitry Andric // x=shuffle(x1,undef,mask) 1308dff0c46cSDimitry Andric // ==> 1309dff0c46cSDimitry Andric // x=shuffle(v1,undef,newMask) 1310dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1311dff0c46cSDimitry Andric // 2. 1312dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1313dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1314dff0c46cSDimitry Andric // where v1.size() == mask1.size() 1315dff0c46cSDimitry Andric // ==> 1316dff0c46cSDimitry Andric // x=shuffle(v1,x2,newMask) 1317dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1318dff0c46cSDimitry Andric // 3. 1319dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1320dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1321dff0c46cSDimitry Andric // where v2.size() == mask2.size() 1322dff0c46cSDimitry Andric // ==> 1323dff0c46cSDimitry Andric // x=shuffle(x1,v2,newMask) 1324dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1325dff0c46cSDimitry Andric // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1326dff0c46cSDimitry Andric // 4. 1327dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1328dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1329dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1330dff0c46cSDimitry Andric // where v1.size() == v2.size() 1331dff0c46cSDimitry Andric // ==> 1332dff0c46cSDimitry Andric // x=shuffle(v1,v2,newMask) 1333dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1334dff0c46cSDimitry Andric // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1335dff0c46cSDimitry Andric // 1336dff0c46cSDimitry Andric // Here we are really conservative: 1337f22ef01cSRoman Divacky // we are absolutely afraid of producing a shuffle mask not in the input 1338f22ef01cSRoman Divacky // program, because the code gen may not be smart enough to turn a merged 1339f22ef01cSRoman Divacky // shuffle into two specific shuffles: it may produce worse code. As such, 13402754fe60SDimitry Andric // we only merge two shuffles if the result is either a splat or one of the 1341dff0c46cSDimitry Andric // input shuffle masks. In this case, merging the shuffles just removes 13422754fe60SDimitry Andric // one instruction, which we know is safe. This is good for things like 1343dff0c46cSDimitry Andric // turning: (splat(splat)) -> splat, or 1344dff0c46cSDimitry Andric // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1345dff0c46cSDimitry Andric ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1346dff0c46cSDimitry Andric ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1347dff0c46cSDimitry Andric if (LHSShuffle) 1348dff0c46cSDimitry Andric if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 134991bc56edSDimitry Andric LHSShuffle = nullptr; 1350dff0c46cSDimitry Andric if (RHSShuffle) 1351dff0c46cSDimitry Andric if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 135291bc56edSDimitry Andric RHSShuffle = nullptr; 1353dff0c46cSDimitry Andric if (!LHSShuffle && !RHSShuffle) 135491bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1355dff0c46cSDimitry Andric 135691bc56edSDimitry Andric Value* LHSOp0 = nullptr; 135791bc56edSDimitry Andric Value* LHSOp1 = nullptr; 135891bc56edSDimitry Andric Value* RHSOp0 = nullptr; 1359dff0c46cSDimitry Andric unsigned LHSOp0Width = 0; 1360dff0c46cSDimitry Andric unsigned RHSOp0Width = 0; 1361dff0c46cSDimitry Andric if (LHSShuffle) { 1362dff0c46cSDimitry Andric LHSOp0 = LHSShuffle->getOperand(0); 1363dff0c46cSDimitry Andric LHSOp1 = LHSShuffle->getOperand(1); 1364d88c1a5aSDimitry Andric LHSOp0Width = LHSOp0->getType()->getVectorNumElements(); 1365dff0c46cSDimitry Andric } 1366dff0c46cSDimitry Andric if (RHSShuffle) { 1367dff0c46cSDimitry Andric RHSOp0 = RHSShuffle->getOperand(0); 1368d88c1a5aSDimitry Andric RHSOp0Width = RHSOp0->getType()->getVectorNumElements(); 1369dff0c46cSDimitry Andric } 1370dff0c46cSDimitry Andric Value* newLHS = LHS; 1371dff0c46cSDimitry Andric Value* newRHS = RHS; 1372dff0c46cSDimitry Andric if (LHSShuffle) { 1373dff0c46cSDimitry Andric // case 1 1374f22ef01cSRoman Divacky if (isa<UndefValue>(RHS)) { 1375dff0c46cSDimitry Andric newLHS = LHSOp0; 1376dff0c46cSDimitry Andric newRHS = LHSOp1; 1377dff0c46cSDimitry Andric } 1378dff0c46cSDimitry Andric // case 2 or 4 1379dff0c46cSDimitry Andric else if (LHSOp0Width == LHSWidth) { 1380dff0c46cSDimitry Andric newLHS = LHSOp0; 1381dff0c46cSDimitry Andric } 1382dff0c46cSDimitry Andric } 1383dff0c46cSDimitry Andric // case 3 or 4 1384dff0c46cSDimitry Andric if (RHSShuffle && RHSOp0Width == LHSWidth) { 1385dff0c46cSDimitry Andric newRHS = RHSOp0; 1386dff0c46cSDimitry Andric } 1387dff0c46cSDimitry Andric // case 4 1388dff0c46cSDimitry Andric if (LHSOp0 == RHSOp0) { 1389dff0c46cSDimitry Andric newLHS = LHSOp0; 139091bc56edSDimitry Andric newRHS = nullptr; 1391dff0c46cSDimitry Andric } 1392f22ef01cSRoman Divacky 1393dff0c46cSDimitry Andric if (newLHS == LHS && newRHS == RHS) 139491bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1395dff0c46cSDimitry Andric 1396dff0c46cSDimitry Andric SmallVector<int, 16> LHSMask; 1397dff0c46cSDimitry Andric SmallVector<int, 16> RHSMask; 1398dff0c46cSDimitry Andric if (newLHS != LHS) 1399dff0c46cSDimitry Andric LHSMask = LHSShuffle->getShuffleMask(); 1400dff0c46cSDimitry Andric if (RHSShuffle && newRHS != RHS) 1401dff0c46cSDimitry Andric RHSMask = RHSShuffle->getShuffleMask(); 1402dff0c46cSDimitry Andric 1403dff0c46cSDimitry Andric unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1404dff0c46cSDimitry Andric SmallVector<int, 16> newMask; 14052754fe60SDimitry Andric bool isSplat = true; 1406dff0c46cSDimitry Andric int SplatElt = -1; 1407dff0c46cSDimitry Andric // Create a new mask for the new ShuffleVectorInst so that the new 1408dff0c46cSDimitry Andric // ShuffleVectorInst is equivalent to the original one. 1409dff0c46cSDimitry Andric for (unsigned i = 0; i < VWidth; ++i) { 1410dff0c46cSDimitry Andric int eltMask; 1411139f7f9bSDimitry Andric if (Mask[i] < 0) { 1412dff0c46cSDimitry Andric // This element is an undef value. 1413dff0c46cSDimitry Andric eltMask = -1; 1414dff0c46cSDimitry Andric } else if (Mask[i] < (int)LHSWidth) { 1415dff0c46cSDimitry Andric // This element is from left hand side vector operand. 1416dff0c46cSDimitry Andric // 1417dff0c46cSDimitry Andric // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1418dff0c46cSDimitry Andric // new mask value for the element. 1419dff0c46cSDimitry Andric if (newLHS != LHS) { 1420dff0c46cSDimitry Andric eltMask = LHSMask[Mask[i]]; 1421dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1422dff0c46cSDimitry Andric // with a -1 mask value. 1423dff0c46cSDimitry Andric if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1424dff0c46cSDimitry Andric eltMask = -1; 1425139f7f9bSDimitry Andric } else 1426dff0c46cSDimitry Andric eltMask = Mask[i]; 1427dff0c46cSDimitry Andric } else { 1428dff0c46cSDimitry Andric // This element is from right hand side vector operand 1429dff0c46cSDimitry Andric // 1430dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1431dff0c46cSDimitry Andric // with a -1 mask value. (case 1) 1432dff0c46cSDimitry Andric if (isa<UndefValue>(RHS)) 1433dff0c46cSDimitry Andric eltMask = -1; 1434dff0c46cSDimitry Andric // If RHS is going to be replaced (case 3 or 4), calculate the 1435dff0c46cSDimitry Andric // new mask value for the element. 1436dff0c46cSDimitry Andric else if (newRHS != RHS) { 1437dff0c46cSDimitry Andric eltMask = RHSMask[Mask[i]-LHSWidth]; 1438dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1439dff0c46cSDimitry Andric // with a -1 mask value. 1440dff0c46cSDimitry Andric if (eltMask >= (int)RHSOp0Width) { 1441dff0c46cSDimitry Andric assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1442dff0c46cSDimitry Andric && "should have been check above"); 1443dff0c46cSDimitry Andric eltMask = -1; 1444dff0c46cSDimitry Andric } 1445139f7f9bSDimitry Andric } else 1446dff0c46cSDimitry Andric eltMask = Mask[i]-LHSWidth; 1447dff0c46cSDimitry Andric 1448dff0c46cSDimitry Andric // If LHS's width is changed, shift the mask value accordingly. 1449dff0c46cSDimitry Andric // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any 14503861d79fSDimitry Andric // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 14513861d79fSDimitry Andric // If newRHS == newLHS, we want to remap any references from newRHS to 14523861d79fSDimitry Andric // newLHS so that we can properly identify splats that may occur due to 145391bc56edSDimitry Andric // obfuscation across the two vectors. 145491bc56edSDimitry Andric if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1455dff0c46cSDimitry Andric eltMask += newLHSWidth; 14562754fe60SDimitry Andric } 1457f22ef01cSRoman Divacky 1458dff0c46cSDimitry Andric // Check if this could still be a splat. 1459dff0c46cSDimitry Andric if (eltMask >= 0) { 1460dff0c46cSDimitry Andric if (SplatElt >= 0 && SplatElt != eltMask) 1461dff0c46cSDimitry Andric isSplat = false; 1462dff0c46cSDimitry Andric SplatElt = eltMask; 1463dff0c46cSDimitry Andric } 1464dff0c46cSDimitry Andric 1465dff0c46cSDimitry Andric newMask.push_back(eltMask); 1466dff0c46cSDimitry Andric } 1467dff0c46cSDimitry Andric 1468dff0c46cSDimitry Andric // If the result mask is equal to one of the original shuffle masks, 1469dff0c46cSDimitry Andric // or is a splat, do the replacement. 1470dff0c46cSDimitry Andric if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1471dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1472dff0c46cSDimitry Andric for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1473dff0c46cSDimitry Andric if (newMask[i] < 0) { 14742754fe60SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1475f22ef01cSRoman Divacky } else { 1476dff0c46cSDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1477f22ef01cSRoman Divacky } 1478f22ef01cSRoman Divacky } 147991bc56edSDimitry Andric if (!newRHS) 1480dff0c46cSDimitry Andric newRHS = UndefValue::get(newLHS->getType()); 1481dff0c46cSDimitry Andric return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1482f22ef01cSRoman Divacky } 1483f22ef01cSRoman Divacky 148491bc56edSDimitry Andric // If the result mask is an identity, replace uses of this instruction with 148591bc56edSDimitry Andric // corresponding argument. 148691bc56edSDimitry Andric bool isLHSID, isRHSID; 14877d523365SDimitry Andric recognizeIdentityMask(newMask, isLHSID, isRHSID); 14883ca95b02SDimitry Andric if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 14893ca95b02SDimitry Andric if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 149091bc56edSDimitry Andric 149191bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1492f22ef01cSRoman Divacky } 1493