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" 162cab237bSDimitry Andric #include "llvm/ADT/APInt.h" 172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h" 18ff0cc061SDimitry Andric #include "llvm/ADT/DenseMap.h" 192cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h" 202cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h" 21875ed548SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 22875ed548SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 232cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h" 242cab237bSDimitry Andric #include "llvm/IR/Constant.h" 252cab237bSDimitry Andric #include "llvm/IR/Constants.h" 262cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 272cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h" 282cab237bSDimitry Andric #include "llvm/IR/Instruction.h" 292cab237bSDimitry Andric #include "llvm/IR/Instructions.h" 302cab237bSDimitry Andric #include "llvm/IR/Operator.h" 3191bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h" 322cab237bSDimitry Andric #include "llvm/IR/Type.h" 332cab237bSDimitry Andric #include "llvm/IR/User.h" 342cab237bSDimitry Andric #include "llvm/IR/Value.h" 352cab237bSDimitry Andric #include "llvm/Support/Casting.h" 362cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h" 372cab237bSDimitry Andric #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 382cab237bSDimitry Andric #include <cassert> 392cab237bSDimitry Andric #include <cstdint> 402cab237bSDimitry Andric #include <iterator> 412cab237bSDimitry Andric #include <utility> 422cab237bSDimitry Andric 43f22ef01cSRoman Divacky using namespace llvm; 44139f7f9bSDimitry Andric using namespace PatternMatch; 45f22ef01cSRoman Divacky 4691bc56edSDimitry Andric #define DEBUG_TYPE "instcombine" 4791bc56edSDimitry Andric 487d523365SDimitry Andric /// Return true if the value is cheaper to scalarize than it is to leave as a 497d523365SDimitry Andric /// vector operation. isConstant indicates whether we're extracting one known 507d523365SDimitry Andric /// element. If false we're extracting a variable index. 517d523365SDimitry Andric static bool cheapToScalarize(Value *V, bool isConstant) { 52dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 53f22ef01cSRoman Divacky if (isConstant) return true; 54dff0c46cSDimitry Andric 55dff0c46cSDimitry Andric // If all elts are the same, we can extract it and use any of the values. 5685d60e68SDimitry Andric if (Constant *Op0 = C->getAggregateElement(0U)) { 5785d60e68SDimitry Andric for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; 5885d60e68SDimitry Andric ++i) 59dff0c46cSDimitry Andric if (C->getAggregateElement(i) != Op0) 60f22ef01cSRoman Divacky return false; 61f22ef01cSRoman Divacky return true; 62f22ef01cSRoman Divacky } 6385d60e68SDimitry Andric } 64f22ef01cSRoman Divacky Instruction *I = dyn_cast<Instruction>(V); 65f22ef01cSRoman Divacky if (!I) return false; 66f22ef01cSRoman Divacky 67f22ef01cSRoman Divacky // Insert element gets simplified to the inserted element or is deleted if 68f22ef01cSRoman Divacky // this is constant idx extract element and its a constant idx insertelt. 69f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::InsertElement && isConstant && 70f22ef01cSRoman Divacky isa<ConstantInt>(I->getOperand(2))) 71f22ef01cSRoman Divacky return true; 72f22ef01cSRoman Divacky if (I->getOpcode() == Instruction::Load && I->hasOneUse()) 73f22ef01cSRoman Divacky return true; 74f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) 75f22ef01cSRoman Divacky if (BO->hasOneUse() && 767d523365SDimitry Andric (cheapToScalarize(BO->getOperand(0), isConstant) || 777d523365SDimitry Andric cheapToScalarize(BO->getOperand(1), isConstant))) 78f22ef01cSRoman Divacky return true; 79f22ef01cSRoman Divacky if (CmpInst *CI = dyn_cast<CmpInst>(I)) 80f22ef01cSRoman Divacky if (CI->hasOneUse() && 817d523365SDimitry Andric (cheapToScalarize(CI->getOperand(0), isConstant) || 827d523365SDimitry Andric cheapToScalarize(CI->getOperand(1), isConstant))) 83f22ef01cSRoman Divacky return true; 84f22ef01cSRoman Divacky 85f22ef01cSRoman Divacky return false; 86f22ef01cSRoman Divacky } 87f22ef01cSRoman Divacky 883ca95b02SDimitry Andric // If we have a PHI node with a vector type that is only used to feed 89f785676fSDimitry Andric // itself and be an operand of extractelement at a constant location, 90f785676fSDimitry Andric // try to replace the PHI of the vector type with a PHI of a scalar type. 91284c1978SDimitry Andric Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { 923ca95b02SDimitry Andric SmallVector<Instruction *, 2> Extracts; 933ca95b02SDimitry Andric // The users we want the PHI to have are: 943ca95b02SDimitry Andric // 1) The EI ExtractElement (we already know this) 953ca95b02SDimitry Andric // 2) Possibly more ExtractElements with the same index. 963ca95b02SDimitry Andric // 3) Another operand, which will feed back into the PHI. 973ca95b02SDimitry Andric Instruction *PHIUser = nullptr; 983ca95b02SDimitry Andric for (auto U : PN->users()) { 993ca95b02SDimitry Andric if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 1003ca95b02SDimitry Andric if (EI.getIndexOperand() == EU->getIndexOperand()) 1013ca95b02SDimitry Andric Extracts.push_back(EU); 1023ca95b02SDimitry Andric else 10391bc56edSDimitry Andric return nullptr; 1043ca95b02SDimitry Andric } else if (!PHIUser) { 1053ca95b02SDimitry Andric PHIUser = cast<Instruction>(U); 1063ca95b02SDimitry Andric } else { 1073ca95b02SDimitry Andric return nullptr; 1083ca95b02SDimitry Andric } 1093ca95b02SDimitry Andric } 110284c1978SDimitry Andric 1113ca95b02SDimitry Andric if (!PHIUser) 1123ca95b02SDimitry Andric return nullptr; 113284c1978SDimitry Andric 114284c1978SDimitry Andric // Verify that this PHI user has one use, which is the PHI itself, 115284c1978SDimitry Andric // and that it is a binary operation which is cheap to scalarize. 1162cab237bSDimitry Andric // otherwise return nullptr. 11791bc56edSDimitry Andric if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 1187d523365SDimitry Andric !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) 11991bc56edSDimitry Andric return nullptr; 120284c1978SDimitry Andric 121284c1978SDimitry Andric // Create a scalar PHI node that will replace the vector PHI node 122284c1978SDimitry Andric // just before the current PHI node. 123f785676fSDimitry Andric PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 124f785676fSDimitry Andric PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 125284c1978SDimitry Andric // Scalarize each PHI operand. 126284c1978SDimitry Andric for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 127284c1978SDimitry Andric Value *PHIInVal = PN->getIncomingValue(i); 128284c1978SDimitry Andric BasicBlock *inBB = PN->getIncomingBlock(i); 129284c1978SDimitry Andric Value *Elt = EI.getIndexOperand(); 130284c1978SDimitry Andric // If the operand is the PHI induction variable: 131284c1978SDimitry Andric if (PHIInVal == PHIUser) { 132284c1978SDimitry Andric // Scalarize the binary operation. Its first operand is the 13391bc56edSDimitry Andric // scalar PHI, and the second operand is extracted from the other 134284c1978SDimitry Andric // vector operand. 135284c1978SDimitry Andric BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 136284c1978SDimitry Andric unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 137f785676fSDimitry Andric Value *Op = InsertNewInstWith( 138f785676fSDimitry Andric ExtractElementInst::Create(B0->getOperand(opId), Elt, 139f785676fSDimitry Andric B0->getOperand(opId)->getName() + ".Elt"), 140284c1978SDimitry Andric *B0); 141f785676fSDimitry Andric Value *newPHIUser = InsertNewInstWith( 1423ca95b02SDimitry Andric BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 1433ca95b02SDimitry Andric scalarPHI, Op, B0), *B0); 144284c1978SDimitry Andric scalarPHI->addIncoming(newPHIUser, inBB); 145284c1978SDimitry Andric } else { 146284c1978SDimitry Andric // Scalarize PHI input: 147f785676fSDimitry Andric Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 148284c1978SDimitry Andric // Insert the new instruction into the predecessor basic block. 149284c1978SDimitry Andric Instruction *pos = dyn_cast<Instruction>(PHIInVal); 150284c1978SDimitry Andric BasicBlock::iterator InsertPos; 151284c1978SDimitry Andric if (pos && !isa<PHINode>(pos)) { 1527d523365SDimitry Andric InsertPos = ++pos->getIterator(); 153284c1978SDimitry Andric } else { 154284c1978SDimitry Andric InsertPos = inBB->getFirstInsertionPt(); 155284c1978SDimitry Andric } 156284c1978SDimitry Andric 157284c1978SDimitry Andric InsertNewInstWith(newEI, *InsertPos); 158284c1978SDimitry Andric 159284c1978SDimitry Andric scalarPHI->addIncoming(newEI, inBB); 160284c1978SDimitry Andric } 161284c1978SDimitry Andric } 1623ca95b02SDimitry Andric 1633ca95b02SDimitry Andric for (auto E : Extracts) 1643ca95b02SDimitry Andric replaceInstUsesWith(*E, scalarPHI); 1653ca95b02SDimitry Andric 1663ca95b02SDimitry Andric return &EI; 167284c1978SDimitry Andric } 168284c1978SDimitry Andric 169f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { 170f37b6182SDimitry Andric if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(), 171db17bf38SDimitry Andric EI.getIndexOperand(), 172db17bf38SDimitry Andric SQ.getWithInstruction(&EI))) 1733ca95b02SDimitry Andric return replaceInstUsesWith(EI, V); 174875ed548SDimitry Andric 175f22ef01cSRoman Divacky // If vector val is constant with all elements the same, replace EI with 176dff0c46cSDimitry Andric // that element. We handle a known element # below. 177dff0c46cSDimitry Andric if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 1787d523365SDimitry Andric if (cheapToScalarize(C, false)) 1793ca95b02SDimitry Andric return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 180f22ef01cSRoman Divacky 181f22ef01cSRoman Divacky // If extracting a specified index from the vector, see if we can recursively 182f22ef01cSRoman Divacky // find a previously computed scalar that was inserted into the vector. 183f22ef01cSRoman Divacky if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 184f22ef01cSRoman Divacky unsigned IndexVal = IdxC->getZExtValue(); 185f22ef01cSRoman Divacky unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 186f22ef01cSRoman Divacky 187875ed548SDimitry Andric // InstSimplify handles cases where the index is invalid. 188875ed548SDimitry Andric assert(IndexVal < VectorWidth); 189f22ef01cSRoman Divacky 190f22ef01cSRoman Divacky // This instruction only demands the single element from the input vector. 191f22ef01cSRoman Divacky // If the input vector has a single use, simplify it based on this use 192f22ef01cSRoman Divacky // property. 193f22ef01cSRoman Divacky if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 194f22ef01cSRoman Divacky APInt UndefElts(VectorWidth, 0); 195f22ef01cSRoman Divacky APInt DemandedMask(VectorWidth, 0); 1962754fe60SDimitry Andric DemandedMask.setBit(IndexVal); 197ff0cc061SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 198ff0cc061SDimitry Andric UndefElts)) { 199f22ef01cSRoman Divacky EI.setOperand(0, V); 200f22ef01cSRoman Divacky return &EI; 201f22ef01cSRoman Divacky } 202f22ef01cSRoman Divacky } 203f22ef01cSRoman Divacky 2047d523365SDimitry Andric // If this extractelement is directly using a bitcast from a vector of 205f22ef01cSRoman Divacky // the same number of elements, see if we can find the source element from 206f22ef01cSRoman Divacky // it. In this case, we will end up needing to bitcast the scalars. 207f22ef01cSRoman Divacky if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 208dff0c46cSDimitry Andric if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 209f22ef01cSRoman Divacky if (VT->getNumElements() == VectorWidth) 210875ed548SDimitry Andric if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 211f22ef01cSRoman Divacky return new BitCastInst(Elt, EI.getType()); 212f22ef01cSRoman Divacky } 213284c1978SDimitry Andric 214284c1978SDimitry Andric // If there's a vector PHI feeding a scalar use through this extractelement 215284c1978SDimitry Andric // instruction, try to scalarize the PHI. 216284c1978SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 217284c1978SDimitry Andric Instruction *scalarPHI = scalarizePHI(EI, PN); 218284c1978SDimitry Andric if (scalarPHI) 219f785676fSDimitry Andric return scalarPHI; 220284c1978SDimitry Andric } 221f22ef01cSRoman Divacky } 222f22ef01cSRoman Divacky 223f22ef01cSRoman Divacky if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 224f22ef01cSRoman Divacky // Push extractelement into predecessor operation if legal and 2257d523365SDimitry Andric // profitable to do so. 226f22ef01cSRoman Divacky if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 227f22ef01cSRoman Divacky if (I->hasOneUse() && 2287d523365SDimitry Andric cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 229f22ef01cSRoman Divacky Value *newEI0 = 230c4394386SDimitry Andric Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 231f22ef01cSRoman Divacky EI.getName()+".lhs"); 232f22ef01cSRoman Divacky Value *newEI1 = 233c4394386SDimitry Andric Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 234f22ef01cSRoman Divacky EI.getName()+".rhs"); 2353ca95b02SDimitry Andric return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 2363ca95b02SDimitry Andric newEI0, newEI1, BO); 237f22ef01cSRoman Divacky } 238f22ef01cSRoman Divacky } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 239f22ef01cSRoman Divacky // Extracting the inserted element? 240f22ef01cSRoman Divacky if (IE->getOperand(2) == EI.getOperand(1)) 2413ca95b02SDimitry Andric return replaceInstUsesWith(EI, IE->getOperand(1)); 242f22ef01cSRoman Divacky // If the inserted and extracted elements are constants, they must not 243f22ef01cSRoman Divacky // be the same value, extract from the pre-inserted value instead. 244f22ef01cSRoman Divacky if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 245f22ef01cSRoman Divacky Worklist.AddValue(EI.getOperand(0)); 246f22ef01cSRoman Divacky EI.setOperand(0, IE->getOperand(0)); 247f22ef01cSRoman Divacky return &EI; 248f22ef01cSRoman Divacky } 249f22ef01cSRoman Divacky } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 250f22ef01cSRoman Divacky // If this is extracting an element from a shufflevector, figure out where 251f22ef01cSRoman Divacky // it came from and extract from the appropriate input element instead. 252f22ef01cSRoman Divacky if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 253dff0c46cSDimitry Andric int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 254f22ef01cSRoman Divacky Value *Src; 255f22ef01cSRoman Divacky unsigned LHSWidth = 256dff0c46cSDimitry Andric SVI->getOperand(0)->getType()->getVectorNumElements(); 257f22ef01cSRoman Divacky 2582754fe60SDimitry Andric if (SrcIdx < 0) 2593ca95b02SDimitry Andric return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 2602754fe60SDimitry Andric if (SrcIdx < (int)LHSWidth) 261f22ef01cSRoman Divacky Src = SVI->getOperand(0); 2622754fe60SDimitry Andric else { 263f22ef01cSRoman Divacky SrcIdx -= LHSWidth; 264f22ef01cSRoman Divacky Src = SVI->getOperand(1); 265f22ef01cSRoman Divacky } 2666122f3e6SDimitry Andric Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 267f22ef01cSRoman Divacky return ExtractElementInst::Create(Src, 2682754fe60SDimitry Andric ConstantInt::get(Int32Ty, 269f22ef01cSRoman Divacky SrcIdx, false)); 270f22ef01cSRoman Divacky } 2713b0f4066SDimitry Andric } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 2727d523365SDimitry Andric // Canonicalize extractelement(cast) -> cast(extractelement). 2737d523365SDimitry Andric // Bitcasts can change the number of vector elements, and they cost 2747d523365SDimitry Andric // nothing. 275284c1978SDimitry Andric if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 276c4394386SDimitry Andric Value *EE = Builder.CreateExtractElement(CI->getOperand(0), 2773b0f4066SDimitry Andric EI.getIndexOperand()); 278284c1978SDimitry Andric Worklist.AddValue(EE); 2793b0f4066SDimitry Andric return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 280f22ef01cSRoman Divacky } 2813b0f4066SDimitry Andric } 282f22ef01cSRoman Divacky } 28391bc56edSDimitry Andric return nullptr; 284f22ef01cSRoman Divacky } 285f22ef01cSRoman Divacky 2867d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or 2877d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false. 2887d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 289dff0c46cSDimitry Andric SmallVectorImpl<Constant*> &Mask) { 29091bc56edSDimitry Andric assert(LHS->getType() == RHS->getType() && 291f22ef01cSRoman Divacky "Invalid CollectSingleShuffleElements"); 292f785676fSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 293f22ef01cSRoman Divacky 294f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 295f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 296f22ef01cSRoman Divacky return true; 297f22ef01cSRoman Divacky } 298f22ef01cSRoman Divacky 299f22ef01cSRoman Divacky if (V == LHS) { 300f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 301f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 302f22ef01cSRoman Divacky return true; 303f22ef01cSRoman Divacky } 304f22ef01cSRoman Divacky 305f22ef01cSRoman Divacky if (V == RHS) { 306f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 307f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 308f22ef01cSRoman Divacky i+NumElts)); 309f22ef01cSRoman Divacky return true; 310f22ef01cSRoman Divacky } 311f22ef01cSRoman Divacky 312f22ef01cSRoman Divacky if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 313f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 314f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 315f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 316f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 317f22ef01cSRoman Divacky 318f22ef01cSRoman Divacky if (!isa<ConstantInt>(IdxOp)) 319f22ef01cSRoman Divacky return false; 320f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 321f22ef01cSRoman Divacky 322f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 32391bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 324f22ef01cSRoman Divacky // transitively ok. 3257d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 326f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted undef. 327f22ef01cSRoman Divacky Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 328f22ef01cSRoman Divacky return true; 329f22ef01cSRoman Divacky } 330f22ef01cSRoman Divacky } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 33191bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1))) { 332f22ef01cSRoman Divacky unsigned ExtractedIdx = 333f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 33491bc56edSDimitry Andric unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 335f22ef01cSRoman Divacky 336f22ef01cSRoman Divacky // This must be extracting from either LHS or RHS. 337f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 33891bc56edSDimitry Andric // We can handle this if the vector we are inserting into is 339f22ef01cSRoman Divacky // transitively ok. 3407d523365SDimitry Andric if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 341f22ef01cSRoman Divacky // If so, update the mask to reflect the inserted value. 342f22ef01cSRoman Divacky if (EI->getOperand(0) == LHS) { 343f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 344f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 345f22ef01cSRoman Divacky ExtractedIdx); 346f22ef01cSRoman Divacky } else { 347f22ef01cSRoman Divacky assert(EI->getOperand(0) == RHS); 348f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 349f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 35091bc56edSDimitry Andric ExtractedIdx + NumLHSElts); 351f22ef01cSRoman Divacky } 352f22ef01cSRoman Divacky return true; 353f22ef01cSRoman Divacky } 354f22ef01cSRoman Divacky } 355f22ef01cSRoman Divacky } 356f22ef01cSRoman Divacky } 357f22ef01cSRoman Divacky } 358f22ef01cSRoman Divacky 359f22ef01cSRoman Divacky return false; 360f22ef01cSRoman Divacky } 361f22ef01cSRoman Divacky 3627d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we 3637d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single 3647d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs. 3657d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt, 3667d523365SDimitry Andric ExtractElementInst *ExtElt, 3677d523365SDimitry Andric InstCombiner &IC) { 3687d523365SDimitry Andric VectorType *InsVecType = InsElt->getType(); 3697d523365SDimitry Andric VectorType *ExtVecType = ExtElt->getVectorOperandType(); 3707d523365SDimitry Andric unsigned NumInsElts = InsVecType->getVectorNumElements(); 3717d523365SDimitry Andric unsigned NumExtElts = ExtVecType->getVectorNumElements(); 3727d523365SDimitry Andric 3737d523365SDimitry Andric // The inserted-to vector must be wider than the extracted-from vector. 3747d523365SDimitry Andric if (InsVecType->getElementType() != ExtVecType->getElementType() || 3757d523365SDimitry Andric NumExtElts >= NumInsElts) 3767d523365SDimitry Andric return; 3777d523365SDimitry Andric 3787d523365SDimitry Andric // Create a shuffle mask to widen the extended-from vector using undefined 3797d523365SDimitry Andric // values. The mask selects all of the values of the original vector followed 3807d523365SDimitry Andric // by as many undefined values as needed to create a vector of the same length 3817d523365SDimitry Andric // as the inserted-to vector. 3827d523365SDimitry Andric SmallVector<Constant *, 16> ExtendMask; 3837d523365SDimitry Andric IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 3847d523365SDimitry Andric for (unsigned i = 0; i < NumExtElts; ++i) 3857d523365SDimitry Andric ExtendMask.push_back(ConstantInt::get(IntType, i)); 3867d523365SDimitry Andric for (unsigned i = NumExtElts; i < NumInsElts; ++i) 3877d523365SDimitry Andric ExtendMask.push_back(UndefValue::get(IntType)); 3887d523365SDimitry Andric 3897d523365SDimitry Andric Value *ExtVecOp = ExtElt->getVectorOperand(); 390a8bcc4d8SDimitry Andric auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 391a8bcc4d8SDimitry Andric BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 392a8bcc4d8SDimitry Andric ? ExtVecOpInst->getParent() 393a8bcc4d8SDimitry Andric : ExtElt->getParent(); 394a8bcc4d8SDimitry Andric 395a8bcc4d8SDimitry Andric // TODO: This restriction matches the basic block check below when creating 396a8bcc4d8SDimitry Andric // new extractelement instructions. If that limitation is removed, this one 397a8bcc4d8SDimitry Andric // could also be removed. But for now, we just bail out to ensure that we 398a8bcc4d8SDimitry Andric // will replace the extractelement instruction that is feeding our 399a8bcc4d8SDimitry Andric // insertelement instruction. This allows the insertelement to then be 400a8bcc4d8SDimitry Andric // replaced by a shufflevector. If the insertelement is not replaced, we can 401a8bcc4d8SDimitry Andric // induce infinite looping because there's an optimization for extractelement 402a8bcc4d8SDimitry Andric // that will delete our widening shuffle. This would trigger another attempt 403a8bcc4d8SDimitry Andric // here to create that shuffle, and we spin forever. 404a8bcc4d8SDimitry Andric if (InsertionBlock != InsElt->getParent()) 405a8bcc4d8SDimitry Andric return; 406a8bcc4d8SDimitry Andric 407d88c1a5aSDimitry Andric // TODO: This restriction matches the check in visitInsertElementInst() and 408d88c1a5aSDimitry Andric // prevents an infinite loop caused by not turning the extract/insert pair 409d88c1a5aSDimitry Andric // into a shuffle. We really should not need either check, but we're lacking 410d88c1a5aSDimitry Andric // folds for shufflevectors because we're afraid to generate shuffle masks 411d88c1a5aSDimitry Andric // that the backend can't handle. 412d88c1a5aSDimitry Andric if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 413d88c1a5aSDimitry Andric return; 414d88c1a5aSDimitry Andric 4157d523365SDimitry Andric auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 4167d523365SDimitry Andric ConstantVector::get(ExtendMask)); 4177d523365SDimitry Andric 4184d0b32cdSDimitry Andric // Insert the new shuffle after the vector operand of the extract is defined 419444ed5c5SDimitry Andric // (as long as it's not a PHI) or at the start of the basic block of the 420444ed5c5SDimitry Andric // extract, so any subsequent extracts in the same basic block can use it. 421444ed5c5SDimitry Andric // TODO: Insert before the earliest ExtractElementInst that is replaced. 422444ed5c5SDimitry Andric if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 4234d0b32cdSDimitry Andric WideVec->insertAfter(ExtVecOpInst); 424444ed5c5SDimitry Andric else 4254d0b32cdSDimitry Andric IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 4264d0b32cdSDimitry Andric 4274d0b32cdSDimitry Andric // Replace extracts from the original narrow vector with extracts from the new 4284d0b32cdSDimitry Andric // wide vector. 4297d523365SDimitry Andric for (User *U : ExtVecOp->users()) { 4304d0b32cdSDimitry Andric ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 431444ed5c5SDimitry Andric if (!OldExt || OldExt->getParent() != WideVec->getParent()) 4324d0b32cdSDimitry Andric continue; 4337d523365SDimitry Andric auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 434db17bf38SDimitry Andric NewExt->insertAfter(OldExt); 4353ca95b02SDimitry Andric IC.replaceInstUsesWith(*OldExt, NewExt); 4367d523365SDimitry Andric } 4377d523365SDimitry Andric } 43891bc56edSDimitry Andric 43991bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement, 44091bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or 44191bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the 44291bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask 44391bc56edSDimitry Andric /// parameter as required. 44491bc56edSDimitry Andric /// 44591bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have 44691bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target. 4472cab237bSDimitry Andric using ShuffleOps = std::pair<Value *, Value *>; 44891bc56edSDimitry Andric 4497d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V, 45091bc56edSDimitry Andric SmallVectorImpl<Constant *> &Mask, 4517d523365SDimitry Andric Value *PermittedRHS, 4527d523365SDimitry Andric InstCombiner &IC) { 45391bc56edSDimitry Andric assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 454d88c1a5aSDimitry Andric unsigned NumElts = V->getType()->getVectorNumElements(); 455f22ef01cSRoman Divacky 456f22ef01cSRoman Divacky if (isa<UndefValue>(V)) { 457f22ef01cSRoman Divacky Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 45891bc56edSDimitry Andric return std::make_pair( 45991bc56edSDimitry Andric PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 460dff0c46cSDimitry Andric } 461dff0c46cSDimitry Andric 462dff0c46cSDimitry Andric if (isa<ConstantAggregateZero>(V)) { 463f22ef01cSRoman Divacky Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 46491bc56edSDimitry Andric return std::make_pair(V, nullptr); 465dff0c46cSDimitry Andric } 466dff0c46cSDimitry Andric 467dff0c46cSDimitry Andric if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 468f22ef01cSRoman Divacky // If this is an insert of an extract from some other vector, include it. 469f22ef01cSRoman Divacky Value *VecOp = IEI->getOperand(0); 470f22ef01cSRoman Divacky Value *ScalarOp = IEI->getOperand(1); 471f22ef01cSRoman Divacky Value *IdxOp = IEI->getOperand(2); 472f22ef01cSRoman Divacky 473f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 47491bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 475f22ef01cSRoman Divacky unsigned ExtractedIdx = 476f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 477f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 478f22ef01cSRoman Divacky 479f22ef01cSRoman Divacky // Either the extracted from or inserted into vector must be RHSVec, 480f22ef01cSRoman Divacky // otherwise we'd end up with a shuffle of three inputs. 48191bc56edSDimitry Andric if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 48291bc56edSDimitry Andric Value *RHS = EI->getOperand(0); 4837d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 48491bc56edSDimitry Andric assert(LR.second == nullptr || LR.second == RHS); 48591bc56edSDimitry Andric 48691bc56edSDimitry Andric if (LR.first->getType() != RHS->getType()) { 4877d523365SDimitry Andric // Although we are giving up for now, see if we can create extracts 4887d523365SDimitry Andric // that match the inserts for another round of combining. 4897d523365SDimitry Andric replaceExtractElements(IEI, EI, IC); 4907d523365SDimitry Andric 49191bc56edSDimitry Andric // We tried our best, but we can't find anything compatible with RHS 49291bc56edSDimitry Andric // further up the chain. Return a trivial shuffle. 49391bc56edSDimitry Andric for (unsigned i = 0; i < NumElts; ++i) 49491bc56edSDimitry Andric Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 49591bc56edSDimitry Andric return std::make_pair(V, nullptr); 49691bc56edSDimitry Andric } 49791bc56edSDimitry Andric 49891bc56edSDimitry Andric unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 499f22ef01cSRoman Divacky Mask[InsertedIdx % NumElts] = 500f22ef01cSRoman Divacky ConstantInt::get(Type::getInt32Ty(V->getContext()), 50191bc56edSDimitry Andric NumLHSElts+ExtractedIdx); 50291bc56edSDimitry Andric return std::make_pair(LR.first, RHS); 503f22ef01cSRoman Divacky } 504f22ef01cSRoman Divacky 50591bc56edSDimitry Andric if (VecOp == PermittedRHS) { 50691bc56edSDimitry Andric // We've gone as far as we can: anything on the other side of the 50791bc56edSDimitry Andric // extractelement will already have been converted into a shuffle. 50891bc56edSDimitry Andric unsigned NumLHSElts = 50991bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 51091bc56edSDimitry Andric for (unsigned i = 0; i != NumElts; ++i) 51191bc56edSDimitry Andric Mask.push_back(ConstantInt::get( 51291bc56edSDimitry Andric Type::getInt32Ty(V->getContext()), 51391bc56edSDimitry Andric i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 51491bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 515f22ef01cSRoman Divacky } 516f22ef01cSRoman Divacky 517f22ef01cSRoman Divacky // If this insertelement is a chain that comes from exactly these two 518f22ef01cSRoman Divacky // vectors, return the vector and the effective shuffle. 51991bc56edSDimitry Andric if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 5207d523365SDimitry Andric collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 52191bc56edSDimitry Andric Mask)) 52291bc56edSDimitry Andric return std::make_pair(EI->getOperand(0), PermittedRHS); 523f22ef01cSRoman Divacky } 524f22ef01cSRoman Divacky } 525f22ef01cSRoman Divacky } 526f22ef01cSRoman Divacky 5277d523365SDimitry Andric // Otherwise, we can't do anything fancy. Return an identity vector. 528f22ef01cSRoman Divacky for (unsigned i = 0; i != NumElts; ++i) 529f22ef01cSRoman Divacky Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 53091bc56edSDimitry Andric return std::make_pair(V, nullptr); 53191bc56edSDimitry Andric } 53291bc56edSDimitry Andric 53391bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones: 53491bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 53591bc56edSDimitry Andric /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 53691bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the 53791bc56edSDimitry Andric /// first one, making the first one redundant. 53891bc56edSDimitry Andric /// It should be transformed to: 53991bc56edSDimitry Andric /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 54091bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 54191bc56edSDimitry Andric bool IsRedundant = false; 54291bc56edSDimitry Andric ArrayRef<unsigned int> FirstIndices = I.getIndices(); 54391bc56edSDimitry Andric 54491bc56edSDimitry Andric // If there is a chain of insertvalue instructions (each of them except the 54591bc56edSDimitry Andric // last one has only one use and it's another insertvalue insn from this 54691bc56edSDimitry Andric // chain), check if any of the 'children' uses the same indices as the first 54791bc56edSDimitry Andric // instruction. In this case, the first one is redundant. 54891bc56edSDimitry Andric Value *V = &I; 54991bc56edSDimitry Andric unsigned Depth = 0; 55091bc56edSDimitry Andric while (V->hasOneUse() && Depth < 10) { 55191bc56edSDimitry Andric User *U = V->user_back(); 55291bc56edSDimitry Andric auto UserInsInst = dyn_cast<InsertValueInst>(U); 55391bc56edSDimitry Andric if (!UserInsInst || U->getOperand(0) != V) 55491bc56edSDimitry Andric break; 55591bc56edSDimitry Andric if (UserInsInst->getIndices() == FirstIndices) { 55691bc56edSDimitry Andric IsRedundant = true; 55791bc56edSDimitry Andric break; 55891bc56edSDimitry Andric } 55991bc56edSDimitry Andric V = UserInsInst; 56091bc56edSDimitry Andric Depth++; 56191bc56edSDimitry Andric } 56291bc56edSDimitry Andric 56391bc56edSDimitry Andric if (IsRedundant) 5643ca95b02SDimitry Andric return replaceInstUsesWith(I, I.getOperand(0)); 56591bc56edSDimitry Andric return nullptr; 566f22ef01cSRoman Divacky } 567f22ef01cSRoman Divacky 568d88c1a5aSDimitry Andric static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 569d88c1a5aSDimitry Andric int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); 570d88c1a5aSDimitry Andric int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); 571d88c1a5aSDimitry Andric 572d88c1a5aSDimitry Andric // A vector select does not change the size of the operands. 573d88c1a5aSDimitry Andric if (MaskSize != VecSize) 574d88c1a5aSDimitry Andric return false; 575d88c1a5aSDimitry Andric 576d88c1a5aSDimitry Andric // Each mask element must be undefined or choose a vector element from one of 577d88c1a5aSDimitry Andric // the source operands without crossing vector lanes. 578d88c1a5aSDimitry Andric for (int i = 0; i != MaskSize; ++i) { 579d88c1a5aSDimitry Andric int Elt = Shuf.getMaskValue(i); 580d88c1a5aSDimitry Andric if (Elt != -1 && Elt != i && Elt != i + VecSize) 581d88c1a5aSDimitry Andric return false; 582d88c1a5aSDimitry Andric } 583d88c1a5aSDimitry Andric 584d88c1a5aSDimitry Andric return true; 585d88c1a5aSDimitry Andric } 586d88c1a5aSDimitry Andric 587d88c1a5aSDimitry Andric // Turn a chain of inserts that splats a value into a canonical insert + shuffle 588d88c1a5aSDimitry Andric // splat. That is: 589d88c1a5aSDimitry Andric // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> 590d88c1a5aSDimitry Andric // shufflevector(insertelt(X, %k, 0), undef, zero) 591d88c1a5aSDimitry Andric static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) { 592d88c1a5aSDimitry Andric // We are interested in the last insert in a chain. So, if this insert 593d88c1a5aSDimitry Andric // has a single user, and that user is an insert, bail. 594d88c1a5aSDimitry Andric if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) 595d88c1a5aSDimitry Andric return nullptr; 596d88c1a5aSDimitry Andric 597d88c1a5aSDimitry Andric VectorType *VT = cast<VectorType>(InsElt.getType()); 598d88c1a5aSDimitry Andric int NumElements = VT->getNumElements(); 599d88c1a5aSDimitry Andric 600d88c1a5aSDimitry Andric // Do not try to do this for a one-element vector, since that's a nop, 601d88c1a5aSDimitry Andric // and will cause an inf-loop. 602d88c1a5aSDimitry Andric if (NumElements == 1) 603d88c1a5aSDimitry Andric return nullptr; 604d88c1a5aSDimitry Andric 605d88c1a5aSDimitry Andric Value *SplatVal = InsElt.getOperand(1); 606d88c1a5aSDimitry Andric InsertElementInst *CurrIE = &InsElt; 607d88c1a5aSDimitry Andric SmallVector<bool, 16> ElementPresent(NumElements, false); 6082cab237bSDimitry Andric InsertElementInst *FirstIE = nullptr; 609d88c1a5aSDimitry Andric 610d88c1a5aSDimitry Andric // Walk the chain backwards, keeping track of which indices we inserted into, 611d88c1a5aSDimitry Andric // until we hit something that isn't an insert of the splatted value. 612d88c1a5aSDimitry Andric while (CurrIE) { 6132cab237bSDimitry Andric auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); 614d88c1a5aSDimitry Andric if (!Idx || CurrIE->getOperand(1) != SplatVal) 615d88c1a5aSDimitry Andric return nullptr; 616d88c1a5aSDimitry Andric 6172cab237bSDimitry Andric auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); 6182cab237bSDimitry Andric // Check none of the intermediate steps have any additional uses, except 6192cab237bSDimitry Andric // for the root insertelement instruction, which can be re-used, if it 6202cab237bSDimitry Andric // inserts at position 0. 6212cab237bSDimitry Andric if (CurrIE != &InsElt && 6222cab237bSDimitry Andric (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero()))) 623d88c1a5aSDimitry Andric return nullptr; 624d88c1a5aSDimitry Andric 625d88c1a5aSDimitry Andric ElementPresent[Idx->getZExtValue()] = true; 6262cab237bSDimitry Andric FirstIE = CurrIE; 6272cab237bSDimitry Andric CurrIE = NextIE; 628d88c1a5aSDimitry Andric } 629d88c1a5aSDimitry Andric 630d88c1a5aSDimitry Andric // Make sure we've seen an insert into every element. 631d88c1a5aSDimitry Andric if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; })) 632d88c1a5aSDimitry Andric return nullptr; 633d88c1a5aSDimitry Andric 634d88c1a5aSDimitry Andric // All right, create the insert + shuffle. 6352cab237bSDimitry Andric Instruction *InsertFirst; 6362cab237bSDimitry Andric if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero()) 6372cab237bSDimitry Andric InsertFirst = FirstIE; 6382cab237bSDimitry Andric else 6392cab237bSDimitry Andric InsertFirst = InsertElementInst::Create( 640d88c1a5aSDimitry Andric UndefValue::get(VT), SplatVal, 6412cab237bSDimitry Andric ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), 6422cab237bSDimitry Andric "", &InsElt); 643d88c1a5aSDimitry Andric 644d88c1a5aSDimitry Andric Constant *ZeroMask = ConstantAggregateZero::get( 645d88c1a5aSDimitry Andric VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements)); 646d88c1a5aSDimitry Andric 647d88c1a5aSDimitry Andric return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask); 648d88c1a5aSDimitry Andric } 649d88c1a5aSDimitry Andric 6507a7e6055SDimitry Andric /// If we have an insertelement instruction feeding into another insertelement 6517a7e6055SDimitry Andric /// and the 2nd is inserting a constant into the vector, canonicalize that 6527a7e6055SDimitry Andric /// constant insertion before the insertion of a variable: 6537a7e6055SDimitry Andric /// 6547a7e6055SDimitry Andric /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> 6557a7e6055SDimitry Andric /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 6567a7e6055SDimitry Andric /// 6577a7e6055SDimitry Andric /// This has the potential of eliminating the 2nd insertelement instruction 6587a7e6055SDimitry Andric /// via constant folding of the scalar constant into a vector constant. 6597a7e6055SDimitry Andric static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, 6607a7e6055SDimitry Andric InstCombiner::BuilderTy &Builder) { 6617a7e6055SDimitry Andric auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); 6627a7e6055SDimitry Andric if (!InsElt1 || !InsElt1->hasOneUse()) 6637a7e6055SDimitry Andric return nullptr; 6647a7e6055SDimitry Andric 6657a7e6055SDimitry Andric Value *X, *Y; 6667a7e6055SDimitry Andric Constant *ScalarC; 6677a7e6055SDimitry Andric ConstantInt *IdxC1, *IdxC2; 6687a7e6055SDimitry Andric if (match(InsElt1->getOperand(0), m_Value(X)) && 6697a7e6055SDimitry Andric match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && 6707a7e6055SDimitry Andric match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && 6717a7e6055SDimitry Andric match(InsElt2.getOperand(1), m_Constant(ScalarC)) && 6727a7e6055SDimitry Andric match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { 6737a7e6055SDimitry Andric Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); 6747a7e6055SDimitry Andric return InsertElementInst::Create(NewInsElt1, Y, IdxC1); 6757a7e6055SDimitry Andric } 6767a7e6055SDimitry Andric 6777a7e6055SDimitry Andric return nullptr; 6787a7e6055SDimitry Andric } 6797a7e6055SDimitry Andric 680d88c1a5aSDimitry Andric /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 681d88c1a5aSDimitry Andric /// --> shufflevector X, CVec', Mask' 682d88c1a5aSDimitry Andric static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 683d88c1a5aSDimitry Andric auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 684d88c1a5aSDimitry Andric // Bail out if the parent has more than one use. In that case, we'd be 685d88c1a5aSDimitry Andric // replacing the insertelt with a shuffle, and that's not a clear win. 686d88c1a5aSDimitry Andric if (!Inst || !Inst->hasOneUse()) 687d88c1a5aSDimitry Andric return nullptr; 688d88c1a5aSDimitry Andric if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 689d88c1a5aSDimitry Andric // The shuffle must have a constant vector operand. The insertelt must have 690d88c1a5aSDimitry Andric // a constant scalar being inserted at a constant position in the vector. 691d88c1a5aSDimitry Andric Constant *ShufConstVec, *InsEltScalar; 692d88c1a5aSDimitry Andric uint64_t InsEltIndex; 693d88c1a5aSDimitry Andric if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 694d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 695d88c1a5aSDimitry Andric !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 696d88c1a5aSDimitry Andric return nullptr; 697d88c1a5aSDimitry Andric 698d88c1a5aSDimitry Andric // Adding an element to an arbitrary shuffle could be expensive, but a 699d88c1a5aSDimitry Andric // shuffle that selects elements from vectors without crossing lanes is 700d88c1a5aSDimitry Andric // assumed cheap. 701d88c1a5aSDimitry Andric // If we're just adding a constant into that shuffle, it will still be 702d88c1a5aSDimitry Andric // cheap. 703d88c1a5aSDimitry Andric if (!isShuffleEquivalentToSelect(*Shuf)) 704d88c1a5aSDimitry Andric return nullptr; 705d88c1a5aSDimitry Andric 706d88c1a5aSDimitry Andric // From the above 'select' check, we know that the mask has the same number 707d88c1a5aSDimitry Andric // of elements as the vector input operands. We also know that each constant 708d88c1a5aSDimitry Andric // input element is used in its lane and can not be used more than once by 709d88c1a5aSDimitry Andric // the shuffle. Therefore, replace the constant in the shuffle's constant 710d88c1a5aSDimitry Andric // vector with the insertelt constant. Replace the constant in the shuffle's 711d88c1a5aSDimitry Andric // mask vector with the insertelt index plus the length of the vector 712d88c1a5aSDimitry Andric // (because the constant vector operand of a shuffle is always the 2nd 713d88c1a5aSDimitry Andric // operand). 714d88c1a5aSDimitry Andric Constant *Mask = Shuf->getMask(); 715d88c1a5aSDimitry Andric unsigned NumElts = Mask->getType()->getVectorNumElements(); 716d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewShufElts(NumElts); 717d88c1a5aSDimitry Andric SmallVector<Constant *, 16> NewMaskElts(NumElts); 718d88c1a5aSDimitry Andric for (unsigned I = 0; I != NumElts; ++I) { 719d88c1a5aSDimitry Andric if (I == InsEltIndex) { 720d88c1a5aSDimitry Andric NewShufElts[I] = InsEltScalar; 721d88c1a5aSDimitry Andric Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); 722d88c1a5aSDimitry Andric NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); 723d88c1a5aSDimitry Andric } else { 724d88c1a5aSDimitry Andric // Copy over the existing values. 725d88c1a5aSDimitry Andric NewShufElts[I] = ShufConstVec->getAggregateElement(I); 726d88c1a5aSDimitry Andric NewMaskElts[I] = Mask->getAggregateElement(I); 727d88c1a5aSDimitry Andric } 728d88c1a5aSDimitry Andric } 729d88c1a5aSDimitry Andric 730d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 731d88c1a5aSDimitry Andric // original insertelt. The old shuffle will be dead now. 732d88c1a5aSDimitry Andric return new ShuffleVectorInst(Shuf->getOperand(0), 733d88c1a5aSDimitry Andric ConstantVector::get(NewShufElts), 734d88c1a5aSDimitry Andric ConstantVector::get(NewMaskElts)); 735d88c1a5aSDimitry Andric } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 736d88c1a5aSDimitry Andric // Transform sequences of insertelements ops with constant data/indexes into 737d88c1a5aSDimitry Andric // a single shuffle op. 738d88c1a5aSDimitry Andric unsigned NumElts = InsElt.getType()->getNumElements(); 739d88c1a5aSDimitry Andric 740d88c1a5aSDimitry Andric uint64_t InsertIdx[2]; 741d88c1a5aSDimitry Andric Constant *Val[2]; 742d88c1a5aSDimitry Andric if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 743d88c1a5aSDimitry Andric !match(InsElt.getOperand(1), m_Constant(Val[0])) || 744d88c1a5aSDimitry Andric !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 745d88c1a5aSDimitry Andric !match(IEI->getOperand(1), m_Constant(Val[1]))) 746d88c1a5aSDimitry Andric return nullptr; 747d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Values(NumElts); 748d88c1a5aSDimitry Andric SmallVector<Constant *, 16> Mask(NumElts); 749d88c1a5aSDimitry Andric auto ValI = std::begin(Val); 750d88c1a5aSDimitry Andric // Generate new constant vector and mask. 751d88c1a5aSDimitry Andric // We have 2 values/masks from the insertelements instructions. Insert them 752d88c1a5aSDimitry Andric // into new value/mask vectors. 753d88c1a5aSDimitry Andric for (uint64_t I : InsertIdx) { 754d88c1a5aSDimitry Andric if (!Values[I]) { 755d88c1a5aSDimitry Andric assert(!Mask[I]); 756d88c1a5aSDimitry Andric Values[I] = *ValI; 757d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 758d88c1a5aSDimitry Andric NumElts + I); 759d88c1a5aSDimitry Andric } 760d88c1a5aSDimitry Andric ++ValI; 761d88c1a5aSDimitry Andric } 762d88c1a5aSDimitry Andric // Remaining values are filled with 'undef' values. 763d88c1a5aSDimitry Andric for (unsigned I = 0; I < NumElts; ++I) { 764d88c1a5aSDimitry Andric if (!Values[I]) { 765d88c1a5aSDimitry Andric assert(!Mask[I]); 766d88c1a5aSDimitry Andric Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 767d88c1a5aSDimitry Andric Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); 768d88c1a5aSDimitry Andric } 769d88c1a5aSDimitry Andric } 770d88c1a5aSDimitry Andric // Create new operands for a shuffle that includes the constant of the 771d88c1a5aSDimitry Andric // original insertelt. 772d88c1a5aSDimitry Andric return new ShuffleVectorInst(IEI->getOperand(0), 773d88c1a5aSDimitry Andric ConstantVector::get(Values), 774d88c1a5aSDimitry Andric ConstantVector::get(Mask)); 775d88c1a5aSDimitry Andric } 776d88c1a5aSDimitry Andric return nullptr; 777d88c1a5aSDimitry Andric } 778d88c1a5aSDimitry Andric 779f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 780f22ef01cSRoman Divacky Value *VecOp = IE.getOperand(0); 781f22ef01cSRoman Divacky Value *ScalarOp = IE.getOperand(1); 782f22ef01cSRoman Divacky Value *IdxOp = IE.getOperand(2); 783f22ef01cSRoman Divacky 7842cab237bSDimitry Andric if (auto *V = SimplifyInsertElementInst( 7852cab237bSDimitry Andric VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE))) 7862cab237bSDimitry Andric return replaceInstUsesWith(IE, V); 7872cab237bSDimitry Andric 788f22ef01cSRoman Divacky // Inserting an undef or into an undefined place, remove this. 789f22ef01cSRoman Divacky if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 7903ca95b02SDimitry Andric replaceInstUsesWith(IE, VecOp); 791f22ef01cSRoman Divacky 792f22ef01cSRoman Divacky // If the inserted element was extracted from some other vector, and if the 793f22ef01cSRoman Divacky // indexes are constant, try to turn this into a shufflevector operation. 794f22ef01cSRoman Divacky if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 79591bc56edSDimitry Andric if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 79691bc56edSDimitry Andric unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 79791bc56edSDimitry Andric unsigned NumExtractVectorElts = 79891bc56edSDimitry Andric EI->getOperand(0)->getType()->getVectorNumElements(); 799f22ef01cSRoman Divacky unsigned ExtractedIdx = 800f22ef01cSRoman Divacky cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 801f22ef01cSRoman Divacky unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 802f22ef01cSRoman Divacky 80391bc56edSDimitry Andric if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 8043ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 805f22ef01cSRoman Divacky 80691bc56edSDimitry Andric if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 8073ca95b02SDimitry Andric return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 808f22ef01cSRoman Divacky 809f22ef01cSRoman Divacky // If we are extracting a value from a vector, then inserting it right 810f22ef01cSRoman Divacky // back into the same place, just use the input vector. 811f22ef01cSRoman Divacky if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 8123ca95b02SDimitry Andric return replaceInstUsesWith(IE, VecOp); 813f22ef01cSRoman Divacky 814f22ef01cSRoman Divacky // If this insertelement isn't used by some other insertelement, turn it 815f22ef01cSRoman Divacky // (and any insertelements it points to), into one big shuffle. 81691bc56edSDimitry Andric if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 817dff0c46cSDimitry Andric SmallVector<Constant*, 16> Mask; 8187d523365SDimitry Andric ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 81991bc56edSDimitry Andric 82091bc56edSDimitry Andric // The proposed shuffle may be trivial, in which case we shouldn't 82191bc56edSDimitry Andric // perform the combine. 82291bc56edSDimitry Andric if (LR.first != &IE && LR.second != &IE) { 823f22ef01cSRoman Divacky // We now have a shuffle of LHS, RHS, Mask. 82491bc56edSDimitry Andric if (LR.second == nullptr) 82591bc56edSDimitry Andric LR.second = UndefValue::get(LR.first->getType()); 82691bc56edSDimitry Andric return new ShuffleVectorInst(LR.first, LR.second, 82791bc56edSDimitry Andric ConstantVector::get(Mask)); 82891bc56edSDimitry Andric } 829f22ef01cSRoman Divacky } 830f22ef01cSRoman Divacky } 831f22ef01cSRoman Divacky } 832f22ef01cSRoman Divacky 833d88c1a5aSDimitry Andric unsigned VWidth = VecOp->getType()->getVectorNumElements(); 834f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 835f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 8362754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 8372754fe60SDimitry Andric if (V != &IE) 8383ca95b02SDimitry Andric return replaceInstUsesWith(IE, V); 839f22ef01cSRoman Divacky return &IE; 8402754fe60SDimitry Andric } 841f22ef01cSRoman Divacky 842d88c1a5aSDimitry Andric if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 843d88c1a5aSDimitry Andric return Shuf; 844d88c1a5aSDimitry Andric 845c4394386SDimitry Andric if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) 8467a7e6055SDimitry Andric return NewInsElt; 8477a7e6055SDimitry Andric 848d88c1a5aSDimitry Andric // Turn a sequence of inserts that broadcasts a scalar into a single 849d88c1a5aSDimitry Andric // insert + shufflevector. 850d88c1a5aSDimitry Andric if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE)) 851d88c1a5aSDimitry Andric return Broadcast; 852d88c1a5aSDimitry Andric 85391bc56edSDimitry Andric return nullptr; 854f22ef01cSRoman Divacky } 855f22ef01cSRoman Divacky 856f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector 857f785676fSDimitry Andric /// elements were shuffled in a different order. 858f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 859f785676fSDimitry Andric unsigned Depth = 5) { 860f785676fSDimitry Andric // We can always reorder the elements of a constant. 861f785676fSDimitry Andric if (isa<Constant>(V)) 862f785676fSDimitry Andric return true; 863f785676fSDimitry Andric 864f785676fSDimitry Andric // We won't reorder vector arguments. No IPO here. 865f785676fSDimitry Andric Instruction *I = dyn_cast<Instruction>(V); 866f785676fSDimitry Andric if (!I) return false; 867f785676fSDimitry Andric 868f785676fSDimitry Andric // Two users may expect different orders of the elements. Don't try it. 869f785676fSDimitry Andric if (!I->hasOneUse()) 870f785676fSDimitry Andric return false; 871f785676fSDimitry Andric 872f785676fSDimitry Andric if (Depth == 0) return false; 873f785676fSDimitry Andric 874f785676fSDimitry Andric switch (I->getOpcode()) { 875f785676fSDimitry Andric case Instruction::Add: 876f785676fSDimitry Andric case Instruction::FAdd: 877f785676fSDimitry Andric case Instruction::Sub: 878f785676fSDimitry Andric case Instruction::FSub: 879f785676fSDimitry Andric case Instruction::Mul: 880f785676fSDimitry Andric case Instruction::FMul: 881f785676fSDimitry Andric case Instruction::UDiv: 882f785676fSDimitry Andric case Instruction::SDiv: 883f785676fSDimitry Andric case Instruction::FDiv: 884f785676fSDimitry Andric case Instruction::URem: 885f785676fSDimitry Andric case Instruction::SRem: 886f785676fSDimitry Andric case Instruction::FRem: 887f785676fSDimitry Andric case Instruction::Shl: 888f785676fSDimitry Andric case Instruction::LShr: 889f785676fSDimitry Andric case Instruction::AShr: 890f785676fSDimitry Andric case Instruction::And: 891f785676fSDimitry Andric case Instruction::Or: 892f785676fSDimitry Andric case Instruction::Xor: 893f785676fSDimitry Andric case Instruction::ICmp: 894f785676fSDimitry Andric case Instruction::FCmp: 895f785676fSDimitry Andric case Instruction::Trunc: 896f785676fSDimitry Andric case Instruction::ZExt: 897f785676fSDimitry Andric case Instruction::SExt: 898f785676fSDimitry Andric case Instruction::FPToUI: 899f785676fSDimitry Andric case Instruction::FPToSI: 900f785676fSDimitry Andric case Instruction::UIToFP: 901f785676fSDimitry Andric case Instruction::SIToFP: 902f785676fSDimitry Andric case Instruction::FPTrunc: 903f785676fSDimitry Andric case Instruction::FPExt: 904f785676fSDimitry Andric case Instruction::GetElementPtr: { 9057d523365SDimitry Andric for (Value *Operand : I->operands()) { 9067d523365SDimitry Andric if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 907f785676fSDimitry Andric return false; 908f785676fSDimitry Andric } 909f785676fSDimitry Andric return true; 910f785676fSDimitry Andric } 911f785676fSDimitry Andric case Instruction::InsertElement: { 912f785676fSDimitry Andric ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 913f785676fSDimitry Andric if (!CI) return false; 914f785676fSDimitry Andric int ElementNumber = CI->getLimitedValue(); 915f785676fSDimitry Andric 916f785676fSDimitry Andric // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 917f785676fSDimitry Andric // can't put an element into multiple indices. 918f785676fSDimitry Andric bool SeenOnce = false; 919f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 920f785676fSDimitry Andric if (Mask[i] == ElementNumber) { 921f785676fSDimitry Andric if (SeenOnce) 922f785676fSDimitry Andric return false; 923f785676fSDimitry Andric SeenOnce = true; 924f785676fSDimitry Andric } 925f785676fSDimitry Andric } 926f785676fSDimitry Andric return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 927f785676fSDimitry Andric } 928f785676fSDimitry Andric } 929f785676fSDimitry Andric return false; 930f785676fSDimitry Andric } 931f785676fSDimitry Andric 932f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given. 933f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct. 9347d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 935f785676fSDimitry Andric // We don't want to use the IRBuilder here because we want the replacement 936f785676fSDimitry Andric // instructions to appear next to 'I', not the builder's insertion point. 937f785676fSDimitry Andric switch (I->getOpcode()) { 938f785676fSDimitry Andric case Instruction::Add: 939f785676fSDimitry Andric case Instruction::FAdd: 940f785676fSDimitry Andric case Instruction::Sub: 941f785676fSDimitry Andric case Instruction::FSub: 942f785676fSDimitry Andric case Instruction::Mul: 943f785676fSDimitry Andric case Instruction::FMul: 944f785676fSDimitry Andric case Instruction::UDiv: 945f785676fSDimitry Andric case Instruction::SDiv: 946f785676fSDimitry Andric case Instruction::FDiv: 947f785676fSDimitry Andric case Instruction::URem: 948f785676fSDimitry Andric case Instruction::SRem: 949f785676fSDimitry Andric case Instruction::FRem: 950f785676fSDimitry Andric case Instruction::Shl: 951f785676fSDimitry Andric case Instruction::LShr: 952f785676fSDimitry Andric case Instruction::AShr: 953f785676fSDimitry Andric case Instruction::And: 954f785676fSDimitry Andric case Instruction::Or: 955f785676fSDimitry Andric case Instruction::Xor: { 956f785676fSDimitry Andric BinaryOperator *BO = cast<BinaryOperator>(I); 957f785676fSDimitry Andric assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 958f785676fSDimitry Andric BinaryOperator *New = 959f785676fSDimitry Andric BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 960f785676fSDimitry Andric NewOps[0], NewOps[1], "", BO); 961f785676fSDimitry Andric if (isa<OverflowingBinaryOperator>(BO)) { 962f785676fSDimitry Andric New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 963f785676fSDimitry Andric New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 964f785676fSDimitry Andric } 965f785676fSDimitry Andric if (isa<PossiblyExactOperator>(BO)) { 966f785676fSDimitry Andric New->setIsExact(BO->isExact()); 967f785676fSDimitry Andric } 96891bc56edSDimitry Andric if (isa<FPMathOperator>(BO)) 96991bc56edSDimitry Andric New->copyFastMathFlags(I); 970f785676fSDimitry Andric return New; 971f785676fSDimitry Andric } 972f785676fSDimitry Andric case Instruction::ICmp: 973f785676fSDimitry Andric assert(NewOps.size() == 2 && "icmp with #ops != 2"); 974f785676fSDimitry Andric return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 975f785676fSDimitry Andric NewOps[0], NewOps[1]); 976f785676fSDimitry Andric case Instruction::FCmp: 977f785676fSDimitry Andric assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 978f785676fSDimitry Andric return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 979f785676fSDimitry Andric NewOps[0], NewOps[1]); 980f785676fSDimitry Andric case Instruction::Trunc: 981f785676fSDimitry Andric case Instruction::ZExt: 982f785676fSDimitry Andric case Instruction::SExt: 983f785676fSDimitry Andric case Instruction::FPToUI: 984f785676fSDimitry Andric case Instruction::FPToSI: 985f785676fSDimitry Andric case Instruction::UIToFP: 986f785676fSDimitry Andric case Instruction::SIToFP: 987f785676fSDimitry Andric case Instruction::FPTrunc: 988f785676fSDimitry Andric case Instruction::FPExt: { 989f785676fSDimitry Andric // It's possible that the mask has a different number of elements from 990f785676fSDimitry Andric // the original cast. We recompute the destination type to match the mask. 991f785676fSDimitry Andric Type *DestTy = 992f785676fSDimitry Andric VectorType::get(I->getType()->getScalarType(), 993f785676fSDimitry Andric NewOps[0]->getType()->getVectorNumElements()); 994f785676fSDimitry Andric assert(NewOps.size() == 1 && "cast with #ops != 1"); 995f785676fSDimitry Andric return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 996f785676fSDimitry Andric "", I); 997f785676fSDimitry Andric } 998f785676fSDimitry Andric case Instruction::GetElementPtr: { 999f785676fSDimitry Andric Value *Ptr = NewOps[0]; 1000f785676fSDimitry Andric ArrayRef<Value*> Idx = NewOps.slice(1); 1001ff0cc061SDimitry Andric GetElementPtrInst *GEP = GetElementPtrInst::Create( 1002ff0cc061SDimitry Andric cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 1003f785676fSDimitry Andric GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 1004f785676fSDimitry Andric return GEP; 1005f785676fSDimitry Andric } 1006f785676fSDimitry Andric } 1007f785676fSDimitry Andric llvm_unreachable("failed to rebuild vector instructions"); 1008f785676fSDimitry Andric } 1009f785676fSDimitry Andric 1010f785676fSDimitry Andric Value * 1011f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 1012f785676fSDimitry Andric // Mask.size() does not need to be equal to the number of vector elements. 1013f785676fSDimitry Andric 1014f785676fSDimitry Andric assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 10152cab237bSDimitry Andric Type *EltTy = V->getType()->getScalarType(); 10162cab237bSDimitry Andric if (isa<UndefValue>(V)) 10172cab237bSDimitry Andric return UndefValue::get(VectorType::get(EltTy, Mask.size())); 10182cab237bSDimitry Andric 10192cab237bSDimitry Andric if (isa<ConstantAggregateZero>(V)) 10202cab237bSDimitry Andric return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size())); 10212cab237bSDimitry Andric 1022f785676fSDimitry Andric if (Constant *C = dyn_cast<Constant>(V)) { 1023f785676fSDimitry Andric SmallVector<Constant *, 16> MaskValues; 1024f785676fSDimitry Andric for (int i = 0, e = Mask.size(); i != e; ++i) { 1025f785676fSDimitry Andric if (Mask[i] == -1) 1026c4394386SDimitry Andric MaskValues.push_back(UndefValue::get(Builder.getInt32Ty())); 1027f785676fSDimitry Andric else 1028c4394386SDimitry Andric MaskValues.push_back(Builder.getInt32(Mask[i])); 1029f785676fSDimitry Andric } 1030f785676fSDimitry Andric return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 1031f785676fSDimitry Andric ConstantVector::get(MaskValues)); 1032f785676fSDimitry Andric } 1033f785676fSDimitry Andric 1034f785676fSDimitry Andric Instruction *I = cast<Instruction>(V); 1035f785676fSDimitry Andric switch (I->getOpcode()) { 1036f785676fSDimitry Andric case Instruction::Add: 1037f785676fSDimitry Andric case Instruction::FAdd: 1038f785676fSDimitry Andric case Instruction::Sub: 1039f785676fSDimitry Andric case Instruction::FSub: 1040f785676fSDimitry Andric case Instruction::Mul: 1041f785676fSDimitry Andric case Instruction::FMul: 1042f785676fSDimitry Andric case Instruction::UDiv: 1043f785676fSDimitry Andric case Instruction::SDiv: 1044f785676fSDimitry Andric case Instruction::FDiv: 1045f785676fSDimitry Andric case Instruction::URem: 1046f785676fSDimitry Andric case Instruction::SRem: 1047f785676fSDimitry Andric case Instruction::FRem: 1048f785676fSDimitry Andric case Instruction::Shl: 1049f785676fSDimitry Andric case Instruction::LShr: 1050f785676fSDimitry Andric case Instruction::AShr: 1051f785676fSDimitry Andric case Instruction::And: 1052f785676fSDimitry Andric case Instruction::Or: 1053f785676fSDimitry Andric case Instruction::Xor: 1054f785676fSDimitry Andric case Instruction::ICmp: 1055f785676fSDimitry Andric case Instruction::FCmp: 1056f785676fSDimitry Andric case Instruction::Trunc: 1057f785676fSDimitry Andric case Instruction::ZExt: 1058f785676fSDimitry Andric case Instruction::SExt: 1059f785676fSDimitry Andric case Instruction::FPToUI: 1060f785676fSDimitry Andric case Instruction::FPToSI: 1061f785676fSDimitry Andric case Instruction::UIToFP: 1062f785676fSDimitry Andric case Instruction::SIToFP: 1063f785676fSDimitry Andric case Instruction::FPTrunc: 1064f785676fSDimitry Andric case Instruction::FPExt: 1065f785676fSDimitry Andric case Instruction::Select: 1066f785676fSDimitry Andric case Instruction::GetElementPtr: { 1067f785676fSDimitry Andric SmallVector<Value*, 8> NewOps; 1068f785676fSDimitry Andric bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 1069f785676fSDimitry Andric for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 1070f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 1071f785676fSDimitry Andric NewOps.push_back(V); 1072f785676fSDimitry Andric NeedsRebuild |= (V != I->getOperand(i)); 1073f785676fSDimitry Andric } 1074f785676fSDimitry Andric if (NeedsRebuild) { 10757d523365SDimitry Andric return buildNew(I, NewOps); 1076f785676fSDimitry Andric } 1077f785676fSDimitry Andric return I; 1078f785676fSDimitry Andric } 1079f785676fSDimitry Andric case Instruction::InsertElement: { 1080f785676fSDimitry Andric int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 1081f785676fSDimitry Andric 1082f785676fSDimitry Andric // The insertelement was inserting at Element. Figure out which element 1083f785676fSDimitry Andric // that becomes after shuffling. The answer is guaranteed to be unique 1084f785676fSDimitry Andric // by CanEvaluateShuffled. 1085f785676fSDimitry Andric bool Found = false; 1086f785676fSDimitry Andric int Index = 0; 1087f785676fSDimitry Andric for (int e = Mask.size(); Index != e; ++Index) { 1088f785676fSDimitry Andric if (Mask[Index] == Element) { 1089f785676fSDimitry Andric Found = true; 1090f785676fSDimitry Andric break; 1091f785676fSDimitry Andric } 1092f785676fSDimitry Andric } 1093f785676fSDimitry Andric 109491bc56edSDimitry Andric // If element is not in Mask, no need to handle the operand 1 (element to 109591bc56edSDimitry Andric // be inserted). Just evaluate values in operand 0 according to Mask. 1096f785676fSDimitry Andric if (!Found) 109791bc56edSDimitry Andric return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1098f785676fSDimitry Andric 1099f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1100f785676fSDimitry Andric return InsertElementInst::Create(V, I->getOperand(1), 1101c4394386SDimitry Andric Builder.getInt32(Index), "", I); 1102f785676fSDimitry Andric } 1103f785676fSDimitry Andric } 1104f785676fSDimitry Andric llvm_unreachable("failed to reorder elements of vector instruction!"); 1105f785676fSDimitry Andric } 1106f22ef01cSRoman Divacky 11077d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 110891bc56edSDimitry Andric bool &isLHSID, bool &isRHSID) { 110991bc56edSDimitry Andric isLHSID = isRHSID = true; 111091bc56edSDimitry Andric 111191bc56edSDimitry Andric for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 111291bc56edSDimitry Andric if (Mask[i] < 0) continue; // Ignore undef values. 111391bc56edSDimitry Andric // Is this an identity shuffle of the LHS value? 111491bc56edSDimitry Andric isLHSID &= (Mask[i] == (int)i); 111591bc56edSDimitry Andric 111691bc56edSDimitry Andric // Is this an identity shuffle of the RHS value? 111791bc56edSDimitry Andric isRHSID &= (Mask[i]-e == i); 111891bc56edSDimitry Andric } 111991bc56edSDimitry Andric } 112091bc56edSDimitry Andric 1121ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from 1122ff0cc061SDimitry Andric // LHS, for example: 1123ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1124ff0cc061SDimitry Andric // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1125ff0cc061SDimitry Andric // Shuffles to: |EE|FF|GG|HH| 1126ff0cc061SDimitry Andric // +--+--+--+--+ 1127ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1128ff0cc061SDimitry Andric SmallVector<int, 16> &Mask) { 1129d88c1a5aSDimitry Andric unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements(); 1130ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1131ff0cc061SDimitry Andric unsigned BegIdx = Mask.front(); 1132ff0cc061SDimitry Andric unsigned EndIdx = Mask.back(); 1133ff0cc061SDimitry Andric if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1134ff0cc061SDimitry Andric return false; 1135ff0cc061SDimitry Andric for (unsigned I = 0; I != MaskElems; ++I) 1136ff0cc061SDimitry Andric if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1137ff0cc061SDimitry Andric return false; 1138ff0cc061SDimitry Andric return true; 1139ff0cc061SDimitry Andric } 1140ff0cc061SDimitry Andric 1141f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 1142f22ef01cSRoman Divacky Value *LHS = SVI.getOperand(0); 1143f22ef01cSRoman Divacky Value *RHS = SVI.getOperand(1); 1144dff0c46cSDimitry Andric SmallVector<int, 16> Mask = SVI.getShuffleMask(); 1145ff0cc061SDimitry Andric Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 1146f22ef01cSRoman Divacky 1147db17bf38SDimitry Andric if (auto *V = SimplifyShuffleVectorInst( 1148db17bf38SDimitry Andric LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI))) 11497a7e6055SDimitry Andric return replaceInstUsesWith(SVI, V); 11507a7e6055SDimitry Andric 1151f22ef01cSRoman Divacky bool MadeChange = false; 1152d88c1a5aSDimitry Andric unsigned VWidth = SVI.getType()->getVectorNumElements(); 1153f22ef01cSRoman Divacky 1154f22ef01cSRoman Divacky APInt UndefElts(VWidth, 0); 1155f22ef01cSRoman Divacky APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 11562754fe60SDimitry Andric if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 11572754fe60SDimitry Andric if (V != &SVI) 11583ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 11592cab237bSDimitry Andric return &SVI; 1160f22ef01cSRoman Divacky } 1161f22ef01cSRoman Divacky 1162d88c1a5aSDimitry Andric unsigned LHSWidth = LHS->getType()->getVectorNumElements(); 1163dff0c46cSDimitry Andric 1164f22ef01cSRoman Divacky // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 1165f22ef01cSRoman Divacky // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 1166f22ef01cSRoman Divacky if (LHS == RHS || isa<UndefValue>(LHS)) { 1167f22ef01cSRoman Divacky if (isa<UndefValue>(LHS) && LHS == RHS) { 1168f22ef01cSRoman Divacky // shuffle(undef,undef,mask) -> undef. 1169f785676fSDimitry Andric Value *Result = (VWidth == LHSWidth) 1170dff0c46cSDimitry Andric ? LHS : UndefValue::get(SVI.getType()); 11713ca95b02SDimitry Andric return replaceInstUsesWith(SVI, Result); 1172f22ef01cSRoman Divacky } 1173f22ef01cSRoman Divacky 1174f22ef01cSRoman Divacky // Remap any references to RHS to use LHS. 1175dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1176dff0c46cSDimitry Andric for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 1177dff0c46cSDimitry Andric if (Mask[i] < 0) { 1178ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1179dff0c46cSDimitry Andric continue; 1180dff0c46cSDimitry Andric } 1181dff0c46cSDimitry Andric 11822754fe60SDimitry Andric if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 11832754fe60SDimitry Andric (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 11842754fe60SDimitry Andric Mask[i] = -1; // Turn into undef. 1185ff0cc061SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1186f22ef01cSRoman Divacky } else { 1187f22ef01cSRoman Divacky Mask[i] = Mask[i] % e; // Force to LHS. 1188ff0cc061SDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 1189f22ef01cSRoman Divacky } 1190f22ef01cSRoman Divacky } 1191f22ef01cSRoman Divacky SVI.setOperand(0, SVI.getOperand(1)); 1192f22ef01cSRoman Divacky SVI.setOperand(1, UndefValue::get(RHS->getType())); 1193f22ef01cSRoman Divacky SVI.setOperand(2, ConstantVector::get(Elts)); 1194f22ef01cSRoman Divacky LHS = SVI.getOperand(0); 1195f22ef01cSRoman Divacky RHS = SVI.getOperand(1); 1196f22ef01cSRoman Divacky MadeChange = true; 1197f22ef01cSRoman Divacky } 1198f22ef01cSRoman Divacky 1199dff0c46cSDimitry Andric if (VWidth == LHSWidth) { 1200f22ef01cSRoman Divacky // Analyze the shuffle, are the LHS or RHS and identity shuffles? 120191bc56edSDimitry Andric bool isLHSID, isRHSID; 12027d523365SDimitry Andric recognizeIdentityMask(Mask, isLHSID, isRHSID); 1203f22ef01cSRoman Divacky 1204f22ef01cSRoman Divacky // Eliminate identity shuffles. 12053ca95b02SDimitry Andric if (isLHSID) return replaceInstUsesWith(SVI, LHS); 12063ca95b02SDimitry Andric if (isRHSID) return replaceInstUsesWith(SVI, RHS); 1207dff0c46cSDimitry Andric } 1208f22ef01cSRoman Divacky 1209f785676fSDimitry Andric if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 1210f785676fSDimitry Andric Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 12113ca95b02SDimitry Andric return replaceInstUsesWith(SVI, V); 1212f785676fSDimitry Andric } 1213f785676fSDimitry Andric 1214ff0cc061SDimitry Andric // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 1215ff0cc061SDimitry Andric // a non-vector type. We can instead bitcast the original vector followed by 1216ff0cc061SDimitry Andric // an extract of the desired element: 1217ff0cc061SDimitry Andric // 1218ff0cc061SDimitry Andric // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1219ff0cc061SDimitry Andric // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1220ff0cc061SDimitry Andric // %1 = bitcast <4 x i8> %sroa to i32 1221ff0cc061SDimitry Andric // Becomes: 1222ff0cc061SDimitry Andric // %bc = bitcast <16 x i8> %in to <4 x i32> 1223ff0cc061SDimitry Andric // %ext = extractelement <4 x i32> %bc, i32 0 1224ff0cc061SDimitry Andric // 1225ff0cc061SDimitry Andric // If the shuffle is extracting a contiguous range of values from the input 1226ff0cc061SDimitry Andric // vector then each use which is a bitcast of the extracted size can be 1227ff0cc061SDimitry Andric // replaced. This will work if the vector types are compatible, and the begin 1228ff0cc061SDimitry Andric // index is aligned to a value in the casted vector type. If the begin index 1229ff0cc061SDimitry Andric // isn't aligned then we can shuffle the original vector (keeping the same 1230ff0cc061SDimitry Andric // vector type) before extracting. 1231ff0cc061SDimitry Andric // 1232ff0cc061SDimitry Andric // This code will bail out if the target type is fundamentally incompatible 1233ff0cc061SDimitry Andric // with vectors of the source type. 1234ff0cc061SDimitry Andric // 1235ff0cc061SDimitry Andric // Example of <16 x i8>, target type i32: 1236ff0cc061SDimitry Andric // Index range [4,8): v-----------v Will work. 1237ff0cc061SDimitry Andric // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1238ff0cc061SDimitry Andric // <16 x i8>: | | | | | | | | | | | | | | | | | 1239ff0cc061SDimitry Andric // <4 x i32>: | | | | | 1240ff0cc061SDimitry Andric // +-----------+-----------+-----------+-----------+ 1241ff0cc061SDimitry Andric // Index range [6,10): ^-----------^ Needs an extra shuffle. 1242ff0cc061SDimitry Andric // Target type i40: ^--------------^ Won't work, bail. 1243ff0cc061SDimitry Andric if (isShuffleExtractingFromLHS(SVI, Mask)) { 1244ff0cc061SDimitry Andric Value *V = LHS; 1245ff0cc061SDimitry Andric unsigned MaskElems = Mask.size(); 1246ff0cc061SDimitry Andric VectorType *SrcTy = cast<VectorType>(V->getType()); 1247ff0cc061SDimitry Andric unsigned VecBitWidth = SrcTy->getBitWidth(); 1248ff0cc061SDimitry Andric unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1249ff0cc061SDimitry Andric assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1250ff0cc061SDimitry Andric unsigned SrcNumElems = SrcTy->getNumElements(); 1251ff0cc061SDimitry Andric SmallVector<BitCastInst *, 8> BCs; 1252ff0cc061SDimitry Andric DenseMap<Type *, Value *> NewBCs; 1253ff0cc061SDimitry Andric for (User *U : SVI.users()) 1254ff0cc061SDimitry Andric if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1255ff0cc061SDimitry Andric if (!BC->use_empty()) 1256ff0cc061SDimitry Andric // Only visit bitcasts that weren't previously handled. 1257ff0cc061SDimitry Andric BCs.push_back(BC); 1258ff0cc061SDimitry Andric for (BitCastInst *BC : BCs) { 12597a7e6055SDimitry Andric unsigned BegIdx = Mask.front(); 1260ff0cc061SDimitry Andric Type *TgtTy = BC->getDestTy(); 1261ff0cc061SDimitry Andric unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1262ff0cc061SDimitry Andric if (!TgtElemBitWidth) 1263ff0cc061SDimitry Andric continue; 1264ff0cc061SDimitry Andric unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1265ff0cc061SDimitry Andric bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1266ff0cc061SDimitry Andric bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1267ff0cc061SDimitry Andric if (!VecBitWidthsEqual) 1268ff0cc061SDimitry Andric continue; 1269ff0cc061SDimitry Andric if (!VectorType::isValidElementType(TgtTy)) 1270ff0cc061SDimitry Andric continue; 1271ff0cc061SDimitry Andric VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1272ff0cc061SDimitry Andric if (!BegIsAligned) { 1273ff0cc061SDimitry Andric // Shuffle the input so [0,NumElements) contains the output, and 1274ff0cc061SDimitry Andric // [NumElems,SrcNumElems) is undef. 1275ff0cc061SDimitry Andric SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1276ff0cc061SDimitry Andric UndefValue::get(Int32Ty)); 1277ff0cc061SDimitry Andric for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1278ff0cc061SDimitry Andric ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1279c4394386SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), 1280ff0cc061SDimitry Andric ConstantVector::get(ShuffleMask), 1281ff0cc061SDimitry Andric SVI.getName() + ".extract"); 1282ff0cc061SDimitry Andric BegIdx = 0; 1283ff0cc061SDimitry Andric } 1284ff0cc061SDimitry Andric unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1285ff0cc061SDimitry Andric assert(SrcElemsPerTgtElem); 1286ff0cc061SDimitry Andric BegIdx /= SrcElemsPerTgtElem; 1287ff0cc061SDimitry Andric bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1288ff0cc061SDimitry Andric auto *NewBC = 1289ff0cc061SDimitry Andric BCAlreadyExists 1290ff0cc061SDimitry Andric ? NewBCs[CastSrcTy] 1291c4394386SDimitry Andric : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1292ff0cc061SDimitry Andric if (!BCAlreadyExists) 1293ff0cc061SDimitry Andric NewBCs[CastSrcTy] = NewBC; 1294c4394386SDimitry Andric auto *Ext = Builder.CreateExtractElement( 1295ff0cc061SDimitry Andric NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1296ff0cc061SDimitry Andric // The shufflevector isn't being replaced: the bitcast that used it 1297ff0cc061SDimitry Andric // is. InstCombine will visit the newly-created instructions. 12983ca95b02SDimitry Andric replaceInstUsesWith(*BC, Ext); 1299ff0cc061SDimitry Andric MadeChange = true; 1300ff0cc061SDimitry Andric } 1301ff0cc061SDimitry Andric } 1302ff0cc061SDimitry Andric 1303f22ef01cSRoman Divacky // If the LHS is a shufflevector itself, see if we can combine it with this 1304dff0c46cSDimitry Andric // one without producing an unusual shuffle. 1305dff0c46cSDimitry Andric // Cases that might be simplified: 1306dff0c46cSDimitry Andric // 1. 1307dff0c46cSDimitry Andric // x1=shuffle(v1,v2,mask1) 1308dff0c46cSDimitry Andric // x=shuffle(x1,undef,mask) 1309dff0c46cSDimitry Andric // ==> 1310dff0c46cSDimitry Andric // x=shuffle(v1,undef,newMask) 1311dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1312dff0c46cSDimitry Andric // 2. 1313dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1314dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1315dff0c46cSDimitry Andric // where v1.size() == mask1.size() 1316dff0c46cSDimitry Andric // ==> 1317dff0c46cSDimitry Andric // x=shuffle(v1,x2,newMask) 1318dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1319dff0c46cSDimitry Andric // 3. 1320dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1321dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1322dff0c46cSDimitry Andric // where v2.size() == mask2.size() 1323dff0c46cSDimitry Andric // ==> 1324dff0c46cSDimitry Andric // x=shuffle(x1,v2,newMask) 1325dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1326dff0c46cSDimitry Andric // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1327dff0c46cSDimitry Andric // 4. 1328dff0c46cSDimitry Andric // x1=shuffle(v1,undef,mask1) 1329dff0c46cSDimitry Andric // x2=shuffle(v2,undef,mask2) 1330dff0c46cSDimitry Andric // x=shuffle(x1,x2,mask) 1331dff0c46cSDimitry Andric // where v1.size() == v2.size() 1332dff0c46cSDimitry Andric // ==> 1333dff0c46cSDimitry Andric // x=shuffle(v1,v2,newMask) 1334dff0c46cSDimitry Andric // newMask[i] = (mask[i] < x1.size()) 1335dff0c46cSDimitry Andric // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1336dff0c46cSDimitry Andric // 1337dff0c46cSDimitry Andric // Here we are really conservative: 1338f22ef01cSRoman Divacky // we are absolutely afraid of producing a shuffle mask not in the input 1339f22ef01cSRoman Divacky // program, because the code gen may not be smart enough to turn a merged 1340f22ef01cSRoman Divacky // shuffle into two specific shuffles: it may produce worse code. As such, 13412754fe60SDimitry Andric // we only merge two shuffles if the result is either a splat or one of the 1342dff0c46cSDimitry Andric // input shuffle masks. In this case, merging the shuffles just removes 13432754fe60SDimitry Andric // one instruction, which we know is safe. This is good for things like 1344dff0c46cSDimitry Andric // turning: (splat(splat)) -> splat, or 1345dff0c46cSDimitry Andric // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1346dff0c46cSDimitry Andric ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1347dff0c46cSDimitry Andric ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1348dff0c46cSDimitry Andric if (LHSShuffle) 1349dff0c46cSDimitry Andric if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 135091bc56edSDimitry Andric LHSShuffle = nullptr; 1351dff0c46cSDimitry Andric if (RHSShuffle) 1352dff0c46cSDimitry Andric if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 135391bc56edSDimitry Andric RHSShuffle = nullptr; 1354dff0c46cSDimitry Andric if (!LHSShuffle && !RHSShuffle) 135591bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1356dff0c46cSDimitry Andric 135791bc56edSDimitry Andric Value* LHSOp0 = nullptr; 135891bc56edSDimitry Andric Value* LHSOp1 = nullptr; 135991bc56edSDimitry Andric Value* RHSOp0 = nullptr; 1360dff0c46cSDimitry Andric unsigned LHSOp0Width = 0; 1361dff0c46cSDimitry Andric unsigned RHSOp0Width = 0; 1362dff0c46cSDimitry Andric if (LHSShuffle) { 1363dff0c46cSDimitry Andric LHSOp0 = LHSShuffle->getOperand(0); 1364dff0c46cSDimitry Andric LHSOp1 = LHSShuffle->getOperand(1); 1365d88c1a5aSDimitry Andric LHSOp0Width = LHSOp0->getType()->getVectorNumElements(); 1366dff0c46cSDimitry Andric } 1367dff0c46cSDimitry Andric if (RHSShuffle) { 1368dff0c46cSDimitry Andric RHSOp0 = RHSShuffle->getOperand(0); 1369d88c1a5aSDimitry Andric RHSOp0Width = RHSOp0->getType()->getVectorNumElements(); 1370dff0c46cSDimitry Andric } 1371dff0c46cSDimitry Andric Value* newLHS = LHS; 1372dff0c46cSDimitry Andric Value* newRHS = RHS; 1373dff0c46cSDimitry Andric if (LHSShuffle) { 1374dff0c46cSDimitry Andric // case 1 1375f22ef01cSRoman Divacky if (isa<UndefValue>(RHS)) { 1376dff0c46cSDimitry Andric newLHS = LHSOp0; 1377dff0c46cSDimitry Andric newRHS = LHSOp1; 1378dff0c46cSDimitry Andric } 1379dff0c46cSDimitry Andric // case 2 or 4 1380dff0c46cSDimitry Andric else if (LHSOp0Width == LHSWidth) { 1381dff0c46cSDimitry Andric newLHS = LHSOp0; 1382dff0c46cSDimitry Andric } 1383dff0c46cSDimitry Andric } 1384dff0c46cSDimitry Andric // case 3 or 4 1385dff0c46cSDimitry Andric if (RHSShuffle && RHSOp0Width == LHSWidth) { 1386dff0c46cSDimitry Andric newRHS = RHSOp0; 1387dff0c46cSDimitry Andric } 1388dff0c46cSDimitry Andric // case 4 1389dff0c46cSDimitry Andric if (LHSOp0 == RHSOp0) { 1390dff0c46cSDimitry Andric newLHS = LHSOp0; 139191bc56edSDimitry Andric newRHS = nullptr; 1392dff0c46cSDimitry Andric } 1393f22ef01cSRoman Divacky 1394dff0c46cSDimitry Andric if (newLHS == LHS && newRHS == RHS) 139591bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1396dff0c46cSDimitry Andric 1397dff0c46cSDimitry Andric SmallVector<int, 16> LHSMask; 1398dff0c46cSDimitry Andric SmallVector<int, 16> RHSMask; 1399dff0c46cSDimitry Andric if (newLHS != LHS) 1400dff0c46cSDimitry Andric LHSMask = LHSShuffle->getShuffleMask(); 1401dff0c46cSDimitry Andric if (RHSShuffle && newRHS != RHS) 1402dff0c46cSDimitry Andric RHSMask = RHSShuffle->getShuffleMask(); 1403dff0c46cSDimitry Andric 1404dff0c46cSDimitry Andric unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1405dff0c46cSDimitry Andric SmallVector<int, 16> newMask; 14062754fe60SDimitry Andric bool isSplat = true; 1407dff0c46cSDimitry Andric int SplatElt = -1; 1408dff0c46cSDimitry Andric // Create a new mask for the new ShuffleVectorInst so that the new 1409dff0c46cSDimitry Andric // ShuffleVectorInst is equivalent to the original one. 1410dff0c46cSDimitry Andric for (unsigned i = 0; i < VWidth; ++i) { 1411dff0c46cSDimitry Andric int eltMask; 1412139f7f9bSDimitry Andric if (Mask[i] < 0) { 1413dff0c46cSDimitry Andric // This element is an undef value. 1414dff0c46cSDimitry Andric eltMask = -1; 1415dff0c46cSDimitry Andric } else if (Mask[i] < (int)LHSWidth) { 1416dff0c46cSDimitry Andric // This element is from left hand side vector operand. 1417dff0c46cSDimitry Andric // 1418dff0c46cSDimitry Andric // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1419dff0c46cSDimitry Andric // new mask value for the element. 1420dff0c46cSDimitry Andric if (newLHS != LHS) { 1421dff0c46cSDimitry Andric eltMask = LHSMask[Mask[i]]; 1422dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1423dff0c46cSDimitry Andric // with a -1 mask value. 1424dff0c46cSDimitry Andric if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1425dff0c46cSDimitry Andric eltMask = -1; 1426139f7f9bSDimitry Andric } else 1427dff0c46cSDimitry Andric eltMask = Mask[i]; 1428dff0c46cSDimitry Andric } else { 1429dff0c46cSDimitry Andric // This element is from right hand side vector operand 1430dff0c46cSDimitry Andric // 1431dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1432dff0c46cSDimitry Andric // with a -1 mask value. (case 1) 1433dff0c46cSDimitry Andric if (isa<UndefValue>(RHS)) 1434dff0c46cSDimitry Andric eltMask = -1; 1435dff0c46cSDimitry Andric // If RHS is going to be replaced (case 3 or 4), calculate the 1436dff0c46cSDimitry Andric // new mask value for the element. 1437dff0c46cSDimitry Andric else if (newRHS != RHS) { 1438dff0c46cSDimitry Andric eltMask = RHSMask[Mask[i]-LHSWidth]; 1439dff0c46cSDimitry Andric // If the value selected is an undef value, explicitly specify it 1440dff0c46cSDimitry Andric // with a -1 mask value. 1441dff0c46cSDimitry Andric if (eltMask >= (int)RHSOp0Width) { 1442dff0c46cSDimitry Andric assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1443dff0c46cSDimitry Andric && "should have been check above"); 1444dff0c46cSDimitry Andric eltMask = -1; 1445dff0c46cSDimitry Andric } 1446139f7f9bSDimitry Andric } else 1447dff0c46cSDimitry Andric eltMask = Mask[i]-LHSWidth; 1448dff0c46cSDimitry Andric 1449dff0c46cSDimitry Andric // If LHS's width is changed, shift the mask value accordingly. 14502cab237bSDimitry Andric // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any 14513861d79fSDimitry Andric // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 14523861d79fSDimitry Andric // If newRHS == newLHS, we want to remap any references from newRHS to 14533861d79fSDimitry Andric // newLHS so that we can properly identify splats that may occur due to 145491bc56edSDimitry Andric // obfuscation across the two vectors. 145591bc56edSDimitry Andric if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1456dff0c46cSDimitry Andric eltMask += newLHSWidth; 14572754fe60SDimitry Andric } 1458f22ef01cSRoman Divacky 1459dff0c46cSDimitry Andric // Check if this could still be a splat. 1460dff0c46cSDimitry Andric if (eltMask >= 0) { 1461dff0c46cSDimitry Andric if (SplatElt >= 0 && SplatElt != eltMask) 1462dff0c46cSDimitry Andric isSplat = false; 1463dff0c46cSDimitry Andric SplatElt = eltMask; 1464dff0c46cSDimitry Andric } 1465dff0c46cSDimitry Andric 1466dff0c46cSDimitry Andric newMask.push_back(eltMask); 1467dff0c46cSDimitry Andric } 1468dff0c46cSDimitry Andric 1469dff0c46cSDimitry Andric // If the result mask is equal to one of the original shuffle masks, 1470dff0c46cSDimitry Andric // or is a splat, do the replacement. 1471dff0c46cSDimitry Andric if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1472dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 1473dff0c46cSDimitry Andric for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1474dff0c46cSDimitry Andric if (newMask[i] < 0) { 14752754fe60SDimitry Andric Elts.push_back(UndefValue::get(Int32Ty)); 1476f22ef01cSRoman Divacky } else { 1477dff0c46cSDimitry Andric Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1478f22ef01cSRoman Divacky } 1479f22ef01cSRoman Divacky } 148091bc56edSDimitry Andric if (!newRHS) 1481dff0c46cSDimitry Andric newRHS = UndefValue::get(newLHS->getType()); 1482dff0c46cSDimitry Andric return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1483f22ef01cSRoman Divacky } 1484f22ef01cSRoman Divacky 148591bc56edSDimitry Andric // If the result mask is an identity, replace uses of this instruction with 148691bc56edSDimitry Andric // corresponding argument. 148791bc56edSDimitry Andric bool isLHSID, isRHSID; 14887d523365SDimitry Andric recognizeIdentityMask(newMask, isLHSID, isRHSID); 14893ca95b02SDimitry Andric if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 14903ca95b02SDimitry Andric if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 149191bc56edSDimitry Andric 149291bc56edSDimitry Andric return MadeChange ? &SVI : nullptr; 1493f22ef01cSRoman Divacky } 1494