1f22ef01cSRoman Divacky //===- InstCombineVectorOps.cpp -------------------------------------------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This file implements instcombine for ExtractElement, InsertElement and 11f22ef01cSRoman Divacky // ShuffleVector. 12f22ef01cSRoman Divacky // 13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 14f22ef01cSRoman Divacky 15ff0cc061SDimitry Andric #include "InstCombineInternal.h" 16ff0cc061SDimitry Andric #include "llvm/ADT/DenseMap.h" 17875ed548SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 18875ed548SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 1991bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h" 20f22ef01cSRoman Divacky using namespace llvm; 21139f7f9bSDimitry Andric using namespace PatternMatch; 22f22ef01cSRoman Divacky 2391bc56edSDimitry Andric #define DEBUG_TYPE "instcombine" 2491bc56edSDimitry Andric 257d523365SDimitry Andric /// Return true if the value is cheaper to scalarize than it is to leave as a 267d523365SDimitry Andric /// vector operation. isConstant indicates whether we're extracting one known 277d523365SDimitry Andric /// element. If false we're extracting a variable index. 287d523365SDimitry Andric static bool cheapToScalarize(Value *V, bool isConstant) { 29dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 30f22ef01cSRoman Divacky if (isConstant) return true; 31dff0c46cSDimitry Andric 32dff0c46cSDimitry Andric // If all elts are the same, we can extract it and use any of the values. 3385d60e68SDimitry Andric if (Constant *Op0 = C->getAggregateElement(0U)) { 3485d60e68SDimitry Andric for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; 3585d60e68SDimitry Andric ++i) 36dff0c46cSDimitry Andric if (C->getAggregateElement(i) != Op0) 37f22ef01cSRoman Divacky return false; 38f22ef01cSRoman Divacky return true; 39f22ef01cSRoman Divacky } 4085d60e68SDimitry Andric } 41f22ef01cSRoman Divacky Instruction *I = dyn_cast<Instruction>(V); 42f22ef01cSRoman Divacky if (!I) return false; 43f22ef01cSRoman Divacky 44f22ef01cSRoman Divacky // Insert element gets simplified to the inserted element or is deleted if 45f22ef01cSRoman Divacky // this is constant idx extract element and its a constant idx insertelt. 46f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::InsertElement && isConstant && 47f22ef01cSRoman Divacky isa<ConstantInt>(I->getOperand(2))) 48f22ef01cSRoman Divacky return true; 49f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::Load && I->hasOneUse()) 50f22ef01cSRoman Divacky return true; 51f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) 52f22ef01cSRoman Divacky if (BO->hasOneUse() && 537d523365SDimitry Andric (cheapToScalarize(BO->getOperand(0), isConstant) || 547d523365SDimitry Andric cheapToScalarize(BO->getOperand(1), isConstant))) 55f22ef01cSRoman Divacky return true; 56f22ef01cSRoman Divacky if (CmpInst *CI = dyn_cast<CmpInst>(I)) 57f22ef01cSRoman Divacky if (CI->hasOneUse() && 587d523365SDimitry Andric (cheapToScalarize(CI->getOperand(0), isConstant) || 597d523365SDimitry Andric cheapToScalarize(CI->getOperand(1), isConstant))) 60f22ef01cSRoman Divacky return true; 61f22ef01cSRoman Divacky 62f22ef01cSRoman Divacky return false; 63f22ef01cSRoman Divacky } 64f22ef01cSRoman Divacky 653ca95b02SDimitry Andric // If we have a PHI node with a vector type that is only used to feed 66f785676fSDimitry Andric // itself and be an operand of extractelement at a constant location, 67f785676fSDimitry Andric // try to replace the PHI of the vector type with a PHI of a scalar type. 68284c1978SDimitry Andric Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { 693ca95b02SDimitry Andric SmallVector<Instruction *, 2> Extracts; 703ca95b02SDimitry Andric // The users we want the PHI to have are: 713ca95b02SDimitry Andric // 1) The EI ExtractElement (we already know this) 723ca95b02SDimitry Andric // 2) Possibly more ExtractElements with the same index. 733ca95b02SDimitry Andric // 3) Another operand, which will feed back into the PHI. 743ca95b02SDimitry Andric Instruction *PHIUser = nullptr; 753ca95b02SDimitry Andric for (auto U : PN->users()) { 763ca95b02SDimitry Andric if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 773ca95b02SDimitry Andric if (EI.getIndexOperand() == EU->getIndexOperand()) 783ca95b02SDimitry Andric Extracts.push_back(EU); 793ca95b02SDimitry Andric else 8091bc56edSDimitry Andric return nullptr; 813ca95b02SDimitry Andric } else if (!PHIUser) { 823ca95b02SDimitry Andric PHIUser = cast<Instruction>(U); 833ca95b02SDimitry Andric } else { 843ca95b02SDimitry Andric return nullptr; 853ca95b02SDimitry Andric } 863ca95b02SDimitry Andric } 87284c1978SDimitry Andric 883ca95b02SDimitry Andric if (!PHIUser) 893ca95b02SDimitry Andric return nullptr; 90284c1978SDimitry Andric 91284c1978SDimitry Andric // Verify that this PHI user has one use, which is the PHI itself, 92284c1978SDimitry Andric // and that it is a binary operation which is cheap to scalarize. 93284c1978SDimitry Andric // otherwise return NULL. 9491bc56edSDimitry Andric if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 957d523365SDimitry Andric !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) 9691bc56edSDimitry Andric return nullptr; 97284c1978SDimitry Andric 98284c1978SDimitry Andric // Create a scalar PHI node that will replace the vector PHI node 99284c1978SDimitry Andric // just before the current PHI node. 100f785676fSDimitry Andric PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 101f785676fSDimitry Andric PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 102284c1978SDimitry Andric // Scalarize each PHI operand. 103284c1978SDimitry Andric for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 104284c1978SDimitry Andric Value *PHIInVal = PN->getIncomingValue(i); 105284c1978SDimitry Andric BasicBlock *inBB = PN->getIncomingBlock(i); 106284c1978SDimitry Andric Value *Elt = EI.getIndexOperand(); 107284c1978SDimitry Andric // If the operand is the PHI induction variable: 108284c1978SDimitry Andric if (PHIInVal == PHIUser) { 109284c1978SDimitry Andric // Scalarize the binary operation. Its first operand is the 11091bc56edSDimitry Andric // scalar PHI, and the second operand is extracted from the other 111284c1978SDimitry Andric // vector operand. 112284c1978SDimitry Andric BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 113284c1978SDimitry Andric unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 114f785676fSDimitry Andric Value *Op = InsertNewInstWith( 115f785676fSDimitry Andric ExtractElementInst::Create(B0->getOperand(opId), Elt, 116f785676fSDimitry Andric B0->getOperand(opId)->getName() + ".Elt"), 117284c1978SDimitry Andric *B0); 118f785676fSDimitry Andric Value *newPHIUser = InsertNewInstWith( 1193ca95b02SDimitry Andric BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 1203ca95b02SDimitry Andric scalarPHI, Op, B0), *B0); 121284c1978SDimitry Andric scalarPHI->addIncoming(newPHIUser, inBB); 122284c1978SDimitry Andric } else { 123284c1978SDimitry Andric // Scalarize PHI input: 124f785676fSDimitry Andric Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 125284c1978SDimitry Andric // Insert the new instruction into the predecessor basic block. 126284c1978SDimitry Andric Instruction *pos = dyn_cast<Instruction>(PHIInVal); 127284c1978SDimitry Andric BasicBlock::iterator InsertPos; 128284c1978SDimitry Andric if (pos && !isa<PHINode>(pos)) { 1297d523365SDimitry Andric InsertPos = ++pos->getIterator(); 130284c1978SDimitry Andric } else { 131284c1978SDimitry Andric InsertPos = inBB->getFirstInsertionPt(); 132284c1978SDimitry Andric } 133284c1978SDimitry Andric 134284c1978SDimitry Andric InsertNewInstWith(newEI, *InsertPos); 135284c1978SDimitry Andric 136284c1978SDimitry Andric scalarPHI->addIncoming(newEI, inBB); 137284c1978SDimitry Andric } 138284c1978SDimitry Andric } 1393ca95b02SDimitry Andric 1403ca95b02SDimitry Andric for (auto E : Extracts) 1413ca95b02SDimitry Andric replaceInstUsesWith(*E, scalarPHI); 1423ca95b02SDimitry Andric 1433ca95b02SDimitry Andric return &EI; 144284c1978SDimitry Andric } 145284c1978SDimitry Andric 146f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { 147875ed548SDimitry Andric if (Value *V = SimplifyExtractElementInst( 148875ed548SDimitry Andric EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC)) 1493ca95b02SDimitry Andric return replaceInstUsesWith(EI, V); 150875ed548SDimitry Andric 151f22ef01cSRoman Divacky // If vector val is constant with all elements the same, replace EI with 152dff0c46cSDimitry Andric // that element. We handle a known element # below. 153dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 1547d523365SDimitry Andric if (cheapToScalarize(C, false)) 1553ca95b02SDimitry Andric return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 156f22ef01cSRoman Divacky 157f22ef01cSRoman Divacky // If extracting a specified index from the vector, see if we can recursively 158f22ef01cSRoman Divacky // find a previously computed scalar that was inserted into the vector. 159f22ef01cSRoman Divacky if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 160f22ef01cSRoman Divacky unsigned IndexVal = IdxC->getZExtValue(); 161f22ef01cSRoman Divacky unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 162f22ef01cSRoman Divacky 163875ed548SDimitry Andric // InstSimplify handles cases where the index is invalid. 164875ed548SDimitry Andric assert(IndexVal < VectorWidth); 165f22ef01cSRoman Divacky 166f22ef01cSRoman Divacky // This instruction only demands the single element from the input vector. 167f22ef01cSRoman Divacky // If the input vector has a single use, simplify it based on this use 168f22ef01cSRoman Divacky // property. 169f22ef01cSRoman Divacky if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 170f22ef01cSRoman Divacky APInt UndefElts(VectorWidth, 0); 171f22ef01cSRoman Divacky APInt DemandedMask(VectorWidth, 0); 1722754fe60SDimitry Andric DemandedMask.setBit(IndexVal); 173ff0cc061SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 174ff0cc061SDimitry Andric UndefElts)) { 175f22ef01cSRoman Divacky EI.setOperand(0, V); 176f22ef01cSRoman Divacky return &EI; 177f22ef01cSRoman Divacky } 178f22ef01cSRoman Divacky } 179f22ef01cSRoman Divacky 1807d523365SDimitry Andric // If this extractelement is directly using a bitcast from a vector of 181f22ef01cSRoman Divacky // the same number of elements, see if we can find the source element from 182f22ef01cSRoman Divacky // it. In this case, we will end up needing to bitcast the scalars. 183f22ef01cSRoman Divacky if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 184dff0c46cSDimitry Andric if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 185f22ef01cSRoman Divacky if (VT->getNumElements() == VectorWidth) 186875ed548SDimitry Andric if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 187f22ef01cSRoman Divacky return new BitCastInst(Elt, EI.getType()); 188f22ef01cSRoman Divacky } 189284c1978SDimitry Andric 190284c1978SDimitry Andric // If there's a vector PHI feeding a scalar use through this extractelement 191284c1978SDimitry Andric // instruction, try to scalarize the PHI. 192284c1978SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 193284c1978SDimitry Andric Instruction *scalarPHI = scalarizePHI(EI, PN); 194284c1978SDimitry Andric if (scalarPHI) 195f785676fSDimitry Andric return scalarPHI; 196284c1978SDimitry Andric } 197f22ef01cSRoman Divacky } 198f22ef01cSRoman Divacky 199f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 200f22ef01cSRoman Divacky // Push extractelement into predecessor operation if legal and 2017d523365SDimitry Andric // profitable to do so. 202f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 203f22ef01cSRoman Divacky if (I->hasOneUse() && 2047d523365SDimitry Andric cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 205f22ef01cSRoman Divacky Value *newEI0 = 206f22ef01cSRoman Divacky Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 207f22ef01cSRoman Divacky EI.getName()+".lhs"); 208f22ef01cSRoman Divacky Value *newEI1 = 209f22ef01cSRoman Divacky Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 210f22ef01cSRoman Divacky EI.getName()+".rhs"); 2113ca95b02SDimitry Andric return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 2123ca95b02SDimitry Andric newEI0, newEI1, BO); 213f22ef01cSRoman Divacky } 214f22ef01cSRoman Divacky } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 215f22ef01cSRoman Divacky // Extracting the inserted element? 216f22ef01cSRoman Divacky if (IE->getOperand(2) == EI.getOperand(1)) 2173ca95b02SDimitry Andric return replaceInstUsesWith(EI, IE->getOperand(1)); 218f22ef01cSRoman Divacky // If the inserted and extracted elements are constants, they must not 219f22ef01cSRoman Divacky // be the same value, extract from the pre-inserted value instead. 220f22ef01cSRoman Divacky if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 221f22ef01cSRoman Divacky Worklist.AddValue(EI.getOperand(0)); 222f22ef01cSRoman Divacky EI.setOperand(0, IE->getOperand(0)); 223f22ef01cSRoman Divacky return &EI; 224f22ef01cSRoman Divacky } 225f22ef01cSRoman Divacky } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 226f22ef01cSRoman Divacky // If this is extracting an element from a shufflevector, figure out where 227f22ef01cSRoman Divacky // it came from and extract from the appropriate input element instead. 228f22ef01cSRoman Divacky if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 229dff0c46cSDimitry Andric int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 230f22ef01cSRoman Divacky Value *Src; 231f22ef01cSRoman Divacky unsigned LHSWidth = 232dff0c46cSDimitry Andric SVI->getOperand(0)->getType()->getVectorNumElements(); 233f22ef01cSRoman Divacky 2342754fe60SDimitry Andric if (SrcIdx < 0) 2353ca95b02SDimitry Andric return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 2362754fe60SDimitry Andric if (SrcIdx < (int)LHSWidth) 237f22ef01cSRoman Divacky Src = SVI->getOperand(0); 2382754fe60SDimitry Andric else { 239f22ef01cSRoman Divacky SrcIdx -= LHSWidth; 240f22ef01cSRoman Divacky Src = SVI->getOperand(1); 241f22ef01cSRoman Divacky } 2426122f3e6SDimitry Andric Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 243f22ef01cSRoman Divacky return ExtractElementInst::Create(Src, 2442754fe60SDimitry Andric ConstantInt::get(Int32Ty, 245f22ef01cSRoman Divacky SrcIdx, false)); 246f22ef01cSRoman Divacky } 2473b0f4066SDimitry Andric } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 2487d523365SDimitry Andric // Canonicalize extractelement(cast) -> cast(extractelement). 2497d523365SDimitry Andric // Bitcasts can change the number of vector elements, and they cost 2507d523365SDimitry Andric // nothing. 251284c1978SDimitry Andric if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 2523b0f4066SDimitry Andric Value *EE = Builder->CreateExtractElement(CI->getOperand(0), 2533b0f4066SDimitry Andric EI.getIndexOperand()); 254284c1978SDimitry Andric Worklist.AddValue(EE); 2553b0f4066SDimitry Andric return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 256f22ef01cSRoman Divacky } 257f785676fSDimitry Andric } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 258f785676fSDimitry Andric if (SI->hasOneUse()) { 259f785676fSDimitry Andric // TODO: For a select on vectors, it might be useful to do this if it 260f785676fSDimitry Andric // has multiple extractelement uses. For vector select, that seems to 261f785676fSDimitry Andric // fight the vectorizer. 262f785676fSDimitry Andric 263f785676fSDimitry Andric // If we are extracting an element from a vector select or a select on 2647d523365SDimitry Andric // vectors, create a select on the scalars extracted from the vector 2657d523365SDimitry Andric // arguments. 266f785676fSDimitry Andric Value *TrueVal = SI->getTrueValue(); 267f785676fSDimitry Andric Value *FalseVal = SI->getFalseValue(); 268f785676fSDimitry Andric 269f785676fSDimitry Andric Value *Cond = SI->getCondition(); 270f785676fSDimitry Andric if (Cond->getType()->isVectorTy()) { 271f785676fSDimitry Andric Cond = Builder->CreateExtractElement(Cond, 272f785676fSDimitry Andric EI.getIndexOperand(), 273f785676fSDimitry Andric Cond->getName() + ".elt"); 274f785676fSDimitry Andric } 275f785676fSDimitry Andric 276f785676fSDimitry Andric Value *V1Elem 277f785676fSDimitry Andric = Builder->CreateExtractElement(TrueVal, 278f785676fSDimitry Andric EI.getIndexOperand(), 279f785676fSDimitry Andric TrueVal->getName() + ".elt"); 280f785676fSDimitry Andric 281f785676fSDimitry Andric Value *V2Elem 282f785676fSDimitry Andric = Builder->CreateExtractElement(FalseVal, 283f785676fSDimitry Andric EI.getIndexOperand(), 284f785676fSDimitry Andric FalseVal->getName() + ".elt"); 285f785676fSDimitry Andric return SelectInst::Create(Cond, 286f785676fSDimitry Andric V1Elem, 287f785676fSDimitry Andric V2Elem, 288f785676fSDimitry Andric SI->getName() + ".elt"); 289f785676fSDimitry Andric } 2903b0f4066SDimitry Andric } 291f22ef01cSRoman Divacky } 29291bc56edSDimitry Andric return nullptr; 293f22ef01cSRoman Divacky } 294f22ef01cSRoman Divacky 2957d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or 2967d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false. 2977d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 298dff0c46cSDimitry Andric SmallVectorImpl<Constant*> &Mask) { 29991bc56edSDimitry Andric assert(LHS->getType() == RHS->getType() && 300f22ef01cSRoman Divacky "Invalid CollectSingleShuffleElements"); 301f785676fSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 302f22ef01cSRoman Divacky 303f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 304f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 305f22ef01cSRoman Divacky return true; 306f22ef01cSRoman Divacky } 307f22ef01cSRoman Divacky 308f22ef01cSRoman Divacky if (V == LHS) { 309f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 310f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 311f22ef01cSRoman Divacky return true; 312f22ef01cSRoman Divacky } 313f22ef01cSRoman Divacky 314f22ef01cSRoman Divacky if (V == RHS) { 315f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 316f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 317f22ef01cSRoman Divacky i+NumElts)); 318f22ef01cSRoman Divacky return true; 319f22ef01cSRoman Divacky } 320f22ef01cSRoman Divacky 321f22ef01cSRoman Divacky if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 322f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 323f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 324f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 325f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 326f22ef01cSRoman Divacky 327f22ef01cSRoman Divacky if (!isa<ConstantInt>(IdxOp)) 328f22ef01cSRoman Divacky return false; 329f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 330f22ef01cSRoman Divacky 331f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 33291bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 333f22ef01cSRoman Divacky // transitively ok. 3347d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 335f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted undef. 336f22ef01cSRoman Divacky Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 337f22ef01cSRoman Divacky return true; 338f22ef01cSRoman Divacky } 339f22ef01cSRoman Divacky } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 34091bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1))) { 341f22ef01cSRoman Divacky unsigned ExtractedIdx = 342f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 34391bc56edSDimitry Andric unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 344f22ef01cSRoman Divacky 345f22ef01cSRoman Divacky // This must be extracting from either LHS or RHS. 346f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 34791bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 348f22ef01cSRoman Divacky // transitively ok. 3497d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 350f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted value. 351f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS) { 352f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 353f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 354f22ef01cSRoman Divacky ExtractedIdx); 355f22ef01cSRoman Divacky } else { 356f22ef01cSRoman Divacky assert(EI->getOperand(0) == RHS); 357f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 358f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 35991bc56edSDimitry Andric ExtractedIdx + NumLHSElts); 360f22ef01cSRoman Divacky } 361f22ef01cSRoman Divacky return true; 362f22ef01cSRoman Divacky } 363f22ef01cSRoman Divacky } 364f22ef01cSRoman Divacky } 365f22ef01cSRoman Divacky } 366f22ef01cSRoman Divacky } 367f22ef01cSRoman Divacky 368f22ef01cSRoman Divacky return false; 369f22ef01cSRoman Divacky } 370f22ef01cSRoman Divacky 3717d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we 3727d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single 3737d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs. 3747d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt, 3757d523365SDimitry Andric ExtractElementInst *ExtElt, 3767d523365SDimitry Andric InstCombiner &IC) { 3777d523365SDimitry Andric VectorType *InsVecType = InsElt->getType(); 3787d523365SDimitry Andric VectorType *ExtVecType = ExtElt->getVectorOperandType(); 3797d523365SDimitry Andric unsigned NumInsElts = InsVecType->getVectorNumElements(); 3807d523365SDimitry Andric unsigned NumExtElts = ExtVecType->getVectorNumElements(); 3817d523365SDimitry Andric 3827d523365SDimitry Andric // The inserted-to vector must be wider than the extracted-from vector. 3837d523365SDimitry Andric if (InsVecType->getElementType() != ExtVecType->getElementType() || 3847d523365SDimitry Andric NumExtElts >= NumInsElts) 3857d523365SDimitry Andric return; 3867d523365SDimitry Andric 3877d523365SDimitry Andric // Create a shuffle mask to widen the extended-from vector using undefined 3887d523365SDimitry Andric // values. The mask selects all of the values of the original vector followed 3897d523365SDimitry Andric // by as many undefined values as needed to create a vector of the same length 3907d523365SDimitry Andric // as the inserted-to vector. 3917d523365SDimitry Andric SmallVector<Constant *, 16> ExtendMask; 3927d523365SDimitry Andric IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 3937d523365SDimitry Andric for (unsigned i = 0; i < NumExtElts; ++i) 3947d523365SDimitry Andric ExtendMask.push_back(ConstantInt::get(IntType, i)); 3957d523365SDimitry Andric for (unsigned i = NumExtElts; i < NumInsElts; ++i) 3967d523365SDimitry Andric ExtendMask.push_back(UndefValue::get(IntType)); 3977d523365SDimitry Andric 3987d523365SDimitry Andric Value *ExtVecOp = ExtElt->getVectorOperand(); 399a8bcc4d8SDimitry Andric auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 400a8bcc4d8SDimitry Andric BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 401a8bcc4d8SDimitry Andric ? ExtVecOpInst->getParent() 402a8bcc4d8SDimitry Andric : ExtElt->getParent(); 403a8bcc4d8SDimitry Andric 404a8bcc4d8SDimitry Andric // TODO: This restriction matches the basic block check below when creating 405a8bcc4d8SDimitry Andric // new extractelement instructions. If that limitation is removed, this one 406a8bcc4d8SDimitry Andric // could also be removed. But for now, we just bail out to ensure that we 407a8bcc4d8SDimitry Andric // will replace the extractelement instruction that is feeding our 408a8bcc4d8SDimitry Andric // insertelement instruction. This allows the insertelement to then be 409a8bcc4d8SDimitry Andric // replaced by a shufflevector. If the insertelement is not replaced, we can 410a8bcc4d8SDimitry Andric // induce infinite looping because there's an optimization for extractelement 411a8bcc4d8SDimitry Andric // that will delete our widening shuffle. This would trigger another attempt 412a8bcc4d8SDimitry Andric // here to create that shuffle, and we spin forever. 413a8bcc4d8SDimitry Andric if (InsertionBlock != InsElt->getParent()) 414a8bcc4d8SDimitry Andric return; 415a8bcc4d8SDimitry Andric 4167d523365SDimitry Andric auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 4177d523365SDimitry Andric ConstantVector::get(ExtendMask)); 4187d523365SDimitry Andric 4194d0b32cdSDimitry Andric // Insert the new shuffle after the vector operand of the extract is defined 420444ed5c5SDimitry Andric // (as long as it's not a PHI) or at the start of the basic block of the 421444ed5c5SDimitry Andric // extract, so any subsequent extracts in the same basic block can use it. 422444ed5c5SDimitry Andric // TODO: Insert before the earliest ExtractElementInst that is replaced. 423444ed5c5SDimitry Andric if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 4244d0b32cdSDimitry Andric WideVec->insertAfter(ExtVecOpInst); 425444ed5c5SDimitry Andric else 4264d0b32cdSDimitry Andric IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 4274d0b32cdSDimitry Andric 4284d0b32cdSDimitry Andric // Replace extracts from the original narrow vector with extracts from the new 4294d0b32cdSDimitry Andric // wide vector. 4307d523365SDimitry Andric for (User *U : ExtVecOp->users()) { 4314d0b32cdSDimitry Andric ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 432444ed5c5SDimitry Andric if (!OldExt || OldExt->getParent() != WideVec->getParent()) 4334d0b32cdSDimitry Andric continue; 4347d523365SDimitry Andric auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 4357d523365SDimitry Andric NewExt->insertAfter(WideVec); 4363ca95b02SDimitry Andric IC.replaceInstUsesWith(*OldExt, NewExt); 4377d523365SDimitry Andric } 4387d523365SDimitry Andric } 43991bc56edSDimitry Andric 44091bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement, 44191bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or 44291bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the 44391bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask 44491bc56edSDimitry Andric /// parameter as required. 44591bc56edSDimitry Andric /// 44691bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have 44791bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target. 44891bc56edSDimitry Andric typedef std::pair<Value *, Value *> ShuffleOps; 44991bc56edSDimitry Andric 4507d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V, 45191bc56edSDimitry Andric SmallVectorImpl<Constant *> &Mask, 4527d523365SDimitry Andric Value *PermittedRHS, 4537d523365SDimitry Andric InstCombiner &IC) { 45491bc56edSDimitry Andric assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 455f22ef01cSRoman Divacky unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); 456f22ef01cSRoman Divacky 457f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 458f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 45991bc56edSDimitry Andric return std::make_pair( 46091bc56edSDimitry Andric PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 461dff0c46cSDimitry Andric } 462dff0c46cSDimitry Andric 463dff0c46cSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 464f22ef01cSRoman Divacky Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 46591bc56edSDimitry Andric return std::make_pair(V, nullptr); 466dff0c46cSDimitry Andric } 467dff0c46cSDimitry Andric 468dff0c46cSDimitry Andric if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 469f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 470f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 471f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 472f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 473f22ef01cSRoman Divacky 474f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 47591bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 476f22ef01cSRoman Divacky unsigned ExtractedIdx = 477f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 478f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 479f22ef01cSRoman Divacky 480f22ef01cSRoman Divacky // Either the extracted from or inserted into vector must be RHSVec, 481f22ef01cSRoman Divacky // otherwise we'd end up with a shuffle of three inputs. 48291bc56edSDimitry Andric if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 48391bc56edSDimitry Andric Value *RHS = EI->getOperand(0); 4847d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 48591bc56edSDimitry Andric assert(LR.second == nullptr || LR.second == RHS); 48691bc56edSDimitry Andric 48791bc56edSDimitry Andric if (LR.first->getType() != RHS->getType()) { 4887d523365SDimitry Andric // Although we are giving up for now, see if we can create extracts 4897d523365SDimitry Andric // that match the inserts for another round of combining. 4907d523365SDimitry Andric replaceExtractElements(IEI, EI, IC); 4917d523365SDimitry Andric 49291bc56edSDimitry Andric // We tried our best, but we can't find anything compatible with RHS 49391bc56edSDimitry Andric // further up the chain. Return a trivial shuffle. 49491bc56edSDimitry Andric for (unsigned i = 0; i < NumElts; ++i) 49591bc56edSDimitry Andric Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 49691bc56edSDimitry Andric return std::make_pair(V, nullptr); 49791bc56edSDimitry Andric } 49891bc56edSDimitry Andric 49991bc56edSDimitry Andric unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 500f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 501f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 50291bc56edSDimitry Andric NumLHSElts+ExtractedIdx); 50391bc56edSDimitry Andric return std::make_pair(LR.first, RHS); 504f22ef01cSRoman Divacky } 505f22ef01cSRoman Divacky 50691bc56edSDimitry Andric if (VecOp == PermittedRHS) { 50791bc56edSDimitry Andric // We've gone as far as we can: anything on the other side of the 50891bc56edSDimitry Andric // extractelement will already have been converted into a shuffle. 50991bc56edSDimitry Andric unsigned NumLHSElts = 51091bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 51191bc56edSDimitry Andric for (unsigned i = 0; i != NumElts; ++i) 51291bc56edSDimitry Andric Mask.push_back(ConstantInt::get( 51391bc56edSDimitry Andric Type::getInt32Ty(V->getContext()), 51491bc56edSDimitry Andric i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 51591bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 516f22ef01cSRoman Divacky } 517f22ef01cSRoman Divacky 518f22ef01cSRoman Divacky // If this insertelement is a chain that comes from exactly these two 519f22ef01cSRoman Divacky // vectors, return the vector and the effective shuffle. 52091bc56edSDimitry Andric if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 5217d523365SDimitry Andric collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 52291bc56edSDimitry Andric Mask)) 52391bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 524f22ef01cSRoman Divacky } 525f22ef01cSRoman Divacky } 526f22ef01cSRoman Divacky } 527f22ef01cSRoman Divacky 5287d523365SDimitry Andric // Otherwise, we can't do anything fancy. Return an identity vector. 529f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 530f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 53191bc56edSDimitry Andric return std::make_pair(V, nullptr); 53291bc56edSDimitry Andric } 53391bc56edSDimitry Andric 53491bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones: 53591bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 53691bc56edSDimitry Andric /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 53791bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the 53891bc56edSDimitry Andric /// first one, making the first one redundant. 53991bc56edSDimitry Andric /// It should be transformed to: 54091bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 54191bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 54291bc56edSDimitry Andric bool IsRedundant = false; 54391bc56edSDimitry Andric ArrayRef<unsigned int> FirstIndices = I.getIndices(); 54491bc56edSDimitry Andric 54591bc56edSDimitry Andric // If there is a chain of insertvalue instructions (each of them except the 54691bc56edSDimitry Andric // last one has only one use and it's another insertvalue insn from this 54791bc56edSDimitry Andric // chain), check if any of the 'children' uses the same indices as the first 54891bc56edSDimitry Andric // instruction. In this case, the first one is redundant. 54991bc56edSDimitry Andric Value *V = &I; 55091bc56edSDimitry Andric unsigned Depth = 0; 55191bc56edSDimitry Andric while (V->hasOneUse() && Depth < 10) { 55291bc56edSDimitry Andric User *U = V->user_back(); 55391bc56edSDimitry Andric auto UserInsInst = dyn_cast<InsertValueInst>(U); 55491bc56edSDimitry Andric if (!UserInsInst || U->getOperand(0) != V) 55591bc56edSDimitry Andric break; 55691bc56edSDimitry Andric if (UserInsInst->getIndices() == FirstIndices) { 55791bc56edSDimitry Andric IsRedundant = true; 55891bc56edSDimitry Andric break; 55991bc56edSDimitry Andric } 56091bc56edSDimitry Andric V = UserInsInst; 56191bc56edSDimitry Andric Depth++; 56291bc56edSDimitry Andric } 56391bc56edSDimitry Andric 56491bc56edSDimitry Andric if (IsRedundant) 5653ca95b02SDimitry Andric return replaceInstUsesWith(I, I.getOperand(0)); 56691bc56edSDimitry Andric return nullptr; 567f22ef01cSRoman Divacky } 568f22ef01cSRoman Divacky 569f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 570f22ef01cSRoman Divacky Value *VecOp = IE.getOperand(0); 571f22ef01cSRoman Divacky Value *ScalarOp = IE.getOperand(1); 572f22ef01cSRoman Divacky Value *IdxOp = IE.getOperand(2); 573f22ef01cSRoman Divacky 574f22ef01cSRoman Divacky // Inserting an undef or into an undefined place, remove this. 575f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 5763ca95b02SDimitry Andric replaceInstUsesWith(IE, VecOp); 577f22ef01cSRoman Divacky 578f22ef01cSRoman Divacky // If the inserted element was extracted from some other vector, and if the 579f22ef01cSRoman Divacky // indexes are constant, try to turn this into a shufflevector operation. 580f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 58191bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 58291bc56edSDimitry Andric unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 58391bc56edSDimitry Andric unsigned NumExtractVectorElts = 58491bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 585f22ef01cSRoman Divacky unsigned ExtractedIdx = 586f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 587f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 588f22ef01cSRoman Divacky 58991bc56edSDimitry Andric if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 5903ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 591f22ef01cSRoman Divacky 59291bc56edSDimitry Andric if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 5933ca95b02SDimitry Andric return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 594f22ef01cSRoman Divacky 595f22ef01cSRoman Divacky // If we are extracting a value from a vector, then inserting it right 596f22ef01cSRoman Divacky // back into the same place, just use the input vector. 597f22ef01cSRoman Divacky if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 5983ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 599f22ef01cSRoman Divacky 600f22ef01cSRoman Divacky // If this insertelement isn't used by some other insertelement, turn it 601f22ef01cSRoman Divacky // (and any insertelements it points to), into one big shuffle. 60291bc56edSDimitry Andric if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 603dff0c46cSDimitry Andric SmallVector<Constant*, 16> Mask; 6047d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 60591bc56edSDimitry Andric 60691bc56edSDimitry Andric // The proposed shuffle may be trivial, in which case we shouldn't 60791bc56edSDimitry Andric // perform the combine. 60891bc56edSDimitry Andric if (LR.first != &IE && LR.second != &IE) { 609f22ef01cSRoman Divacky // We now have a shuffle of LHS, RHS, Mask. 61091bc56edSDimitry Andric if (LR.second == nullptr) 61191bc56edSDimitry Andric LR.second = UndefValue::get(LR.first->getType()); 61291bc56edSDimitry Andric return new ShuffleVectorInst(LR.first, LR.second, 61391bc56edSDimitry Andric ConstantVector::get(Mask)); 61491bc56edSDimitry Andric } 615f22ef01cSRoman Divacky } 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky } 618f22ef01cSRoman Divacky 619f22ef01cSRoman Divacky unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements(); 620f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 621f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 6222754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 6232754fe60SDimitry Andric if (V != &IE) 6243ca95b02SDimitry Andric return replaceInstUsesWith(IE, V); 625f22ef01cSRoman Divacky return &IE; 6262754fe60SDimitry Andric } 627f22ef01cSRoman Divacky 62891bc56edSDimitry Andric return nullptr; 629f22ef01cSRoman Divacky } 630f22ef01cSRoman Divacky 631f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector 632f785676fSDimitry Andric /// elements were shuffled in a different order. 633f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 634f785676fSDimitry Andric unsigned Depth = 5) { 635f785676fSDimitry Andric // We can always reorder the elements of a constant. 636f785676fSDimitry Andric if (isa<Constant>(V)) 637f785676fSDimitry Andric return true; 638f785676fSDimitry Andric 639f785676fSDimitry Andric // We won't reorder vector arguments. No IPO here. 640f785676fSDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 641f785676fSDimitry Andric if (!I) return false; 642f785676fSDimitry Andric 643f785676fSDimitry Andric // Two users may expect different orders of the elements. Don't try it. 644f785676fSDimitry Andric if (!I->hasOneUse()) 645f785676fSDimitry Andric return false; 646f785676fSDimitry Andric 647f785676fSDimitry Andric if (Depth == 0) return false; 648f785676fSDimitry Andric 649f785676fSDimitry Andric switch (I->getOpcode()) { 650f785676fSDimitry Andric case Instruction::Add: 651f785676fSDimitry Andric case Instruction::FAdd: 652f785676fSDimitry Andric case Instruction::Sub: 653f785676fSDimitry Andric case Instruction::FSub: 654f785676fSDimitry Andric case Instruction::Mul: 655f785676fSDimitry Andric case Instruction::FMul: 656f785676fSDimitry Andric case Instruction::UDiv: 657f785676fSDimitry Andric case Instruction::SDiv: 658f785676fSDimitry Andric case Instruction::FDiv: 659f785676fSDimitry Andric case Instruction::URem: 660f785676fSDimitry Andric case Instruction::SRem: 661f785676fSDimitry Andric case Instruction::FRem: 662f785676fSDimitry Andric case Instruction::Shl: 663f785676fSDimitry Andric case Instruction::LShr: 664f785676fSDimitry Andric case Instruction::AShr: 665f785676fSDimitry Andric case Instruction::And: 666f785676fSDimitry Andric case Instruction::Or: 667f785676fSDimitry Andric case Instruction::Xor: 668f785676fSDimitry Andric case Instruction::ICmp: 669f785676fSDimitry Andric case Instruction::FCmp: 670f785676fSDimitry Andric case Instruction::Trunc: 671f785676fSDimitry Andric case Instruction::ZExt: 672f785676fSDimitry Andric case Instruction::SExt: 673f785676fSDimitry Andric case Instruction::FPToUI: 674f785676fSDimitry Andric case Instruction::FPToSI: 675f785676fSDimitry Andric case Instruction::UIToFP: 676f785676fSDimitry Andric case Instruction::SIToFP: 677f785676fSDimitry Andric case Instruction::FPTrunc: 678f785676fSDimitry Andric case Instruction::FPExt: 679f785676fSDimitry Andric case Instruction::GetElementPtr: { 6807d523365SDimitry Andric for (Value *Operand : I->operands()) { 6817d523365SDimitry Andric if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 682f785676fSDimitry Andric return false; 683f785676fSDimitry Andric } 684f785676fSDimitry Andric return true; 685f785676fSDimitry Andric } 686f785676fSDimitry Andric case Instruction::InsertElement: { 687f785676fSDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 688f785676fSDimitry Andric if (!CI) return false; 689f785676fSDimitry Andric int ElementNumber = CI->getLimitedValue(); 690f785676fSDimitry Andric 691f785676fSDimitry Andric // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 692f785676fSDimitry Andric // can't put an element into multiple indices. 693f785676fSDimitry Andric bool SeenOnce = false; 694f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 695f785676fSDimitry Andric if (Mask[i] == ElementNumber) { 696f785676fSDimitry Andric if (SeenOnce) 697f785676fSDimitry Andric return false; 698f785676fSDimitry Andric SeenOnce = true; 699f785676fSDimitry Andric } 700f785676fSDimitry Andric } 701f785676fSDimitry Andric return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 702f785676fSDimitry Andric } 703f785676fSDimitry Andric } 704f785676fSDimitry Andric return false; 705f785676fSDimitry Andric } 706f785676fSDimitry Andric 707f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given. 708f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct. 7097d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 710f785676fSDimitry Andric // We don't want to use the IRBuilder here because we want the replacement 711f785676fSDimitry Andric // instructions to appear next to 'I', not the builder's insertion point. 712f785676fSDimitry Andric switch (I->getOpcode()) { 713f785676fSDimitry Andric case Instruction::Add: 714f785676fSDimitry Andric case Instruction::FAdd: 715f785676fSDimitry Andric case Instruction::Sub: 716f785676fSDimitry Andric case Instruction::FSub: 717f785676fSDimitry Andric case Instruction::Mul: 718f785676fSDimitry Andric case Instruction::FMul: 719f785676fSDimitry Andric case Instruction::UDiv: 720f785676fSDimitry Andric case Instruction::SDiv: 721f785676fSDimitry Andric case Instruction::FDiv: 722f785676fSDimitry Andric case Instruction::URem: 723f785676fSDimitry Andric case Instruction::SRem: 724f785676fSDimitry Andric case Instruction::FRem: 725f785676fSDimitry Andric case Instruction::Shl: 726f785676fSDimitry Andric case Instruction::LShr: 727f785676fSDimitry Andric case Instruction::AShr: 728f785676fSDimitry Andric case Instruction::And: 729f785676fSDimitry Andric case Instruction::Or: 730f785676fSDimitry Andric case Instruction::Xor: { 731f785676fSDimitry Andric BinaryOperator *BO = cast<BinaryOperator>(I); 732f785676fSDimitry Andric assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 733f785676fSDimitry Andric BinaryOperator *New = 734f785676fSDimitry Andric BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 735f785676fSDimitry Andric NewOps[0], NewOps[1], "", BO); 736f785676fSDimitry Andric if (isa<OverflowingBinaryOperator>(BO)) { 737f785676fSDimitry Andric New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 738f785676fSDimitry Andric New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 739f785676fSDimitry Andric } 740f785676fSDimitry Andric if (isa<PossiblyExactOperator>(BO)) { 741f785676fSDimitry Andric New->setIsExact(BO->isExact()); 742f785676fSDimitry Andric } 74391bc56edSDimitry Andric if (isa<FPMathOperator>(BO)) 74491bc56edSDimitry Andric New->copyFastMathFlags(I); 745f785676fSDimitry Andric return New; 746f785676fSDimitry Andric } 747f785676fSDimitry Andric case Instruction::ICmp: 748f785676fSDimitry Andric assert(NewOps.size() == 2 && "icmp with #ops != 2"); 749f785676fSDimitry Andric return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 750f785676fSDimitry Andric NewOps[0], NewOps[1]); 751f785676fSDimitry Andric case Instruction::FCmp: 752f785676fSDimitry Andric assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 753f785676fSDimitry Andric return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 754f785676fSDimitry Andric NewOps[0], NewOps[1]); 755f785676fSDimitry Andric case Instruction::Trunc: 756f785676fSDimitry Andric case Instruction::ZExt: 757f785676fSDimitry Andric case Instruction::SExt: 758f785676fSDimitry Andric case Instruction::FPToUI: 759f785676fSDimitry Andric case Instruction::FPToSI: 760f785676fSDimitry Andric case Instruction::UIToFP: 761f785676fSDimitry Andric case Instruction::SIToFP: 762f785676fSDimitry Andric case Instruction::FPTrunc: 763f785676fSDimitry Andric case Instruction::FPExt: { 764f785676fSDimitry Andric // It's possible that the mask has a different number of elements from 765f785676fSDimitry Andric // the original cast. We recompute the destination type to match the mask. 766f785676fSDimitry Andric Type *DestTy = 767f785676fSDimitry Andric VectorType::get(I->getType()->getScalarType(), 768f785676fSDimitry Andric NewOps[0]->getType()->getVectorNumElements()); 769f785676fSDimitry Andric assert(NewOps.size() == 1 && "cast with #ops != 1"); 770f785676fSDimitry Andric return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 771f785676fSDimitry Andric "", I); 772f785676fSDimitry Andric } 773f785676fSDimitry Andric case Instruction::GetElementPtr: { 774f785676fSDimitry Andric Value *Ptr = NewOps[0]; 775f785676fSDimitry Andric ArrayRef<Value*> Idx = NewOps.slice(1); 776ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create( 777ff0cc061SDimitry Andric cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 778f785676fSDimitry Andric GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 779f785676fSDimitry Andric return GEP; 780f785676fSDimitry Andric } 781f785676fSDimitry Andric } 782f785676fSDimitry Andric llvm_unreachable("failed to rebuild vector instructions"); 783f785676fSDimitry Andric } 784f785676fSDimitry Andric 785f785676fSDimitry Andric Value * 786f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 787f785676fSDimitry Andric // Mask.size() does not need to be equal to the number of vector elements. 788f785676fSDimitry Andric 789f785676fSDimitry Andric assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 790f785676fSDimitry Andric if (isa<UndefValue>(V)) { 791f785676fSDimitry Andric return UndefValue::get(VectorType::get(V->getType()->getScalarType(), 792f785676fSDimitry Andric Mask.size())); 793f785676fSDimitry Andric } 794f785676fSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 795f785676fSDimitry Andric return ConstantAggregateZero::get( 796f785676fSDimitry Andric VectorType::get(V->getType()->getScalarType(), 797f785676fSDimitry Andric Mask.size())); 798f785676fSDimitry Andric } 799f785676fSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 800f785676fSDimitry Andric SmallVector<Constant *, 16> MaskValues; 801f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 802f785676fSDimitry Andric if (Mask[i] == -1) 803f785676fSDimitry Andric MaskValues.push_back(UndefValue::get(Builder->getInt32Ty())); 804f785676fSDimitry Andric else 805f785676fSDimitry Andric MaskValues.push_back(Builder->getInt32(Mask[i])); 806f785676fSDimitry Andric } 807f785676fSDimitry Andric return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 808f785676fSDimitry Andric ConstantVector::get(MaskValues)); 809f785676fSDimitry Andric } 810f785676fSDimitry Andric 811f785676fSDimitry Andric Instruction *I = cast<Instruction>(V); 812f785676fSDimitry Andric switch (I->getOpcode()) { 813f785676fSDimitry Andric case Instruction::Add: 814f785676fSDimitry Andric case Instruction::FAdd: 815f785676fSDimitry Andric case Instruction::Sub: 816f785676fSDimitry Andric case Instruction::FSub: 817f785676fSDimitry Andric case Instruction::Mul: 818f785676fSDimitry Andric case Instruction::FMul: 819f785676fSDimitry Andric case Instruction::UDiv: 820f785676fSDimitry Andric case Instruction::SDiv: 821f785676fSDimitry Andric case Instruction::FDiv: 822f785676fSDimitry Andric case Instruction::URem: 823f785676fSDimitry Andric case Instruction::SRem: 824f785676fSDimitry Andric case Instruction::FRem: 825f785676fSDimitry Andric case Instruction::Shl: 826f785676fSDimitry Andric case Instruction::LShr: 827f785676fSDimitry Andric case Instruction::AShr: 828f785676fSDimitry Andric case Instruction::And: 829f785676fSDimitry Andric case Instruction::Or: 830f785676fSDimitry Andric case Instruction::Xor: 831f785676fSDimitry Andric case Instruction::ICmp: 832f785676fSDimitry Andric case Instruction::FCmp: 833f785676fSDimitry Andric case Instruction::Trunc: 834f785676fSDimitry Andric case Instruction::ZExt: 835f785676fSDimitry Andric case Instruction::SExt: 836f785676fSDimitry Andric case Instruction::FPToUI: 837f785676fSDimitry Andric case Instruction::FPToSI: 838f785676fSDimitry Andric case Instruction::UIToFP: 839f785676fSDimitry Andric case Instruction::SIToFP: 840f785676fSDimitry Andric case Instruction::FPTrunc: 841f785676fSDimitry Andric case Instruction::FPExt: 842f785676fSDimitry Andric case Instruction::Select: 843f785676fSDimitry Andric case Instruction::GetElementPtr: { 844f785676fSDimitry Andric SmallVector<Value*, 8> NewOps; 845f785676fSDimitry Andric bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 846f785676fSDimitry Andric for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 847f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 848f785676fSDimitry Andric NewOps.push_back(V); 849f785676fSDimitry Andric NeedsRebuild |= (V != I->getOperand(i)); 850f785676fSDimitry Andric } 851f785676fSDimitry Andric if (NeedsRebuild) { 8527d523365SDimitry Andric return buildNew(I, NewOps); 853f785676fSDimitry Andric } 854f785676fSDimitry Andric return I; 855f785676fSDimitry Andric } 856f785676fSDimitry Andric case Instruction::InsertElement: { 857f785676fSDimitry Andric int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 858f785676fSDimitry Andric 859f785676fSDimitry Andric // The insertelement was inserting at Element. Figure out which element 860f785676fSDimitry Andric // that becomes after shuffling. The answer is guaranteed to be unique 861f785676fSDimitry Andric // by CanEvaluateShuffled. 862f785676fSDimitry Andric bool Found = false; 863f785676fSDimitry Andric int Index = 0; 864f785676fSDimitry Andric for (int e = Mask.size(); Index != e; ++Index) { 865f785676fSDimitry Andric if (Mask[Index] == Element) { 866f785676fSDimitry Andric Found = true; 867f785676fSDimitry Andric break; 868f785676fSDimitry Andric } 869f785676fSDimitry Andric } 870f785676fSDimitry Andric 87191bc56edSDimitry Andric // If element is not in Mask, no need to handle the operand 1 (element to 87291bc56edSDimitry Andric // be inserted). Just evaluate values in operand 0 according to Mask. 873f785676fSDimitry Andric if (!Found) 87491bc56edSDimitry Andric return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 875f785676fSDimitry Andric 876f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 877f785676fSDimitry Andric return InsertElementInst::Create(V, I->getOperand(1), 878f785676fSDimitry Andric Builder->getInt32(Index), "", I); 879f785676fSDimitry Andric } 880f785676fSDimitry Andric } 881f785676fSDimitry Andric llvm_unreachable("failed to reorder elements of vector instruction!"); 882f785676fSDimitry Andric } 883f22ef01cSRoman Divacky 8847d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 88591bc56edSDimitry Andric bool &isLHSID, bool &isRHSID) { 88691bc56edSDimitry Andric isLHSID = isRHSID = true; 88791bc56edSDimitry Andric 88891bc56edSDimitry Andric for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 88991bc56edSDimitry Andric if (Mask[i] < 0) continue; // Ignore undef values. 89091bc56edSDimitry Andric // Is this an identity shuffle of the LHS value? 89191bc56edSDimitry Andric isLHSID &= (Mask[i] == (int)i); 89291bc56edSDimitry Andric 89391bc56edSDimitry Andric // Is this an identity shuffle of the RHS value? 89491bc56edSDimitry Andric isRHSID &= (Mask[i]-e == i); 89591bc56edSDimitry Andric } 89691bc56edSDimitry Andric } 89791bc56edSDimitry Andric 898ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from 899ff0cc061SDimitry Andric // LHS, for example: 900ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 901ff0cc061SDimitry Andric // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 902ff0cc061SDimitry Andric // Shuffles to: |EE|FF|GG|HH| 903ff0cc061SDimitry Andric // +--+--+--+--+ 904ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 905ff0cc061SDimitry Andric SmallVector<int, 16> &Mask) { 906ff0cc061SDimitry Andric unsigned LHSElems = 907ff0cc061SDimitry Andric cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements(); 908ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 909ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 910ff0cc061SDimitry Andric unsigned EndIdx = Mask.back(); 911ff0cc061SDimitry Andric if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 912ff0cc061SDimitry Andric return false; 913ff0cc061SDimitry Andric for (unsigned I = 0; I != MaskElems; ++I) 914ff0cc061SDimitry Andric if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 915ff0cc061SDimitry Andric return false; 916ff0cc061SDimitry Andric return true; 917ff0cc061SDimitry Andric } 918ff0cc061SDimitry Andric 919f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 920f22ef01cSRoman Divacky Value *LHS = SVI.getOperand(0); 921f22ef01cSRoman Divacky Value *RHS = SVI.getOperand(1); 922dff0c46cSDimitry Andric SmallVector<int, 16> Mask = SVI.getShuffleMask(); 923ff0cc061SDimitry Andric Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 924f22ef01cSRoman Divacky 925f22ef01cSRoman Divacky bool MadeChange = false; 926f22ef01cSRoman Divacky 927f22ef01cSRoman Divacky // Undefined shuffle mask -> undefined value. 928f22ef01cSRoman Divacky if (isa<UndefValue>(SVI.getOperand(2))) 9293ca95b02SDimitry Andric return replaceInstUsesWith(SVI, UndefValue::get(SVI.getType())); 930f22ef01cSRoman Divacky 931f22ef01cSRoman Divacky unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements(); 932f22ef01cSRoman Divacky 933f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 934f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 9352754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 9362754fe60SDimitry Andric if (V != &SVI) 9373ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 938f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 939f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 940f22ef01cSRoman Divacky MadeChange = true; 941f22ef01cSRoman Divacky } 942f22ef01cSRoman Divacky 943dff0c46cSDimitry Andric unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements(); 944dff0c46cSDimitry Andric 945f22ef01cSRoman Divacky // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 946f22ef01cSRoman Divacky // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 947f22ef01cSRoman Divacky if (LHS == RHS || isa<UndefValue>(LHS)) { 948f22ef01cSRoman Divacky if (isa<UndefValue>(LHS) && LHS == RHS) { 949f22ef01cSRoman Divacky // shuffle(undef,undef,mask) -> undef. 950f785676fSDimitry Andric Value *Result = (VWidth == LHSWidth) 951dff0c46cSDimitry Andric ? LHS : UndefValue::get(SVI.getType()); 9523ca95b02SDimitry Andric return replaceInstUsesWith(SVI, Result); 953f22ef01cSRoman Divacky } 954f22ef01cSRoman Divacky 955f22ef01cSRoman Divacky // Remap any references to RHS to use LHS. 956dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 957dff0c46cSDimitry Andric for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 958dff0c46cSDimitry Andric if (Mask[i] < 0) { 959ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 960dff0c46cSDimitry Andric continue; 961dff0c46cSDimitry Andric } 962dff0c46cSDimitry Andric 9632754fe60SDimitry Andric if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 9642754fe60SDimitry Andric (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 9652754fe60SDimitry Andric Mask[i] = -1; // Turn into undef. 966ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 967f22ef01cSRoman Divacky } else { 968f22ef01cSRoman Divacky Mask[i] = Mask[i] % e; // Force to LHS. 969ff0cc061SDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 970f22ef01cSRoman Divacky } 971f22ef01cSRoman Divacky } 972f22ef01cSRoman Divacky SVI.setOperand(0, SVI.getOperand(1)); 973f22ef01cSRoman Divacky SVI.setOperand(1, UndefValue::get(RHS->getType())); 974f22ef01cSRoman Divacky SVI.setOperand(2, ConstantVector::get(Elts)); 975f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 976f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 977f22ef01cSRoman Divacky MadeChange = true; 978f22ef01cSRoman Divacky } 979f22ef01cSRoman Divacky 980dff0c46cSDimitry Andric if (VWidth == LHSWidth) { 981f22ef01cSRoman Divacky // Analyze the shuffle, are the LHS or RHS and identity shuffles? 98291bc56edSDimitry Andric bool isLHSID, isRHSID; 9837d523365SDimitry Andric recognizeIdentityMask(Mask, isLHSID, isRHSID); 984f22ef01cSRoman Divacky 985f22ef01cSRoman Divacky // Eliminate identity shuffles. 9863ca95b02SDimitry Andric if (isLHSID) return replaceInstUsesWith(SVI, LHS); 9873ca95b02SDimitry Andric if (isRHSID) return replaceInstUsesWith(SVI, RHS); 988dff0c46cSDimitry Andric } 989f22ef01cSRoman Divacky 990f785676fSDimitry Andric if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 991f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 9923ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 993f785676fSDimitry Andric } 994f785676fSDimitry Andric 995ff0cc061SDimitry Andric // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 996ff0cc061SDimitry Andric // a non-vector type. We can instead bitcast the original vector followed by 997ff0cc061SDimitry Andric // an extract of the desired element: 998ff0cc061SDimitry Andric // 999ff0cc061SDimitry Andric // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1000ff0cc061SDimitry Andric // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1001ff0cc061SDimitry Andric // %1 = bitcast <4 x i8> %sroa to i32 1002ff0cc061SDimitry Andric // Becomes: 1003ff0cc061SDimitry Andric // %bc = bitcast <16 x i8> %in to <4 x i32> 1004ff0cc061SDimitry Andric // %ext = extractelement <4 x i32> %bc, i32 0 1005ff0cc061SDimitry Andric // 1006ff0cc061SDimitry Andric // If the shuffle is extracting a contiguous range of values from the input 1007ff0cc061SDimitry Andric // vector then each use which is a bitcast of the extracted size can be 1008ff0cc061SDimitry Andric // replaced. This will work if the vector types are compatible, and the begin 1009ff0cc061SDimitry Andric // index is aligned to a value in the casted vector type. If the begin index 1010ff0cc061SDimitry Andric // isn't aligned then we can shuffle the original vector (keeping the same 1011ff0cc061SDimitry Andric // vector type) before extracting. 1012ff0cc061SDimitry Andric // 1013ff0cc061SDimitry Andric // This code will bail out if the target type is fundamentally incompatible 1014ff0cc061SDimitry Andric // with vectors of the source type. 1015ff0cc061SDimitry Andric // 1016ff0cc061SDimitry Andric // Example of <16 x i8>, target type i32: 1017ff0cc061SDimitry Andric // Index range [4,8): v-----------v Will work. 1018ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1019ff0cc061SDimitry Andric // <16 x i8>: | | | | | | | | | | | | | | | | | 1020ff0cc061SDimitry Andric // <4 x i32>: | | | | | 1021ff0cc061SDimitry Andric // +-----------+-----------+-----------+-----------+ 1022ff0cc061SDimitry Andric // Index range [6,10): ^-----------^ Needs an extra shuffle. 1023ff0cc061SDimitry Andric // Target type i40: ^--------------^ Won't work, bail. 1024ff0cc061SDimitry Andric if (isShuffleExtractingFromLHS(SVI, Mask)) { 1025ff0cc061SDimitry Andric Value *V = LHS; 1026ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1027ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 1028ff0cc061SDimitry Andric VectorType *SrcTy = cast<VectorType>(V->getType()); 1029ff0cc061SDimitry Andric unsigned VecBitWidth = SrcTy->getBitWidth(); 1030ff0cc061SDimitry Andric unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1031ff0cc061SDimitry Andric assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1032ff0cc061SDimitry Andric unsigned SrcNumElems = SrcTy->getNumElements(); 1033ff0cc061SDimitry Andric SmallVector<BitCastInst *, 8> BCs; 1034ff0cc061SDimitry Andric DenseMap<Type *, Value *> NewBCs; 1035ff0cc061SDimitry Andric for (User *U : SVI.users()) 1036ff0cc061SDimitry Andric if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1037ff0cc061SDimitry Andric if (!BC->use_empty()) 1038ff0cc061SDimitry Andric // Only visit bitcasts that weren't previously handled. 1039ff0cc061SDimitry Andric BCs.push_back(BC); 1040ff0cc061SDimitry Andric for (BitCastInst *BC : BCs) { 1041ff0cc061SDimitry Andric Type *TgtTy = BC->getDestTy(); 1042ff0cc061SDimitry Andric unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1043ff0cc061SDimitry Andric if (!TgtElemBitWidth) 1044ff0cc061SDimitry Andric continue; 1045ff0cc061SDimitry Andric unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1046ff0cc061SDimitry Andric bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1047ff0cc061SDimitry Andric bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1048ff0cc061SDimitry Andric if (!VecBitWidthsEqual) 1049ff0cc061SDimitry Andric continue; 1050ff0cc061SDimitry Andric if (!VectorType::isValidElementType(TgtTy)) 1051ff0cc061SDimitry Andric continue; 1052ff0cc061SDimitry Andric VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1053ff0cc061SDimitry Andric if (!BegIsAligned) { 1054ff0cc061SDimitry Andric // Shuffle the input so [0,NumElements) contains the output, and 1055ff0cc061SDimitry Andric // [NumElems,SrcNumElems) is undef. 1056ff0cc061SDimitry Andric SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1057ff0cc061SDimitry Andric UndefValue::get(Int32Ty)); 1058ff0cc061SDimitry Andric for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1059ff0cc061SDimitry Andric ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1060ff0cc061SDimitry Andric V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()), 1061ff0cc061SDimitry Andric ConstantVector::get(ShuffleMask), 1062ff0cc061SDimitry Andric SVI.getName() + ".extract"); 1063ff0cc061SDimitry Andric BegIdx = 0; 1064ff0cc061SDimitry Andric } 1065ff0cc061SDimitry Andric unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1066ff0cc061SDimitry Andric assert(SrcElemsPerTgtElem); 1067ff0cc061SDimitry Andric BegIdx /= SrcElemsPerTgtElem; 1068ff0cc061SDimitry Andric bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1069ff0cc061SDimitry Andric auto *NewBC = 1070ff0cc061SDimitry Andric BCAlreadyExists 1071ff0cc061SDimitry Andric ? NewBCs[CastSrcTy] 1072ff0cc061SDimitry Andric : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1073ff0cc061SDimitry Andric if (!BCAlreadyExists) 1074ff0cc061SDimitry Andric NewBCs[CastSrcTy] = NewBC; 1075ff0cc061SDimitry Andric auto *Ext = Builder->CreateExtractElement( 1076ff0cc061SDimitry Andric NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1077ff0cc061SDimitry Andric // The shufflevector isn't being replaced: the bitcast that used it 1078ff0cc061SDimitry Andric // is. InstCombine will visit the newly-created instructions. 10793ca95b02SDimitry Andric replaceInstUsesWith(*BC, Ext); 1080ff0cc061SDimitry Andric MadeChange = true; 1081ff0cc061SDimitry Andric } 1082ff0cc061SDimitry Andric } 1083ff0cc061SDimitry Andric 1084f22ef01cSRoman Divacky // If the LHS is a shufflevector itself, see if we can combine it with this 1085dff0c46cSDimitry Andric // one without producing an unusual shuffle. 1086dff0c46cSDimitry Andric // Cases that might be simplified: 1087dff0c46cSDimitry Andric // 1. 1088dff0c46cSDimitry Andric // x1=shuffle(v1,v2,mask1) 1089dff0c46cSDimitry Andric // x=shuffle(x1,undef,mask) 1090dff0c46cSDimitry Andric // ==> 1091dff0c46cSDimitry Andric // x=shuffle(v1,undef,newMask) 1092dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1093dff0c46cSDimitry Andric // 2. 1094dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1095dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1096dff0c46cSDimitry Andric // where v1.size() == mask1.size() 1097dff0c46cSDimitry Andric // ==> 1098dff0c46cSDimitry Andric // x=shuffle(v1,x2,newMask) 1099dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1100dff0c46cSDimitry Andric // 3. 1101dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1102dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1103dff0c46cSDimitry Andric // where v2.size() == mask2.size() 1104dff0c46cSDimitry Andric // ==> 1105dff0c46cSDimitry Andric // x=shuffle(x1,v2,newMask) 1106dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1107dff0c46cSDimitry Andric // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1108dff0c46cSDimitry Andric // 4. 1109dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1110dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1111dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1112dff0c46cSDimitry Andric // where v1.size() == v2.size() 1113dff0c46cSDimitry Andric // ==> 1114dff0c46cSDimitry Andric // x=shuffle(v1,v2,newMask) 1115dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1116dff0c46cSDimitry Andric // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1117dff0c46cSDimitry Andric // 1118dff0c46cSDimitry Andric // Here we are really conservative: 1119f22ef01cSRoman Divacky // we are absolutely afraid of producing a shuffle mask not in the input 1120f22ef01cSRoman Divacky // program, because the code gen may not be smart enough to turn a merged 1121f22ef01cSRoman Divacky // shuffle into two specific shuffles: it may produce worse code. As such, 11222754fe60SDimitry Andric // we only merge two shuffles if the result is either a splat or one of the 1123dff0c46cSDimitry Andric // input shuffle masks. In this case, merging the shuffles just removes 11242754fe60SDimitry Andric // one instruction, which we know is safe. This is good for things like 1125dff0c46cSDimitry Andric // turning: (splat(splat)) -> splat, or 1126dff0c46cSDimitry Andric // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1127dff0c46cSDimitry Andric ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1128dff0c46cSDimitry Andric ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1129dff0c46cSDimitry Andric if (LHSShuffle) 1130dff0c46cSDimitry Andric if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 113191bc56edSDimitry Andric LHSShuffle = nullptr; 1132dff0c46cSDimitry Andric if (RHSShuffle) 1133dff0c46cSDimitry Andric if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 113491bc56edSDimitry Andric RHSShuffle = nullptr; 1135dff0c46cSDimitry Andric if (!LHSShuffle && !RHSShuffle) 113691bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1137dff0c46cSDimitry Andric 113891bc56edSDimitry Andric Value* LHSOp0 = nullptr; 113991bc56edSDimitry Andric Value* LHSOp1 = nullptr; 114091bc56edSDimitry Andric Value* RHSOp0 = nullptr; 1141dff0c46cSDimitry Andric unsigned LHSOp0Width = 0; 1142dff0c46cSDimitry Andric unsigned RHSOp0Width = 0; 1143dff0c46cSDimitry Andric if (LHSShuffle) { 1144dff0c46cSDimitry Andric LHSOp0 = LHSShuffle->getOperand(0); 1145dff0c46cSDimitry Andric LHSOp1 = LHSShuffle->getOperand(1); 1146dff0c46cSDimitry Andric LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements(); 1147dff0c46cSDimitry Andric } 1148dff0c46cSDimitry Andric if (RHSShuffle) { 1149dff0c46cSDimitry Andric RHSOp0 = RHSShuffle->getOperand(0); 1150dff0c46cSDimitry Andric RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements(); 1151dff0c46cSDimitry Andric } 1152dff0c46cSDimitry Andric Value* newLHS = LHS; 1153dff0c46cSDimitry Andric Value* newRHS = RHS; 1154dff0c46cSDimitry Andric if (LHSShuffle) { 1155dff0c46cSDimitry Andric // case 1 1156f22ef01cSRoman Divacky if (isa<UndefValue>(RHS)) { 1157dff0c46cSDimitry Andric newLHS = LHSOp0; 1158dff0c46cSDimitry Andric newRHS = LHSOp1; 1159dff0c46cSDimitry Andric } 1160dff0c46cSDimitry Andric // case 2 or 4 1161dff0c46cSDimitry Andric else if (LHSOp0Width == LHSWidth) { 1162dff0c46cSDimitry Andric newLHS = LHSOp0; 1163dff0c46cSDimitry Andric } 1164dff0c46cSDimitry Andric } 1165dff0c46cSDimitry Andric // case 3 or 4 1166dff0c46cSDimitry Andric if (RHSShuffle && RHSOp0Width == LHSWidth) { 1167dff0c46cSDimitry Andric newRHS = RHSOp0; 1168dff0c46cSDimitry Andric } 1169dff0c46cSDimitry Andric // case 4 1170dff0c46cSDimitry Andric if (LHSOp0 == RHSOp0) { 1171dff0c46cSDimitry Andric newLHS = LHSOp0; 117291bc56edSDimitry Andric newRHS = nullptr; 1173dff0c46cSDimitry Andric } 1174f22ef01cSRoman Divacky 1175dff0c46cSDimitry Andric if (newLHS == LHS && newRHS == RHS) 117691bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1177dff0c46cSDimitry Andric 1178dff0c46cSDimitry Andric SmallVector<int, 16> LHSMask; 1179dff0c46cSDimitry Andric SmallVector<int, 16> RHSMask; 1180dff0c46cSDimitry Andric if (newLHS != LHS) 1181dff0c46cSDimitry Andric LHSMask = LHSShuffle->getShuffleMask(); 1182dff0c46cSDimitry Andric if (RHSShuffle && newRHS != RHS) 1183dff0c46cSDimitry Andric RHSMask = RHSShuffle->getShuffleMask(); 1184dff0c46cSDimitry Andric 1185dff0c46cSDimitry Andric unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1186dff0c46cSDimitry Andric SmallVector<int, 16> newMask; 11872754fe60SDimitry Andric bool isSplat = true; 1188dff0c46cSDimitry Andric int SplatElt = -1; 1189dff0c46cSDimitry Andric // Create a new mask for the new ShuffleVectorInst so that the new 1190dff0c46cSDimitry Andric // ShuffleVectorInst is equivalent to the original one. 1191dff0c46cSDimitry Andric for (unsigned i = 0; i < VWidth; ++i) { 1192dff0c46cSDimitry Andric int eltMask; 1193139f7f9bSDimitry Andric if (Mask[i] < 0) { 1194dff0c46cSDimitry Andric // This element is an undef value. 1195dff0c46cSDimitry Andric eltMask = -1; 1196dff0c46cSDimitry Andric } else if (Mask[i] < (int)LHSWidth) { 1197dff0c46cSDimitry Andric // This element is from left hand side vector operand. 1198dff0c46cSDimitry Andric // 1199dff0c46cSDimitry Andric // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1200dff0c46cSDimitry Andric // new mask value for the element. 1201dff0c46cSDimitry Andric if (newLHS != LHS) { 1202dff0c46cSDimitry Andric eltMask = LHSMask[Mask[i]]; 1203dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1204dff0c46cSDimitry Andric // with a -1 mask value. 1205dff0c46cSDimitry Andric if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1206dff0c46cSDimitry Andric eltMask = -1; 1207139f7f9bSDimitry Andric } else 1208dff0c46cSDimitry Andric eltMask = Mask[i]; 1209dff0c46cSDimitry Andric } else { 1210dff0c46cSDimitry Andric // This element is from right hand side vector operand 1211dff0c46cSDimitry Andric // 1212dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1213dff0c46cSDimitry Andric // with a -1 mask value. (case 1) 1214dff0c46cSDimitry Andric if (isa<UndefValue>(RHS)) 1215dff0c46cSDimitry Andric eltMask = -1; 1216dff0c46cSDimitry Andric // If RHS is going to be replaced (case 3 or 4), calculate the 1217dff0c46cSDimitry Andric // new mask value for the element. 1218dff0c46cSDimitry Andric else if (newRHS != RHS) { 1219dff0c46cSDimitry Andric eltMask = RHSMask[Mask[i]-LHSWidth]; 1220dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1221dff0c46cSDimitry Andric // with a -1 mask value. 1222dff0c46cSDimitry Andric if (eltMask >= (int)RHSOp0Width) { 1223dff0c46cSDimitry Andric assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1224dff0c46cSDimitry Andric && "should have been check above"); 1225dff0c46cSDimitry Andric eltMask = -1; 1226dff0c46cSDimitry Andric } 1227139f7f9bSDimitry Andric } else 1228dff0c46cSDimitry Andric eltMask = Mask[i]-LHSWidth; 1229dff0c46cSDimitry Andric 1230dff0c46cSDimitry Andric // If LHS's width is changed, shift the mask value accordingly. 1231dff0c46cSDimitry Andric // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any 12323861d79fSDimitry Andric // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 12333861d79fSDimitry Andric // If newRHS == newLHS, we want to remap any references from newRHS to 12343861d79fSDimitry Andric // newLHS so that we can properly identify splats that may occur due to 123591bc56edSDimitry Andric // obfuscation across the two vectors. 123691bc56edSDimitry Andric if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1237dff0c46cSDimitry Andric eltMask += newLHSWidth; 12382754fe60SDimitry Andric } 1239f22ef01cSRoman Divacky 1240dff0c46cSDimitry Andric // Check if this could still be a splat. 1241dff0c46cSDimitry Andric if (eltMask >= 0) { 1242dff0c46cSDimitry Andric if (SplatElt >= 0 && SplatElt != eltMask) 1243dff0c46cSDimitry Andric isSplat = false; 1244dff0c46cSDimitry Andric SplatElt = eltMask; 1245dff0c46cSDimitry Andric } 1246dff0c46cSDimitry Andric 1247dff0c46cSDimitry Andric newMask.push_back(eltMask); 1248dff0c46cSDimitry Andric } 1249dff0c46cSDimitry Andric 1250dff0c46cSDimitry Andric // If the result mask is equal to one of the original shuffle masks, 1251dff0c46cSDimitry Andric // or is a splat, do the replacement. 1252dff0c46cSDimitry Andric if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1253dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1254dff0c46cSDimitry Andric for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1255dff0c46cSDimitry Andric if (newMask[i] < 0) { 12562754fe60SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1257f22ef01cSRoman Divacky } else { 1258dff0c46cSDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1259f22ef01cSRoman Divacky } 1260f22ef01cSRoman Divacky } 126191bc56edSDimitry Andric if (!newRHS) 1262dff0c46cSDimitry Andric newRHS = UndefValue::get(newLHS->getType()); 1263dff0c46cSDimitry Andric return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1264f22ef01cSRoman Divacky } 1265f22ef01cSRoman Divacky 126691bc56edSDimitry Andric // If the result mask is an identity, replace uses of this instruction with 126791bc56edSDimitry Andric // corresponding argument. 126891bc56edSDimitry Andric bool isLHSID, isRHSID; 12697d523365SDimitry Andric recognizeIdentityMask(newMask, isLHSID, isRHSID); 12703ca95b02SDimitry Andric if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 12713ca95b02SDimitry Andric if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 127291bc56edSDimitry Andric 127391bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1274f22ef01cSRoman Divacky } 1275