1 //===- InstCombineVectorOps.cpp -------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements instcombine for ExtractElement, InsertElement and 10 // ShuffleVector. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallBitVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/InstructionSimplify.h" 23 #include "llvm/Analysis/VectorUtils.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/Constant.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/InstrTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/Operator.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/User.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/Casting.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Transforms/InstCombine/InstCombiner.h" 39 #include <cassert> 40 #include <cstdint> 41 #include <iterator> 42 #include <utility> 43 44 #define DEBUG_TYPE "instcombine" 45 #include "llvm/Transforms/Utils/InstructionWorklist.h" 46 47 using namespace llvm; 48 using namespace PatternMatch; 49 50 STATISTIC(NumAggregateReconstructionsSimplified, 51 "Number of aggregate reconstructions turned into reuse of the " 52 "original aggregate"); 53 54 /// Return true if the value is cheaper to scalarize than it is to leave as a 55 /// vector operation. If the extract index \p EI is a constant integer then 56 /// some operations may be cheap to scalarize. 57 /// 58 /// FIXME: It's possible to create more instructions than previously existed. 59 static bool cheapToScalarize(Value *V, Value *EI) { 60 ConstantInt *CEI = dyn_cast<ConstantInt>(EI); 61 62 // If we can pick a scalar constant value out of a vector, that is free. 63 if (auto *C = dyn_cast<Constant>(V)) 64 return CEI || C->getSplatValue(); 65 66 if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) { 67 ElementCount EC = cast<VectorType>(V->getType())->getElementCount(); 68 // Index needs to be lower than the minimum size of the vector, because 69 // for scalable vector, the vector size is known at run time. 70 return CEI->getValue().ult(EC.getKnownMinValue()); 71 } 72 73 // An insertelement to the same constant index as our extract will simplify 74 // to the scalar inserted element. An insertelement to a different constant 75 // index is irrelevant to our extract. 76 if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt()))) 77 return CEI; 78 79 if (match(V, m_OneUse(m_Load(m_Value())))) 80 return true; 81 82 if (match(V, m_OneUse(m_UnOp()))) 83 return true; 84 85 Value *V0, *V1; 86 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1))))) 87 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI)) 88 return true; 89 90 CmpInst::Predicate UnusedPred; 91 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1))))) 92 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI)) 93 return true; 94 95 return false; 96 } 97 98 // If we have a PHI node with a vector type that is only used to feed 99 // itself and be an operand of extractelement at a constant location, 100 // try to replace the PHI of the vector type with a PHI of a scalar type. 101 Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI, 102 PHINode *PN) { 103 SmallVector<Instruction *, 2> Extracts; 104 // The users we want the PHI to have are: 105 // 1) The EI ExtractElement (we already know this) 106 // 2) Possibly more ExtractElements with the same index. 107 // 3) Another operand, which will feed back into the PHI. 108 Instruction *PHIUser = nullptr; 109 for (auto U : PN->users()) { 110 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 111 if (EI.getIndexOperand() == EU->getIndexOperand()) 112 Extracts.push_back(EU); 113 else 114 return nullptr; 115 } else if (!PHIUser) { 116 PHIUser = cast<Instruction>(U); 117 } else { 118 return nullptr; 119 } 120 } 121 122 if (!PHIUser) 123 return nullptr; 124 125 // Verify that this PHI user has one use, which is the PHI itself, 126 // and that it is a binary operation which is cheap to scalarize. 127 // otherwise return nullptr. 128 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 129 !(isa<BinaryOperator>(PHIUser)) || 130 !cheapToScalarize(PHIUser, EI.getIndexOperand())) 131 return nullptr; 132 133 // Create a scalar PHI node that will replace the vector PHI node 134 // just before the current PHI node. 135 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 136 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 137 // Scalarize each PHI operand. 138 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 139 Value *PHIInVal = PN->getIncomingValue(i); 140 BasicBlock *inBB = PN->getIncomingBlock(i); 141 Value *Elt = EI.getIndexOperand(); 142 // If the operand is the PHI induction variable: 143 if (PHIInVal == PHIUser) { 144 // Scalarize the binary operation. Its first operand is the 145 // scalar PHI, and the second operand is extracted from the other 146 // vector operand. 147 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 148 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 149 Value *Op = InsertNewInstWith( 150 ExtractElementInst::Create(B0->getOperand(opId), Elt, 151 B0->getOperand(opId)->getName() + ".Elt"), 152 *B0); 153 Value *newPHIUser = InsertNewInstWith( 154 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 155 scalarPHI, Op, B0), *B0); 156 scalarPHI->addIncoming(newPHIUser, inBB); 157 } else { 158 // Scalarize PHI input: 159 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 160 // Insert the new instruction into the predecessor basic block. 161 Instruction *pos = dyn_cast<Instruction>(PHIInVal); 162 BasicBlock::iterator InsertPos; 163 if (pos && !isa<PHINode>(pos)) { 164 InsertPos = ++pos->getIterator(); 165 } else { 166 InsertPos = inBB->getFirstInsertionPt(); 167 } 168 169 InsertNewInstWith(newEI, *InsertPos); 170 171 scalarPHI->addIncoming(newEI, inBB); 172 } 173 } 174 175 for (auto E : Extracts) 176 replaceInstUsesWith(*E, scalarPHI); 177 178 return &EI; 179 } 180 181 Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) { 182 Value *X; 183 uint64_t ExtIndexC; 184 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) || 185 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC))) 186 return nullptr; 187 188 ElementCount NumElts = 189 cast<VectorType>(Ext.getVectorOperandType())->getElementCount(); 190 Type *DestTy = Ext.getType(); 191 bool IsBigEndian = DL.isBigEndian(); 192 193 // If we are casting an integer to vector and extracting a portion, that is 194 // a shift-right and truncate. 195 // TODO: Allow FP dest type by casting the trunc to FP? 196 if (X->getType()->isIntegerTy() && DestTy->isIntegerTy() && 197 isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) { 198 assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) && 199 "Expected fixed vector type for bitcast from scalar integer"); 200 201 // Big endian requires adjusting the extract index since MSB is at index 0. 202 // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8 203 // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8 204 if (IsBigEndian) 205 ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC; 206 unsigned ShiftAmountC = ExtIndexC * DestTy->getPrimitiveSizeInBits(); 207 if (!ShiftAmountC || Ext.getVectorOperand()->hasOneUse()) { 208 Value *Lshr = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset"); 209 return new TruncInst(Lshr, DestTy); 210 } 211 } 212 213 if (!X->getType()->isVectorTy()) 214 return nullptr; 215 216 // If this extractelement is using a bitcast from a vector of the same number 217 // of elements, see if we can find the source element from the source vector: 218 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC] 219 auto *SrcTy = cast<VectorType>(X->getType()); 220 ElementCount NumSrcElts = SrcTy->getElementCount(); 221 if (NumSrcElts == NumElts) 222 if (Value *Elt = findScalarElement(X, ExtIndexC)) 223 return new BitCastInst(Elt, DestTy); 224 225 assert(NumSrcElts.isScalable() == NumElts.isScalable() && 226 "Src and Dst must be the same sort of vector type"); 227 228 // If the source elements are wider than the destination, try to shift and 229 // truncate a subset of scalar bits of an insert op. 230 if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) { 231 Value *Scalar; 232 uint64_t InsIndexC; 233 if (!match(X, m_InsertElt(m_Value(), m_Value(Scalar), 234 m_ConstantInt(InsIndexC)))) 235 return nullptr; 236 237 // The extract must be from the subset of vector elements that we inserted 238 // into. Example: if we inserted element 1 of a <2 x i64> and we are 239 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1 240 // of elements 4-7 of the bitcasted vector. 241 unsigned NarrowingRatio = 242 NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue(); 243 if (ExtIndexC / NarrowingRatio != InsIndexC) 244 return nullptr; 245 246 // We are extracting part of the original scalar. How that scalar is 247 // inserted into the vector depends on the endian-ness. Example: 248 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7 249 // +--+--+--+--+--+--+--+--+ 250 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3| 251 // extelt <4 x i16> V', 3: | |S2|S3| 252 // +--+--+--+--+--+--+--+--+ 253 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value. 254 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value. 255 // In this example, we must right-shift little-endian. Big-endian is just a 256 // truncate. 257 unsigned Chunk = ExtIndexC % NarrowingRatio; 258 if (IsBigEndian) 259 Chunk = NarrowingRatio - 1 - Chunk; 260 261 // Bail out if this is an FP vector to FP vector sequence. That would take 262 // more instructions than we started with unless there is no shift, and it 263 // may not be handled as well in the backend. 264 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy(); 265 bool NeedDestBitcast = DestTy->isFloatingPointTy(); 266 if (NeedSrcBitcast && NeedDestBitcast) 267 return nullptr; 268 269 unsigned SrcWidth = SrcTy->getScalarSizeInBits(); 270 unsigned DestWidth = DestTy->getPrimitiveSizeInBits(); 271 unsigned ShAmt = Chunk * DestWidth; 272 273 // TODO: This limitation is more strict than necessary. We could sum the 274 // number of new instructions and subtract the number eliminated to know if 275 // we can proceed. 276 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse()) 277 if (NeedSrcBitcast || NeedDestBitcast) 278 return nullptr; 279 280 if (NeedSrcBitcast) { 281 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth); 282 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy); 283 } 284 285 if (ShAmt) { 286 // Bail out if we could end with more instructions than we started with. 287 if (!Ext.getVectorOperand()->hasOneUse()) 288 return nullptr; 289 Scalar = Builder.CreateLShr(Scalar, ShAmt); 290 } 291 292 if (NeedDestBitcast) { 293 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth); 294 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy); 295 } 296 return new TruncInst(Scalar, DestTy); 297 } 298 299 return nullptr; 300 } 301 302 /// Find elements of V demanded by UserInstr. 303 static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) { 304 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements(); 305 306 // Conservatively assume that all elements are needed. 307 APInt UsedElts(APInt::getAllOnes(VWidth)); 308 309 switch (UserInstr->getOpcode()) { 310 case Instruction::ExtractElement: { 311 ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr); 312 assert(EEI->getVectorOperand() == V); 313 ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand()); 314 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) { 315 UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue()); 316 } 317 break; 318 } 319 case Instruction::ShuffleVector: { 320 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr); 321 unsigned MaskNumElts = 322 cast<FixedVectorType>(UserInstr->getType())->getNumElements(); 323 324 UsedElts = APInt(VWidth, 0); 325 for (unsigned i = 0; i < MaskNumElts; i++) { 326 unsigned MaskVal = Shuffle->getMaskValue(i); 327 if (MaskVal == -1u || MaskVal >= 2 * VWidth) 328 continue; 329 if (Shuffle->getOperand(0) == V && (MaskVal < VWidth)) 330 UsedElts.setBit(MaskVal); 331 if (Shuffle->getOperand(1) == V && 332 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth))) 333 UsedElts.setBit(MaskVal - VWidth); 334 } 335 break; 336 } 337 default: 338 break; 339 } 340 return UsedElts; 341 } 342 343 /// Find union of elements of V demanded by all its users. 344 /// If it is known by querying findDemandedEltsBySingleUser that 345 /// no user demands an element of V, then the corresponding bit 346 /// remains unset in the returned value. 347 static APInt findDemandedEltsByAllUsers(Value *V) { 348 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements(); 349 350 APInt UnionUsedElts(VWidth, 0); 351 for (const Use &U : V->uses()) { 352 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) { 353 UnionUsedElts |= findDemandedEltsBySingleUser(V, I); 354 } else { 355 UnionUsedElts = APInt::getAllOnes(VWidth); 356 break; 357 } 358 359 if (UnionUsedElts.isAllOnes()) 360 break; 361 } 362 363 return UnionUsedElts; 364 } 365 366 Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) { 367 Value *SrcVec = EI.getVectorOperand(); 368 Value *Index = EI.getIndexOperand(); 369 if (Value *V = SimplifyExtractElementInst(SrcVec, Index, 370 SQ.getWithInstruction(&EI))) 371 return replaceInstUsesWith(EI, V); 372 373 // If extracting a specified index from the vector, see if we can recursively 374 // find a previously computed scalar that was inserted into the vector. 375 auto *IndexC = dyn_cast<ConstantInt>(Index); 376 if (IndexC) { 377 ElementCount EC = EI.getVectorOperandType()->getElementCount(); 378 unsigned NumElts = EC.getKnownMinValue(); 379 380 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) { 381 Intrinsic::ID IID = II->getIntrinsicID(); 382 // Index needs to be lower than the minimum size of the vector, because 383 // for scalable vector, the vector size is known at run time. 384 if (IID == Intrinsic::experimental_stepvector && 385 IndexC->getValue().ult(NumElts)) { 386 Type *Ty = EI.getType(); 387 unsigned BitWidth = Ty->getIntegerBitWidth(); 388 Value *Idx; 389 // Return index when its value does not exceed the allowed limit 390 // for the element type of the vector, otherwise return undefined. 391 if (IndexC->getValue().getActiveBits() <= BitWidth) 392 Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth)); 393 else 394 Idx = UndefValue::get(Ty); 395 return replaceInstUsesWith(EI, Idx); 396 } 397 } 398 399 // InstSimplify should handle cases where the index is invalid. 400 // For fixed-length vector, it's invalid to extract out-of-range element. 401 if (!EC.isScalable() && IndexC->getValue().uge(NumElts)) 402 return nullptr; 403 404 if (Instruction *I = foldBitcastExtElt(EI)) 405 return I; 406 407 // If there's a vector PHI feeding a scalar use through this extractelement 408 // instruction, try to scalarize the PHI. 409 if (auto *Phi = dyn_cast<PHINode>(SrcVec)) 410 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi)) 411 return ScalarPHI; 412 } 413 414 // TODO come up with a n-ary matcher that subsumes both unary and 415 // binary matchers. 416 UnaryOperator *UO; 417 if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) { 418 // extelt (unop X), Index --> unop (extelt X, Index) 419 Value *X = UO->getOperand(0); 420 Value *E = Builder.CreateExtractElement(X, Index); 421 return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO); 422 } 423 424 BinaryOperator *BO; 425 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) { 426 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index) 427 Value *X = BO->getOperand(0), *Y = BO->getOperand(1); 428 Value *E0 = Builder.CreateExtractElement(X, Index); 429 Value *E1 = Builder.CreateExtractElement(Y, Index); 430 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO); 431 } 432 433 Value *X, *Y; 434 CmpInst::Predicate Pred; 435 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) && 436 cheapToScalarize(SrcVec, Index)) { 437 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index) 438 Value *E0 = Builder.CreateExtractElement(X, Index); 439 Value *E1 = Builder.CreateExtractElement(Y, Index); 440 return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1); 441 } 442 443 if (auto *I = dyn_cast<Instruction>(SrcVec)) { 444 if (auto *IE = dyn_cast<InsertElementInst>(I)) { 445 // instsimplify already handled the case where the indices are constants 446 // and equal by value, if both are constants, they must not be the same 447 // value, extract from the pre-inserted value instead. 448 if (isa<Constant>(IE->getOperand(2)) && IndexC) 449 return replaceOperand(EI, 0, IE->getOperand(0)); 450 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 451 auto *VecType = cast<VectorType>(GEP->getType()); 452 ElementCount EC = VecType->getElementCount(); 453 uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0; 454 if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) { 455 // Find out why we have a vector result - these are a few examples: 456 // 1. We have a scalar pointer and a vector of indices, or 457 // 2. We have a vector of pointers and a scalar index, or 458 // 3. We have a vector of pointers and a vector of indices, etc. 459 // Here we only consider combining when there is exactly one vector 460 // operand, since the optimization is less obviously a win due to 461 // needing more than one extractelements. 462 463 unsigned VectorOps = 464 llvm::count_if(GEP->operands(), [](const Value *V) { 465 return isa<VectorType>(V->getType()); 466 }); 467 if (VectorOps == 1) { 468 Value *NewPtr = GEP->getPointerOperand(); 469 if (isa<VectorType>(NewPtr->getType())) 470 NewPtr = Builder.CreateExtractElement(NewPtr, IndexC); 471 472 SmallVector<Value *> NewOps; 473 for (unsigned I = 1; I != GEP->getNumOperands(); ++I) { 474 Value *Op = GEP->getOperand(I); 475 if (isa<VectorType>(Op->getType())) 476 NewOps.push_back(Builder.CreateExtractElement(Op, IndexC)); 477 else 478 NewOps.push_back(Op); 479 } 480 481 GetElementPtrInst *NewGEP = GetElementPtrInst::Create( 482 cast<PointerType>(NewPtr->getType())->getElementType(), NewPtr, 483 NewOps); 484 NewGEP->setIsInBounds(GEP->isInBounds()); 485 return NewGEP; 486 } 487 } 488 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) { 489 // If this is extracting an element from a shufflevector, figure out where 490 // it came from and extract from the appropriate input element instead. 491 // Restrict the following transformation to fixed-length vector. 492 if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) { 493 int SrcIdx = 494 SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue()); 495 Value *Src; 496 unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType()) 497 ->getNumElements(); 498 499 if (SrcIdx < 0) 500 return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 501 if (SrcIdx < (int)LHSWidth) 502 Src = SVI->getOperand(0); 503 else { 504 SrcIdx -= LHSWidth; 505 Src = SVI->getOperand(1); 506 } 507 Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 508 return ExtractElementInst::Create( 509 Src, ConstantInt::get(Int32Ty, SrcIdx, false)); 510 } 511 } else if (auto *CI = dyn_cast<CastInst>(I)) { 512 // Canonicalize extractelement(cast) -> cast(extractelement). 513 // Bitcasts can change the number of vector elements, and they cost 514 // nothing. 515 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 516 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index); 517 return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 518 } 519 } 520 } 521 522 // Run demanded elements after other transforms as this can drop flags on 523 // binops. If there's two paths to the same final result, we prefer the 524 // one which doesn't force us to drop flags. 525 if (IndexC) { 526 ElementCount EC = EI.getVectorOperandType()->getElementCount(); 527 unsigned NumElts = EC.getKnownMinValue(); 528 // This instruction only demands the single element from the input vector. 529 // Skip for scalable type, the number of elements is unknown at 530 // compile-time. 531 if (!EC.isScalable() && NumElts != 1) { 532 // If the input vector has a single use, simplify it based on this use 533 // property. 534 if (SrcVec->hasOneUse()) { 535 APInt UndefElts(NumElts, 0); 536 APInt DemandedElts(NumElts, 0); 537 DemandedElts.setBit(IndexC->getZExtValue()); 538 if (Value *V = 539 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts)) 540 return replaceOperand(EI, 0, V); 541 } else { 542 // If the input vector has multiple uses, simplify it based on a union 543 // of all elements used. 544 APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec); 545 if (!DemandedElts.isAllOnes()) { 546 APInt UndefElts(NumElts, 0); 547 if (Value *V = SimplifyDemandedVectorElts( 548 SrcVec, DemandedElts, UndefElts, 0 /* Depth */, 549 true /* AllowMultipleUsers */)) { 550 if (V != SrcVec) { 551 SrcVec->replaceAllUsesWith(V); 552 return &EI; 553 } 554 } 555 } 556 } 557 } 558 } 559 return nullptr; 560 } 561 562 /// If V is a shuffle of values that ONLY returns elements from either LHS or 563 /// RHS, return the shuffle mask and true. Otherwise, return false. 564 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 565 SmallVectorImpl<int> &Mask) { 566 assert(LHS->getType() == RHS->getType() && 567 "Invalid CollectSingleShuffleElements"); 568 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements(); 569 570 if (match(V, m_Undef())) { 571 Mask.assign(NumElts, -1); 572 return true; 573 } 574 575 if (V == LHS) { 576 for (unsigned i = 0; i != NumElts; ++i) 577 Mask.push_back(i); 578 return true; 579 } 580 581 if (V == RHS) { 582 for (unsigned i = 0; i != NumElts; ++i) 583 Mask.push_back(i + NumElts); 584 return true; 585 } 586 587 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 588 // If this is an insert of an extract from some other vector, include it. 589 Value *VecOp = IEI->getOperand(0); 590 Value *ScalarOp = IEI->getOperand(1); 591 Value *IdxOp = IEI->getOperand(2); 592 593 if (!isa<ConstantInt>(IdxOp)) 594 return false; 595 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 596 597 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 598 // We can handle this if the vector we are inserting into is 599 // transitively ok. 600 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 601 // If so, update the mask to reflect the inserted undef. 602 Mask[InsertedIdx] = -1; 603 return true; 604 } 605 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 606 if (isa<ConstantInt>(EI->getOperand(1))) { 607 unsigned ExtractedIdx = 608 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 609 unsigned NumLHSElts = 610 cast<FixedVectorType>(LHS->getType())->getNumElements(); 611 612 // This must be extracting from either LHS or RHS. 613 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 614 // We can handle this if the vector we are inserting into is 615 // transitively ok. 616 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 617 // If so, update the mask to reflect the inserted value. 618 if (EI->getOperand(0) == LHS) { 619 Mask[InsertedIdx % NumElts] = ExtractedIdx; 620 } else { 621 assert(EI->getOperand(0) == RHS); 622 Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts; 623 } 624 return true; 625 } 626 } 627 } 628 } 629 } 630 631 return false; 632 } 633 634 /// If we have insertion into a vector that is wider than the vector that we 635 /// are extracting from, try to widen the source vector to allow a single 636 /// shufflevector to replace one or more insert/extract pairs. 637 static void replaceExtractElements(InsertElementInst *InsElt, 638 ExtractElementInst *ExtElt, 639 InstCombinerImpl &IC) { 640 auto *InsVecType = cast<FixedVectorType>(InsElt->getType()); 641 auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType()); 642 unsigned NumInsElts = InsVecType->getNumElements(); 643 unsigned NumExtElts = ExtVecType->getNumElements(); 644 645 // The inserted-to vector must be wider than the extracted-from vector. 646 if (InsVecType->getElementType() != ExtVecType->getElementType() || 647 NumExtElts >= NumInsElts) 648 return; 649 650 // Create a shuffle mask to widen the extended-from vector using poison 651 // values. The mask selects all of the values of the original vector followed 652 // by as many poison values as needed to create a vector of the same length 653 // as the inserted-to vector. 654 SmallVector<int, 16> ExtendMask; 655 for (unsigned i = 0; i < NumExtElts; ++i) 656 ExtendMask.push_back(i); 657 for (unsigned i = NumExtElts; i < NumInsElts; ++i) 658 ExtendMask.push_back(-1); 659 660 Value *ExtVecOp = ExtElt->getVectorOperand(); 661 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 662 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 663 ? ExtVecOpInst->getParent() 664 : ExtElt->getParent(); 665 666 // TODO: This restriction matches the basic block check below when creating 667 // new extractelement instructions. If that limitation is removed, this one 668 // could also be removed. But for now, we just bail out to ensure that we 669 // will replace the extractelement instruction that is feeding our 670 // insertelement instruction. This allows the insertelement to then be 671 // replaced by a shufflevector. If the insertelement is not replaced, we can 672 // induce infinite looping because there's an optimization for extractelement 673 // that will delete our widening shuffle. This would trigger another attempt 674 // here to create that shuffle, and we spin forever. 675 if (InsertionBlock != InsElt->getParent()) 676 return; 677 678 // TODO: This restriction matches the check in visitInsertElementInst() and 679 // prevents an infinite loop caused by not turning the extract/insert pair 680 // into a shuffle. We really should not need either check, but we're lacking 681 // folds for shufflevectors because we're afraid to generate shuffle masks 682 // that the backend can't handle. 683 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 684 return; 685 686 auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask); 687 688 // Insert the new shuffle after the vector operand of the extract is defined 689 // (as long as it's not a PHI) or at the start of the basic block of the 690 // extract, so any subsequent extracts in the same basic block can use it. 691 // TODO: Insert before the earliest ExtractElementInst that is replaced. 692 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 693 WideVec->insertAfter(ExtVecOpInst); 694 else 695 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 696 697 // Replace extracts from the original narrow vector with extracts from the new 698 // wide vector. 699 for (User *U : ExtVecOp->users()) { 700 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 701 if (!OldExt || OldExt->getParent() != WideVec->getParent()) 702 continue; 703 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 704 NewExt->insertAfter(OldExt); 705 IC.replaceInstUsesWith(*OldExt, NewExt); 706 } 707 } 708 709 /// We are building a shuffle to create V, which is a sequence of insertelement, 710 /// extractelement pairs. If PermittedRHS is set, then we must either use it or 711 /// not rely on the second vector source. Return a std::pair containing the 712 /// left and right vectors of the proposed shuffle (or 0), and set the Mask 713 /// parameter as required. 714 /// 715 /// Note: we intentionally don't try to fold earlier shuffles since they have 716 /// often been chosen carefully to be efficiently implementable on the target. 717 using ShuffleOps = std::pair<Value *, Value *>; 718 719 static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask, 720 Value *PermittedRHS, 721 InstCombinerImpl &IC) { 722 assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 723 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements(); 724 725 if (match(V, m_Undef())) { 726 Mask.assign(NumElts, -1); 727 return std::make_pair( 728 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 729 } 730 731 if (isa<ConstantAggregateZero>(V)) { 732 Mask.assign(NumElts, 0); 733 return std::make_pair(V, nullptr); 734 } 735 736 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 737 // If this is an insert of an extract from some other vector, include it. 738 Value *VecOp = IEI->getOperand(0); 739 Value *ScalarOp = IEI->getOperand(1); 740 Value *IdxOp = IEI->getOperand(2); 741 742 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 743 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 744 unsigned ExtractedIdx = 745 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 746 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 747 748 // Either the extracted from or inserted into vector must be RHSVec, 749 // otherwise we'd end up with a shuffle of three inputs. 750 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 751 Value *RHS = EI->getOperand(0); 752 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 753 assert(LR.second == nullptr || LR.second == RHS); 754 755 if (LR.first->getType() != RHS->getType()) { 756 // Although we are giving up for now, see if we can create extracts 757 // that match the inserts for another round of combining. 758 replaceExtractElements(IEI, EI, IC); 759 760 // We tried our best, but we can't find anything compatible with RHS 761 // further up the chain. Return a trivial shuffle. 762 for (unsigned i = 0; i < NumElts; ++i) 763 Mask[i] = i; 764 return std::make_pair(V, nullptr); 765 } 766 767 unsigned NumLHSElts = 768 cast<FixedVectorType>(RHS->getType())->getNumElements(); 769 Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx; 770 return std::make_pair(LR.first, RHS); 771 } 772 773 if (VecOp == PermittedRHS) { 774 // We've gone as far as we can: anything on the other side of the 775 // extractelement will already have been converted into a shuffle. 776 unsigned NumLHSElts = 777 cast<FixedVectorType>(EI->getOperand(0)->getType()) 778 ->getNumElements(); 779 for (unsigned i = 0; i != NumElts; ++i) 780 Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i); 781 return std::make_pair(EI->getOperand(0), PermittedRHS); 782 } 783 784 // If this insertelement is a chain that comes from exactly these two 785 // vectors, return the vector and the effective shuffle. 786 if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 787 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 788 Mask)) 789 return std::make_pair(EI->getOperand(0), PermittedRHS); 790 } 791 } 792 } 793 794 // Otherwise, we can't do anything fancy. Return an identity vector. 795 for (unsigned i = 0; i != NumElts; ++i) 796 Mask.push_back(i); 797 return std::make_pair(V, nullptr); 798 } 799 800 /// Look for chain of insertvalue's that fully define an aggregate, and trace 801 /// back the values inserted, see if they are all were extractvalue'd from 802 /// the same source aggregate from the exact same element indexes. 803 /// If they were, just reuse the source aggregate. 804 /// This potentially deals with PHI indirections. 805 Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse( 806 InsertValueInst &OrigIVI) { 807 Type *AggTy = OrigIVI.getType(); 808 unsigned NumAggElts; 809 switch (AggTy->getTypeID()) { 810 case Type::StructTyID: 811 NumAggElts = AggTy->getStructNumElements(); 812 break; 813 case Type::ArrayTyID: 814 NumAggElts = AggTy->getArrayNumElements(); 815 break; 816 default: 817 llvm_unreachable("Unhandled aggregate type?"); 818 } 819 820 // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able 821 // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}), 822 // FIXME: any interesting patterns to be caught with larger limit? 823 assert(NumAggElts > 0 && "Aggregate should have elements."); 824 if (NumAggElts > 2) 825 return nullptr; 826 827 static constexpr auto NotFound = None; 828 static constexpr auto FoundMismatch = nullptr; 829 830 // Try to find a value of each element of an aggregate. 831 // FIXME: deal with more complex, not one-dimensional, aggregate types 832 SmallVector<Optional<Instruction *>, 2> AggElts(NumAggElts, NotFound); 833 834 // Do we know values for each element of the aggregate? 835 auto KnowAllElts = [&AggElts]() { 836 return all_of(AggElts, 837 [](Optional<Instruction *> Elt) { return Elt != NotFound; }); 838 }; 839 840 int Depth = 0; 841 842 // Arbitrary `insertvalue` visitation depth limit. Let's be okay with 843 // every element being overwritten twice, which should never happen. 844 static const int DepthLimit = 2 * NumAggElts; 845 846 // Recurse up the chain of `insertvalue` aggregate operands until either we've 847 // reconstructed full initializer or can't visit any more `insertvalue`'s. 848 for (InsertValueInst *CurrIVI = &OrigIVI; 849 Depth < DepthLimit && CurrIVI && !KnowAllElts(); 850 CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()), 851 ++Depth) { 852 auto *InsertedValue = 853 dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand()); 854 if (!InsertedValue) 855 return nullptr; // Inserted value must be produced by an instruction. 856 857 ArrayRef<unsigned int> Indices = CurrIVI->getIndices(); 858 859 // Don't bother with more than single-level aggregates. 860 if (Indices.size() != 1) 861 return nullptr; // FIXME: deal with more complex aggregates? 862 863 // Now, we may have already previously recorded the value for this element 864 // of an aggregate. If we did, that means the CurrIVI will later be 865 // overwritten with the already-recorded value. But if not, let's record it! 866 Optional<Instruction *> &Elt = AggElts[Indices.front()]; 867 Elt = Elt.getValueOr(InsertedValue); 868 869 // FIXME: should we handle chain-terminating undef base operand? 870 } 871 872 // Was that sufficient to deduce the full initializer for the aggregate? 873 if (!KnowAllElts()) 874 return nullptr; // Give up then. 875 876 // We now want to find the source[s] of the aggregate elements we've found. 877 // And with "source" we mean the original aggregate[s] from which 878 // the inserted elements were extracted. This may require PHI translation. 879 880 enum class AggregateDescription { 881 /// When analyzing the value that was inserted into an aggregate, we did 882 /// not manage to find defining `extractvalue` instruction to analyze. 883 NotFound, 884 /// When analyzing the value that was inserted into an aggregate, we did 885 /// manage to find defining `extractvalue` instruction[s], and everything 886 /// matched perfectly - aggregate type, element insertion/extraction index. 887 Found, 888 /// When analyzing the value that was inserted into an aggregate, we did 889 /// manage to find defining `extractvalue` instruction, but there was 890 /// a mismatch: either the source type from which the extraction was didn't 891 /// match the aggregate type into which the insertion was, 892 /// or the extraction/insertion channels mismatched, 893 /// or different elements had different source aggregates. 894 FoundMismatch 895 }; 896 auto Describe = [](Optional<Value *> SourceAggregate) { 897 if (SourceAggregate == NotFound) 898 return AggregateDescription::NotFound; 899 if (*SourceAggregate == FoundMismatch) 900 return AggregateDescription::FoundMismatch; 901 return AggregateDescription::Found; 902 }; 903 904 // Given the value \p Elt that was being inserted into element \p EltIdx of an 905 // aggregate AggTy, see if \p Elt was originally defined by an 906 // appropriate extractvalue (same element index, same aggregate type). 907 // If found, return the source aggregate from which the extraction was. 908 // If \p PredBB is provided, does PHI translation of an \p Elt first. 909 auto FindSourceAggregate = 910 [&](Instruction *Elt, unsigned EltIdx, Optional<BasicBlock *> UseBB, 911 Optional<BasicBlock *> PredBB) -> Optional<Value *> { 912 // For now(?), only deal with, at most, a single level of PHI indirection. 913 if (UseBB && PredBB) 914 Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB)); 915 // FIXME: deal with multiple levels of PHI indirection? 916 917 // Did we find an extraction? 918 auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt); 919 if (!EVI) 920 return NotFound; 921 922 Value *SourceAggregate = EVI->getAggregateOperand(); 923 924 // Is the extraction from the same type into which the insertion was? 925 if (SourceAggregate->getType() != AggTy) 926 return FoundMismatch; 927 // And the element index doesn't change between extraction and insertion? 928 if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front()) 929 return FoundMismatch; 930 931 return SourceAggregate; // AggregateDescription::Found 932 }; 933 934 // Given elements AggElts that were constructing an aggregate OrigIVI, 935 // see if we can find appropriate source aggregate for each of the elements, 936 // and see it's the same aggregate for each element. If so, return it. 937 auto FindCommonSourceAggregate = 938 [&](Optional<BasicBlock *> UseBB, 939 Optional<BasicBlock *> PredBB) -> Optional<Value *> { 940 Optional<Value *> SourceAggregate; 941 942 for (auto I : enumerate(AggElts)) { 943 assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch && 944 "We don't store nullptr in SourceAggregate!"); 945 assert((Describe(SourceAggregate) == AggregateDescription::Found) == 946 (I.index() != 0) && 947 "SourceAggregate should be valid after the first element,"); 948 949 // For this element, is there a plausible source aggregate? 950 // FIXME: we could special-case undef element, IFF we know that in the 951 // source aggregate said element isn't poison. 952 Optional<Value *> SourceAggregateForElement = 953 FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB); 954 955 // Okay, what have we found? Does that correlate with previous findings? 956 957 // Regardless of whether or not we have previously found source 958 // aggregate for previous elements (if any), if we didn't find one for 959 // this element, passthrough whatever we have just found. 960 if (Describe(SourceAggregateForElement) != AggregateDescription::Found) 961 return SourceAggregateForElement; 962 963 // Okay, we have found source aggregate for this element. 964 // Let's see what we already know from previous elements, if any. 965 switch (Describe(SourceAggregate)) { 966 case AggregateDescription::NotFound: 967 // This is apparently the first element that we have examined. 968 SourceAggregate = SourceAggregateForElement; // Record the aggregate! 969 continue; // Great, now look at next element. 970 case AggregateDescription::Found: 971 // We have previously already successfully examined other elements. 972 // Is this the same source aggregate we've found for other elements? 973 if (*SourceAggregateForElement != *SourceAggregate) 974 return FoundMismatch; 975 continue; // Still the same aggregate, look at next element. 976 case AggregateDescription::FoundMismatch: 977 llvm_unreachable("Can't happen. We would have early-exited then."); 978 }; 979 } 980 981 assert(Describe(SourceAggregate) == AggregateDescription::Found && 982 "Must be a valid Value"); 983 return *SourceAggregate; 984 }; 985 986 Optional<Value *> SourceAggregate; 987 988 // Can we find the source aggregate without looking at predecessors? 989 SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/None, /*PredBB=*/None); 990 if (Describe(SourceAggregate) != AggregateDescription::NotFound) { 991 if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch) 992 return nullptr; // Conflicting source aggregates! 993 ++NumAggregateReconstructionsSimplified; 994 return replaceInstUsesWith(OrigIVI, *SourceAggregate); 995 } 996 997 // Okay, apparently we need to look at predecessors. 998 999 // We should be smart about picking the "use" basic block, which will be the 1000 // merge point for aggregate, where we'll insert the final PHI that will be 1001 // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice. 1002 // We should look in which blocks each of the AggElts is being defined, 1003 // they all should be defined in the same basic block. 1004 BasicBlock *UseBB = nullptr; 1005 1006 for (const Optional<Instruction *> &I : AggElts) { 1007 BasicBlock *BB = (*I)->getParent(); 1008 // If it's the first instruction we've encountered, record the basic block. 1009 if (!UseBB) { 1010 UseBB = BB; 1011 continue; 1012 } 1013 // Otherwise, this must be the same basic block we've seen previously. 1014 if (UseBB != BB) 1015 return nullptr; 1016 } 1017 1018 // If *all* of the elements are basic-block-independent, meaning they are 1019 // either function arguments, or constant expressions, then if we didn't 1020 // handle them without predecessor-aware handling, we won't handle them now. 1021 if (!UseBB) 1022 return nullptr; 1023 1024 // If we didn't manage to find source aggregate without looking at 1025 // predecessors, and there are no predecessors to look at, then we're done. 1026 if (pred_empty(UseBB)) 1027 return nullptr; 1028 1029 // Arbitrary predecessor count limit. 1030 static const int PredCountLimit = 64; 1031 1032 // Cache the (non-uniqified!) list of predecessors in a vector, 1033 // checking the limit at the same time for efficiency. 1034 SmallVector<BasicBlock *, 4> Preds; // May have duplicates! 1035 for (BasicBlock *Pred : predecessors(UseBB)) { 1036 // Don't bother if there are too many predecessors. 1037 if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once? 1038 return nullptr; 1039 Preds.emplace_back(Pred); 1040 } 1041 1042 // For each predecessor, what is the source aggregate, 1043 // from which all the elements were originally extracted from? 1044 // Note that we want for the map to have stable iteration order! 1045 SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates; 1046 for (BasicBlock *Pred : Preds) { 1047 std::pair<decltype(SourceAggregates)::iterator, bool> IV = 1048 SourceAggregates.insert({Pred, nullptr}); 1049 // Did we already evaluate this predecessor? 1050 if (!IV.second) 1051 continue; 1052 1053 // Let's hope that when coming from predecessor Pred, all elements of the 1054 // aggregate produced by OrigIVI must have been originally extracted from 1055 // the same aggregate. Is that so? Can we find said original aggregate? 1056 SourceAggregate = FindCommonSourceAggregate(UseBB, Pred); 1057 if (Describe(SourceAggregate) != AggregateDescription::Found) 1058 return nullptr; // Give up. 1059 IV.first->second = *SourceAggregate; 1060 } 1061 1062 // All good! Now we just need to thread the source aggregates here. 1063 // Note that we have to insert the new PHI here, ourselves, because we can't 1064 // rely on InstCombinerImpl::run() inserting it into the right basic block. 1065 // Note that the same block can be a predecessor more than once, 1066 // and we need to preserve that invariant for the PHI node. 1067 BuilderTy::InsertPointGuard Guard(Builder); 1068 Builder.SetInsertPoint(UseBB->getFirstNonPHI()); 1069 auto *PHI = 1070 Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged"); 1071 for (BasicBlock *Pred : Preds) 1072 PHI->addIncoming(SourceAggregates[Pred], Pred); 1073 1074 ++NumAggregateReconstructionsSimplified; 1075 return replaceInstUsesWith(OrigIVI, PHI); 1076 } 1077 1078 /// Try to find redundant insertvalue instructions, like the following ones: 1079 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 1080 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 1081 /// Here the second instruction inserts values at the same indices, as the 1082 /// first one, making the first one redundant. 1083 /// It should be transformed to: 1084 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 1085 Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) { 1086 bool IsRedundant = false; 1087 ArrayRef<unsigned int> FirstIndices = I.getIndices(); 1088 1089 // If there is a chain of insertvalue instructions (each of them except the 1090 // last one has only one use and it's another insertvalue insn from this 1091 // chain), check if any of the 'children' uses the same indices as the first 1092 // instruction. In this case, the first one is redundant. 1093 Value *V = &I; 1094 unsigned Depth = 0; 1095 while (V->hasOneUse() && Depth < 10) { 1096 User *U = V->user_back(); 1097 auto UserInsInst = dyn_cast<InsertValueInst>(U); 1098 if (!UserInsInst || U->getOperand(0) != V) 1099 break; 1100 if (UserInsInst->getIndices() == FirstIndices) { 1101 IsRedundant = true; 1102 break; 1103 } 1104 V = UserInsInst; 1105 Depth++; 1106 } 1107 1108 if (IsRedundant) 1109 return replaceInstUsesWith(I, I.getOperand(0)); 1110 1111 if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I)) 1112 return NewI; 1113 1114 return nullptr; 1115 } 1116 1117 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 1118 // Can not analyze scalable type, the number of elements is not a compile-time 1119 // constant. 1120 if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType())) 1121 return false; 1122 1123 int MaskSize = Shuf.getShuffleMask().size(); 1124 int VecSize = 1125 cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements(); 1126 1127 // A vector select does not change the size of the operands. 1128 if (MaskSize != VecSize) 1129 return false; 1130 1131 // Each mask element must be undefined or choose a vector element from one of 1132 // the source operands without crossing vector lanes. 1133 for (int i = 0; i != MaskSize; ++i) { 1134 int Elt = Shuf.getMaskValue(i); 1135 if (Elt != -1 && Elt != i && Elt != i + VecSize) 1136 return false; 1137 } 1138 1139 return true; 1140 } 1141 1142 /// Turn a chain of inserts that splats a value into an insert + shuffle: 1143 /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> 1144 /// shufflevector(insertelt(X, %k, 0), poison, zero) 1145 static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) { 1146 // We are interested in the last insert in a chain. So if this insert has a 1147 // single user and that user is an insert, bail. 1148 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) 1149 return nullptr; 1150 1151 VectorType *VecTy = InsElt.getType(); 1152 // Can not handle scalable type, the number of elements is not a compile-time 1153 // constant. 1154 if (isa<ScalableVectorType>(VecTy)) 1155 return nullptr; 1156 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1157 1158 // Do not try to do this for a one-element vector, since that's a nop, 1159 // and will cause an inf-loop. 1160 if (NumElements == 1) 1161 return nullptr; 1162 1163 Value *SplatVal = InsElt.getOperand(1); 1164 InsertElementInst *CurrIE = &InsElt; 1165 SmallBitVector ElementPresent(NumElements, false); 1166 InsertElementInst *FirstIE = nullptr; 1167 1168 // Walk the chain backwards, keeping track of which indices we inserted into, 1169 // until we hit something that isn't an insert of the splatted value. 1170 while (CurrIE) { 1171 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); 1172 if (!Idx || CurrIE->getOperand(1) != SplatVal) 1173 return nullptr; 1174 1175 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); 1176 // Check none of the intermediate steps have any additional uses, except 1177 // for the root insertelement instruction, which can be re-used, if it 1178 // inserts at position 0. 1179 if (CurrIE != &InsElt && 1180 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero()))) 1181 return nullptr; 1182 1183 ElementPresent[Idx->getZExtValue()] = true; 1184 FirstIE = CurrIE; 1185 CurrIE = NextIE; 1186 } 1187 1188 // If this is just a single insertelement (not a sequence), we are done. 1189 if (FirstIE == &InsElt) 1190 return nullptr; 1191 1192 // If we are not inserting into an undef vector, make sure we've seen an 1193 // insert into every element. 1194 // TODO: If the base vector is not undef, it might be better to create a splat 1195 // and then a select-shuffle (blend) with the base vector. 1196 if (!match(FirstIE->getOperand(0), m_Undef())) 1197 if (!ElementPresent.all()) 1198 return nullptr; 1199 1200 // Create the insert + shuffle. 1201 Type *Int32Ty = Type::getInt32Ty(InsElt.getContext()); 1202 PoisonValue *PoisonVec = PoisonValue::get(VecTy); 1203 Constant *Zero = ConstantInt::get(Int32Ty, 0); 1204 if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero()) 1205 FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt); 1206 1207 // Splat from element 0, but replace absent elements with undef in the mask. 1208 SmallVector<int, 16> Mask(NumElements, 0); 1209 for (unsigned i = 0; i != NumElements; ++i) 1210 if (!ElementPresent[i]) 1211 Mask[i] = -1; 1212 1213 return new ShuffleVectorInst(FirstIE, Mask); 1214 } 1215 1216 /// Try to fold an insert element into an existing splat shuffle by changing 1217 /// the shuffle's mask to include the index of this insert element. 1218 static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) { 1219 // Check if the vector operand of this insert is a canonical splat shuffle. 1220 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); 1221 if (!Shuf || !Shuf->isZeroEltSplat()) 1222 return nullptr; 1223 1224 // Bail out early if shuffle is scalable type. The number of elements in 1225 // shuffle mask is unknown at compile-time. 1226 if (isa<ScalableVectorType>(Shuf->getType())) 1227 return nullptr; 1228 1229 // Check for a constant insertion index. 1230 uint64_t IdxC; 1231 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) 1232 return nullptr; 1233 1234 // Check if the splat shuffle's input is the same as this insert's scalar op. 1235 Value *X = InsElt.getOperand(1); 1236 Value *Op0 = Shuf->getOperand(0); 1237 if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt()))) 1238 return nullptr; 1239 1240 // Replace the shuffle mask element at the index of this insert with a zero. 1241 // For example: 1242 // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1 1243 // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef> 1244 unsigned NumMaskElts = 1245 cast<FixedVectorType>(Shuf->getType())->getNumElements(); 1246 SmallVector<int, 16> NewMask(NumMaskElts); 1247 for (unsigned i = 0; i != NumMaskElts; ++i) 1248 NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i); 1249 1250 return new ShuffleVectorInst(Op0, NewMask); 1251 } 1252 1253 /// Try to fold an extract+insert element into an existing identity shuffle by 1254 /// changing the shuffle's mask to include the index of this insert element. 1255 static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) { 1256 // Check if the vector operand of this insert is an identity shuffle. 1257 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0)); 1258 if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) || 1259 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding())) 1260 return nullptr; 1261 1262 // Bail out early if shuffle is scalable type. The number of elements in 1263 // shuffle mask is unknown at compile-time. 1264 if (isa<ScalableVectorType>(Shuf->getType())) 1265 return nullptr; 1266 1267 // Check for a constant insertion index. 1268 uint64_t IdxC; 1269 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC))) 1270 return nullptr; 1271 1272 // Check if this insert's scalar op is extracted from the identity shuffle's 1273 // input vector. 1274 Value *Scalar = InsElt.getOperand(1); 1275 Value *X = Shuf->getOperand(0); 1276 if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC)))) 1277 return nullptr; 1278 1279 // Replace the shuffle mask element at the index of this extract+insert with 1280 // that same index value. 1281 // For example: 1282 // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask' 1283 unsigned NumMaskElts = 1284 cast<FixedVectorType>(Shuf->getType())->getNumElements(); 1285 SmallVector<int, 16> NewMask(NumMaskElts); 1286 ArrayRef<int> OldMask = Shuf->getShuffleMask(); 1287 for (unsigned i = 0; i != NumMaskElts; ++i) { 1288 if (i != IdxC) { 1289 // All mask elements besides the inserted element remain the same. 1290 NewMask[i] = OldMask[i]; 1291 } else if (OldMask[i] == (int)IdxC) { 1292 // If the mask element was already set, there's nothing to do 1293 // (demanded elements analysis may unset it later). 1294 return nullptr; 1295 } else { 1296 assert(OldMask[i] == UndefMaskElem && 1297 "Unexpected shuffle mask element for identity shuffle"); 1298 NewMask[i] = IdxC; 1299 } 1300 } 1301 1302 return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask); 1303 } 1304 1305 /// If we have an insertelement instruction feeding into another insertelement 1306 /// and the 2nd is inserting a constant into the vector, canonicalize that 1307 /// constant insertion before the insertion of a variable: 1308 /// 1309 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> 1310 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 1311 /// 1312 /// This has the potential of eliminating the 2nd insertelement instruction 1313 /// via constant folding of the scalar constant into a vector constant. 1314 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, 1315 InstCombiner::BuilderTy &Builder) { 1316 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); 1317 if (!InsElt1 || !InsElt1->hasOneUse()) 1318 return nullptr; 1319 1320 Value *X, *Y; 1321 Constant *ScalarC; 1322 ConstantInt *IdxC1, *IdxC2; 1323 if (match(InsElt1->getOperand(0), m_Value(X)) && 1324 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && 1325 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && 1326 match(InsElt2.getOperand(1), m_Constant(ScalarC)) && 1327 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { 1328 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); 1329 return InsertElementInst::Create(NewInsElt1, Y, IdxC1); 1330 } 1331 1332 return nullptr; 1333 } 1334 1335 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 1336 /// --> shufflevector X, CVec', Mask' 1337 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 1338 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 1339 // Bail out if the parent has more than one use. In that case, we'd be 1340 // replacing the insertelt with a shuffle, and that's not a clear win. 1341 if (!Inst || !Inst->hasOneUse()) 1342 return nullptr; 1343 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 1344 // The shuffle must have a constant vector operand. The insertelt must have 1345 // a constant scalar being inserted at a constant position in the vector. 1346 Constant *ShufConstVec, *InsEltScalar; 1347 uint64_t InsEltIndex; 1348 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 1349 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 1350 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 1351 return nullptr; 1352 1353 // Adding an element to an arbitrary shuffle could be expensive, but a 1354 // shuffle that selects elements from vectors without crossing lanes is 1355 // assumed cheap. 1356 // If we're just adding a constant into that shuffle, it will still be 1357 // cheap. 1358 if (!isShuffleEquivalentToSelect(*Shuf)) 1359 return nullptr; 1360 1361 // From the above 'select' check, we know that the mask has the same number 1362 // of elements as the vector input operands. We also know that each constant 1363 // input element is used in its lane and can not be used more than once by 1364 // the shuffle. Therefore, replace the constant in the shuffle's constant 1365 // vector with the insertelt constant. Replace the constant in the shuffle's 1366 // mask vector with the insertelt index plus the length of the vector 1367 // (because the constant vector operand of a shuffle is always the 2nd 1368 // operand). 1369 ArrayRef<int> Mask = Shuf->getShuffleMask(); 1370 unsigned NumElts = Mask.size(); 1371 SmallVector<Constant *, 16> NewShufElts(NumElts); 1372 SmallVector<int, 16> NewMaskElts(NumElts); 1373 for (unsigned I = 0; I != NumElts; ++I) { 1374 if (I == InsEltIndex) { 1375 NewShufElts[I] = InsEltScalar; 1376 NewMaskElts[I] = InsEltIndex + NumElts; 1377 } else { 1378 // Copy over the existing values. 1379 NewShufElts[I] = ShufConstVec->getAggregateElement(I); 1380 NewMaskElts[I] = Mask[I]; 1381 } 1382 1383 // Bail if we failed to find an element. 1384 if (!NewShufElts[I]) 1385 return nullptr; 1386 } 1387 1388 // Create new operands for a shuffle that includes the constant of the 1389 // original insertelt. The old shuffle will be dead now. 1390 return new ShuffleVectorInst(Shuf->getOperand(0), 1391 ConstantVector::get(NewShufElts), NewMaskElts); 1392 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 1393 // Transform sequences of insertelements ops with constant data/indexes into 1394 // a single shuffle op. 1395 // Can not handle scalable type, the number of elements needed to create 1396 // shuffle mask is not a compile-time constant. 1397 if (isa<ScalableVectorType>(InsElt.getType())) 1398 return nullptr; 1399 unsigned NumElts = 1400 cast<FixedVectorType>(InsElt.getType())->getNumElements(); 1401 1402 uint64_t InsertIdx[2]; 1403 Constant *Val[2]; 1404 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 1405 !match(InsElt.getOperand(1), m_Constant(Val[0])) || 1406 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 1407 !match(IEI->getOperand(1), m_Constant(Val[1]))) 1408 return nullptr; 1409 SmallVector<Constant *, 16> Values(NumElts); 1410 SmallVector<int, 16> Mask(NumElts); 1411 auto ValI = std::begin(Val); 1412 // Generate new constant vector and mask. 1413 // We have 2 values/masks from the insertelements instructions. Insert them 1414 // into new value/mask vectors. 1415 for (uint64_t I : InsertIdx) { 1416 if (!Values[I]) { 1417 Values[I] = *ValI; 1418 Mask[I] = NumElts + I; 1419 } 1420 ++ValI; 1421 } 1422 // Remaining values are filled with 'undef' values. 1423 for (unsigned I = 0; I < NumElts; ++I) { 1424 if (!Values[I]) { 1425 Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 1426 Mask[I] = I; 1427 } 1428 } 1429 // Create new operands for a shuffle that includes the constant of the 1430 // original insertelt. 1431 return new ShuffleVectorInst(IEI->getOperand(0), 1432 ConstantVector::get(Values), Mask); 1433 } 1434 return nullptr; 1435 } 1436 1437 /// If both the base vector and the inserted element are extended from the same 1438 /// type, do the insert element in the narrow source type followed by extend. 1439 /// TODO: This can be extended to include other cast opcodes, but particularly 1440 /// if we create a wider insertelement, make sure codegen is not harmed. 1441 static Instruction *narrowInsElt(InsertElementInst &InsElt, 1442 InstCombiner::BuilderTy &Builder) { 1443 // We are creating a vector extend. If the original vector extend has another 1444 // use, that would mean we end up with 2 vector extends, so avoid that. 1445 // TODO: We could ease the use-clause to "if at least one op has one use" 1446 // (assuming that the source types match - see next TODO comment). 1447 Value *Vec = InsElt.getOperand(0); 1448 if (!Vec->hasOneUse()) 1449 return nullptr; 1450 1451 Value *Scalar = InsElt.getOperand(1); 1452 Value *X, *Y; 1453 CastInst::CastOps CastOpcode; 1454 if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y)))) 1455 CastOpcode = Instruction::FPExt; 1456 else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y)))) 1457 CastOpcode = Instruction::SExt; 1458 else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y)))) 1459 CastOpcode = Instruction::ZExt; 1460 else 1461 return nullptr; 1462 1463 // TODO: We can allow mismatched types by creating an intermediate cast. 1464 if (X->getType()->getScalarType() != Y->getType()) 1465 return nullptr; 1466 1467 // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index) 1468 Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2)); 1469 return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType()); 1470 } 1471 1472 Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) { 1473 Value *VecOp = IE.getOperand(0); 1474 Value *ScalarOp = IE.getOperand(1); 1475 Value *IdxOp = IE.getOperand(2); 1476 1477 if (auto *V = SimplifyInsertElementInst( 1478 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE))) 1479 return replaceInstUsesWith(IE, V); 1480 1481 // If the scalar is bitcast and inserted into undef, do the insert in the 1482 // source type followed by bitcast. 1483 // TODO: Generalize for insert into any constant, not just undef? 1484 Value *ScalarSrc; 1485 if (match(VecOp, m_Undef()) && 1486 match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) && 1487 (ScalarSrc->getType()->isIntegerTy() || 1488 ScalarSrc->getType()->isFloatingPointTy())) { 1489 // inselt undef, (bitcast ScalarSrc), IdxOp --> 1490 // bitcast (inselt undef, ScalarSrc, IdxOp) 1491 Type *ScalarTy = ScalarSrc->getType(); 1492 Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount()); 1493 UndefValue *NewUndef = UndefValue::get(VecTy); 1494 Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp); 1495 return new BitCastInst(NewInsElt, IE.getType()); 1496 } 1497 1498 // If the vector and scalar are both bitcast from the same element type, do 1499 // the insert in that source type followed by bitcast. 1500 Value *VecSrc; 1501 if (match(VecOp, m_BitCast(m_Value(VecSrc))) && 1502 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) && 1503 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) && 1504 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() && 1505 cast<VectorType>(VecSrc->getType())->getElementType() == 1506 ScalarSrc->getType()) { 1507 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp --> 1508 // bitcast (inselt VecSrc, ScalarSrc, IdxOp) 1509 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp); 1510 return new BitCastInst(NewInsElt, IE.getType()); 1511 } 1512 1513 // If the inserted element was extracted from some other fixed-length vector 1514 // and both indexes are valid constants, try to turn this into a shuffle. 1515 // Can not handle scalable vector type, the number of elements needed to 1516 // create shuffle mask is not a compile-time constant. 1517 uint64_t InsertedIdx, ExtractedIdx; 1518 Value *ExtVecOp; 1519 if (isa<FixedVectorType>(IE.getType()) && 1520 match(IdxOp, m_ConstantInt(InsertedIdx)) && 1521 match(ScalarOp, 1522 m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) && 1523 isa<FixedVectorType>(ExtVecOp->getType()) && 1524 ExtractedIdx < 1525 cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) { 1526 // TODO: Looking at the user(s) to determine if this insert is a 1527 // fold-to-shuffle opportunity does not match the usual instcombine 1528 // constraints. We should decide if the transform is worthy based only 1529 // on this instruction and its operands, but that may not work currently. 1530 // 1531 // Here, we are trying to avoid creating shuffles before reaching 1532 // the end of a chain of extract-insert pairs. This is complicated because 1533 // we do not generally form arbitrary shuffle masks in instcombine 1534 // (because those may codegen poorly), but collectShuffleElements() does 1535 // exactly that. 1536 // 1537 // The rules for determining what is an acceptable target-independent 1538 // shuffle mask are fuzzy because they evolve based on the backend's 1539 // capabilities and real-world impact. 1540 auto isShuffleRootCandidate = [](InsertElementInst &Insert) { 1541 if (!Insert.hasOneUse()) 1542 return true; 1543 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back()); 1544 if (!InsertUser) 1545 return true; 1546 return false; 1547 }; 1548 1549 // Try to form a shuffle from a chain of extract-insert ops. 1550 if (isShuffleRootCandidate(IE)) { 1551 SmallVector<int, 16> Mask; 1552 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 1553 1554 // The proposed shuffle may be trivial, in which case we shouldn't 1555 // perform the combine. 1556 if (LR.first != &IE && LR.second != &IE) { 1557 // We now have a shuffle of LHS, RHS, Mask. 1558 if (LR.second == nullptr) 1559 LR.second = UndefValue::get(LR.first->getType()); 1560 return new ShuffleVectorInst(LR.first, LR.second, Mask); 1561 } 1562 } 1563 } 1564 1565 if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) { 1566 unsigned VWidth = VecTy->getNumElements(); 1567 APInt UndefElts(VWidth, 0); 1568 APInt AllOnesEltMask(APInt::getAllOnes(VWidth)); 1569 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 1570 if (V != &IE) 1571 return replaceInstUsesWith(IE, V); 1572 return &IE; 1573 } 1574 } 1575 1576 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 1577 return Shuf; 1578 1579 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) 1580 return NewInsElt; 1581 1582 if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE)) 1583 return Broadcast; 1584 1585 if (Instruction *Splat = foldInsEltIntoSplat(IE)) 1586 return Splat; 1587 1588 if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE)) 1589 return IdentityShuf; 1590 1591 if (Instruction *Ext = narrowInsElt(IE, Builder)) 1592 return Ext; 1593 1594 return nullptr; 1595 } 1596 1597 /// Return true if we can evaluate the specified expression tree if the vector 1598 /// elements were shuffled in a different order. 1599 static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask, 1600 unsigned Depth = 5) { 1601 // We can always reorder the elements of a constant. 1602 if (isa<Constant>(V)) 1603 return true; 1604 1605 // We won't reorder vector arguments. No IPO here. 1606 Instruction *I = dyn_cast<Instruction>(V); 1607 if (!I) return false; 1608 1609 // Two users may expect different orders of the elements. Don't try it. 1610 if (!I->hasOneUse()) 1611 return false; 1612 1613 if (Depth == 0) return false; 1614 1615 switch (I->getOpcode()) { 1616 case Instruction::UDiv: 1617 case Instruction::SDiv: 1618 case Instruction::URem: 1619 case Instruction::SRem: 1620 // Propagating an undefined shuffle mask element to integer div/rem is not 1621 // allowed because those opcodes can create immediate undefined behavior 1622 // from an undefined element in an operand. 1623 if (llvm::is_contained(Mask, -1)) 1624 return false; 1625 LLVM_FALLTHROUGH; 1626 case Instruction::Add: 1627 case Instruction::FAdd: 1628 case Instruction::Sub: 1629 case Instruction::FSub: 1630 case Instruction::Mul: 1631 case Instruction::FMul: 1632 case Instruction::FDiv: 1633 case Instruction::FRem: 1634 case Instruction::Shl: 1635 case Instruction::LShr: 1636 case Instruction::AShr: 1637 case Instruction::And: 1638 case Instruction::Or: 1639 case Instruction::Xor: 1640 case Instruction::ICmp: 1641 case Instruction::FCmp: 1642 case Instruction::Trunc: 1643 case Instruction::ZExt: 1644 case Instruction::SExt: 1645 case Instruction::FPToUI: 1646 case Instruction::FPToSI: 1647 case Instruction::UIToFP: 1648 case Instruction::SIToFP: 1649 case Instruction::FPTrunc: 1650 case Instruction::FPExt: 1651 case Instruction::GetElementPtr: { 1652 // Bail out if we would create longer vector ops. We could allow creating 1653 // longer vector ops, but that may result in more expensive codegen. 1654 Type *ITy = I->getType(); 1655 if (ITy->isVectorTy() && 1656 Mask.size() > cast<FixedVectorType>(ITy)->getNumElements()) 1657 return false; 1658 for (Value *Operand : I->operands()) { 1659 if (!canEvaluateShuffled(Operand, Mask, Depth - 1)) 1660 return false; 1661 } 1662 return true; 1663 } 1664 case Instruction::InsertElement: { 1665 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 1666 if (!CI) return false; 1667 int ElementNumber = CI->getLimitedValue(); 1668 1669 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 1670 // can't put an element into multiple indices. 1671 bool SeenOnce = false; 1672 for (int i = 0, e = Mask.size(); i != e; ++i) { 1673 if (Mask[i] == ElementNumber) { 1674 if (SeenOnce) 1675 return false; 1676 SeenOnce = true; 1677 } 1678 } 1679 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1); 1680 } 1681 } 1682 return false; 1683 } 1684 1685 /// Rebuild a new instruction just like 'I' but with the new operands given. 1686 /// In the event of type mismatch, the type of the operands is correct. 1687 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 1688 // We don't want to use the IRBuilder here because we want the replacement 1689 // instructions to appear next to 'I', not the builder's insertion point. 1690 switch (I->getOpcode()) { 1691 case Instruction::Add: 1692 case Instruction::FAdd: 1693 case Instruction::Sub: 1694 case Instruction::FSub: 1695 case Instruction::Mul: 1696 case Instruction::FMul: 1697 case Instruction::UDiv: 1698 case Instruction::SDiv: 1699 case Instruction::FDiv: 1700 case Instruction::URem: 1701 case Instruction::SRem: 1702 case Instruction::FRem: 1703 case Instruction::Shl: 1704 case Instruction::LShr: 1705 case Instruction::AShr: 1706 case Instruction::And: 1707 case Instruction::Or: 1708 case Instruction::Xor: { 1709 BinaryOperator *BO = cast<BinaryOperator>(I); 1710 assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 1711 BinaryOperator *New = 1712 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 1713 NewOps[0], NewOps[1], "", BO); 1714 if (isa<OverflowingBinaryOperator>(BO)) { 1715 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 1716 New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 1717 } 1718 if (isa<PossiblyExactOperator>(BO)) { 1719 New->setIsExact(BO->isExact()); 1720 } 1721 if (isa<FPMathOperator>(BO)) 1722 New->copyFastMathFlags(I); 1723 return New; 1724 } 1725 case Instruction::ICmp: 1726 assert(NewOps.size() == 2 && "icmp with #ops != 2"); 1727 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 1728 NewOps[0], NewOps[1]); 1729 case Instruction::FCmp: 1730 assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 1731 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 1732 NewOps[0], NewOps[1]); 1733 case Instruction::Trunc: 1734 case Instruction::ZExt: 1735 case Instruction::SExt: 1736 case Instruction::FPToUI: 1737 case Instruction::FPToSI: 1738 case Instruction::UIToFP: 1739 case Instruction::SIToFP: 1740 case Instruction::FPTrunc: 1741 case Instruction::FPExt: { 1742 // It's possible that the mask has a different number of elements from 1743 // the original cast. We recompute the destination type to match the mask. 1744 Type *DestTy = VectorType::get( 1745 I->getType()->getScalarType(), 1746 cast<VectorType>(NewOps[0]->getType())->getElementCount()); 1747 assert(NewOps.size() == 1 && "cast with #ops != 1"); 1748 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 1749 "", I); 1750 } 1751 case Instruction::GetElementPtr: { 1752 Value *Ptr = NewOps[0]; 1753 ArrayRef<Value*> Idx = NewOps.slice(1); 1754 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1755 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 1756 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 1757 return GEP; 1758 } 1759 } 1760 llvm_unreachable("failed to rebuild vector instructions"); 1761 } 1762 1763 static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 1764 // Mask.size() does not need to be equal to the number of vector elements. 1765 1766 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 1767 Type *EltTy = V->getType()->getScalarType(); 1768 Type *I32Ty = IntegerType::getInt32Ty(V->getContext()); 1769 if (match(V, m_Undef())) 1770 return UndefValue::get(FixedVectorType::get(EltTy, Mask.size())); 1771 1772 if (isa<ConstantAggregateZero>(V)) 1773 return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size())); 1774 1775 if (Constant *C = dyn_cast<Constant>(V)) 1776 return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()), 1777 Mask); 1778 1779 Instruction *I = cast<Instruction>(V); 1780 switch (I->getOpcode()) { 1781 case Instruction::Add: 1782 case Instruction::FAdd: 1783 case Instruction::Sub: 1784 case Instruction::FSub: 1785 case Instruction::Mul: 1786 case Instruction::FMul: 1787 case Instruction::UDiv: 1788 case Instruction::SDiv: 1789 case Instruction::FDiv: 1790 case Instruction::URem: 1791 case Instruction::SRem: 1792 case Instruction::FRem: 1793 case Instruction::Shl: 1794 case Instruction::LShr: 1795 case Instruction::AShr: 1796 case Instruction::And: 1797 case Instruction::Or: 1798 case Instruction::Xor: 1799 case Instruction::ICmp: 1800 case Instruction::FCmp: 1801 case Instruction::Trunc: 1802 case Instruction::ZExt: 1803 case Instruction::SExt: 1804 case Instruction::FPToUI: 1805 case Instruction::FPToSI: 1806 case Instruction::UIToFP: 1807 case Instruction::SIToFP: 1808 case Instruction::FPTrunc: 1809 case Instruction::FPExt: 1810 case Instruction::Select: 1811 case Instruction::GetElementPtr: { 1812 SmallVector<Value*, 8> NewOps; 1813 bool NeedsRebuild = 1814 (Mask.size() != 1815 cast<FixedVectorType>(I->getType())->getNumElements()); 1816 for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 1817 Value *V; 1818 // Recursively call evaluateInDifferentElementOrder on vector arguments 1819 // as well. E.g. GetElementPtr may have scalar operands even if the 1820 // return value is a vector, so we need to examine the operand type. 1821 if (I->getOperand(i)->getType()->isVectorTy()) 1822 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask); 1823 else 1824 V = I->getOperand(i); 1825 NewOps.push_back(V); 1826 NeedsRebuild |= (V != I->getOperand(i)); 1827 } 1828 if (NeedsRebuild) { 1829 return buildNew(I, NewOps); 1830 } 1831 return I; 1832 } 1833 case Instruction::InsertElement: { 1834 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 1835 1836 // The insertelement was inserting at Element. Figure out which element 1837 // that becomes after shuffling. The answer is guaranteed to be unique 1838 // by CanEvaluateShuffled. 1839 bool Found = false; 1840 int Index = 0; 1841 for (int e = Mask.size(); Index != e; ++Index) { 1842 if (Mask[Index] == Element) { 1843 Found = true; 1844 break; 1845 } 1846 } 1847 1848 // If element is not in Mask, no need to handle the operand 1 (element to 1849 // be inserted). Just evaluate values in operand 0 according to Mask. 1850 if (!Found) 1851 return evaluateInDifferentElementOrder(I->getOperand(0), Mask); 1852 1853 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask); 1854 return InsertElementInst::Create(V, I->getOperand(1), 1855 ConstantInt::get(I32Ty, Index), "", I); 1856 } 1857 } 1858 llvm_unreachable("failed to reorder elements of vector instruction!"); 1859 } 1860 1861 // Returns true if the shuffle is extracting a contiguous range of values from 1862 // LHS, for example: 1863 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1864 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1865 // Shuffles to: |EE|FF|GG|HH| 1866 // +--+--+--+--+ 1867 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1868 ArrayRef<int> Mask) { 1869 unsigned LHSElems = 1870 cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements(); 1871 unsigned MaskElems = Mask.size(); 1872 unsigned BegIdx = Mask.front(); 1873 unsigned EndIdx = Mask.back(); 1874 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1875 return false; 1876 for (unsigned I = 0; I != MaskElems; ++I) 1877 if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1878 return false; 1879 return true; 1880 } 1881 1882 /// These are the ingredients in an alternate form binary operator as described 1883 /// below. 1884 struct BinopElts { 1885 BinaryOperator::BinaryOps Opcode; 1886 Value *Op0; 1887 Value *Op1; 1888 BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0, 1889 Value *V0 = nullptr, Value *V1 = nullptr) : 1890 Opcode(Opc), Op0(V0), Op1(V1) {} 1891 operator bool() const { return Opcode != 0; } 1892 }; 1893 1894 /// Binops may be transformed into binops with different opcodes and operands. 1895 /// Reverse the usual canonicalization to enable folds with the non-canonical 1896 /// form of the binop. If a transform is possible, return the elements of the 1897 /// new binop. If not, return invalid elements. 1898 static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) { 1899 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1); 1900 Type *Ty = BO->getType(); 1901 switch (BO->getOpcode()) { 1902 case Instruction::Shl: { 1903 // shl X, C --> mul X, (1 << C) 1904 Constant *C; 1905 if (match(BO1, m_Constant(C))) { 1906 Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C); 1907 return { Instruction::Mul, BO0, ShlOne }; 1908 } 1909 break; 1910 } 1911 case Instruction::Or: { 1912 // or X, C --> add X, C (when X and C have no common bits set) 1913 const APInt *C; 1914 if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL)) 1915 return { Instruction::Add, BO0, BO1 }; 1916 break; 1917 } 1918 default: 1919 break; 1920 } 1921 return {}; 1922 } 1923 1924 static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) { 1925 assert(Shuf.isSelect() && "Must have select-equivalent shuffle"); 1926 1927 // Are we shuffling together some value and that same value after it has been 1928 // modified by a binop with a constant? 1929 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); 1930 Constant *C; 1931 bool Op0IsBinop; 1932 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C)))) 1933 Op0IsBinop = true; 1934 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C)))) 1935 Op0IsBinop = false; 1936 else 1937 return nullptr; 1938 1939 // The identity constant for a binop leaves a variable operand unchanged. For 1940 // a vector, this is a splat of something like 0, -1, or 1. 1941 // If there's no identity constant for this binop, we're done. 1942 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1); 1943 BinaryOperator::BinaryOps BOpcode = BO->getOpcode(); 1944 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true); 1945 if (!IdC) 1946 return nullptr; 1947 1948 // Shuffle identity constants into the lanes that return the original value. 1949 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4} 1950 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4} 1951 // The existing binop constant vector remains in the same operand position. 1952 ArrayRef<int> Mask = Shuf.getShuffleMask(); 1953 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) : 1954 ConstantExpr::getShuffleVector(IdC, C, Mask); 1955 1956 bool MightCreatePoisonOrUB = 1957 is_contained(Mask, UndefMaskElem) && 1958 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode)); 1959 if (MightCreatePoisonOrUB) 1960 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true); 1961 1962 // shuf (bop X, C), X, M --> bop X, C' 1963 // shuf X, (bop X, C), M --> bop X, C' 1964 Value *X = Op0IsBinop ? Op1 : Op0; 1965 Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC); 1966 NewBO->copyIRFlags(BO); 1967 1968 // An undef shuffle mask element may propagate as an undef constant element in 1969 // the new binop. That would produce poison where the original code might not. 1970 // If we already made a safe constant, then there's no danger. 1971 if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB) 1972 NewBO->dropPoisonGeneratingFlags(); 1973 return NewBO; 1974 } 1975 1976 /// If we have an insert of a scalar to a non-zero element of an undefined 1977 /// vector and then shuffle that value, that's the same as inserting to the zero 1978 /// element and shuffling. Splatting from the zero element is recognized as the 1979 /// canonical form of splat. 1980 static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf, 1981 InstCombiner::BuilderTy &Builder) { 1982 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); 1983 ArrayRef<int> Mask = Shuf.getShuffleMask(); 1984 Value *X; 1985 uint64_t IndexC; 1986 1987 // Match a shuffle that is a splat to a non-zero element. 1988 if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X), 1989 m_ConstantInt(IndexC)))) || 1990 !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0) 1991 return nullptr; 1992 1993 // Insert into element 0 of an undef vector. 1994 UndefValue *UndefVec = UndefValue::get(Shuf.getType()); 1995 Constant *Zero = Builder.getInt32(0); 1996 Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero); 1997 1998 // Splat from element 0. Any mask element that is undefined remains undefined. 1999 // For example: 2000 // shuf (inselt undef, X, 2), _, <2,2,undef> 2001 // --> shuf (inselt undef, X, 0), poison, <0,0,undef> 2002 unsigned NumMaskElts = 2003 cast<FixedVectorType>(Shuf.getType())->getNumElements(); 2004 SmallVector<int, 16> NewMask(NumMaskElts, 0); 2005 for (unsigned i = 0; i != NumMaskElts; ++i) 2006 if (Mask[i] == UndefMaskElem) 2007 NewMask[i] = Mask[i]; 2008 2009 return new ShuffleVectorInst(NewIns, NewMask); 2010 } 2011 2012 /// Try to fold shuffles that are the equivalent of a vector select. 2013 static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf, 2014 InstCombiner::BuilderTy &Builder, 2015 const DataLayout &DL) { 2016 if (!Shuf.isSelect()) 2017 return nullptr; 2018 2019 // Canonicalize to choose from operand 0 first unless operand 1 is undefined. 2020 // Commuting undef to operand 0 conflicts with another canonicalization. 2021 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements(); 2022 if (!match(Shuf.getOperand(1), m_Undef()) && 2023 Shuf.getMaskValue(0) >= (int)NumElts) { 2024 // TODO: Can we assert that both operands of a shuffle-select are not undef 2025 // (otherwise, it would have been folded by instsimplify? 2026 Shuf.commute(); 2027 return &Shuf; 2028 } 2029 2030 if (Instruction *I = foldSelectShuffleWith1Binop(Shuf)) 2031 return I; 2032 2033 BinaryOperator *B0, *B1; 2034 if (!match(Shuf.getOperand(0), m_BinOp(B0)) || 2035 !match(Shuf.getOperand(1), m_BinOp(B1))) 2036 return nullptr; 2037 2038 Value *X, *Y; 2039 Constant *C0, *C1; 2040 bool ConstantsAreOp1; 2041 if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) && 2042 match(B1, m_BinOp(m_Value(Y), m_Constant(C1)))) 2043 ConstantsAreOp1 = true; 2044 else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) && 2045 match(B1, m_BinOp(m_Constant(C1), m_Value(Y)))) 2046 ConstantsAreOp1 = false; 2047 else 2048 return nullptr; 2049 2050 // We need matching binops to fold the lanes together. 2051 BinaryOperator::BinaryOps Opc0 = B0->getOpcode(); 2052 BinaryOperator::BinaryOps Opc1 = B1->getOpcode(); 2053 bool DropNSW = false; 2054 if (ConstantsAreOp1 && Opc0 != Opc1) { 2055 // TODO: We drop "nsw" if shift is converted into multiply because it may 2056 // not be correct when the shift amount is BitWidth - 1. We could examine 2057 // each vector element to determine if it is safe to keep that flag. 2058 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl) 2059 DropNSW = true; 2060 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) { 2061 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop"); 2062 Opc0 = AltB0.Opcode; 2063 C0 = cast<Constant>(AltB0.Op1); 2064 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) { 2065 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop"); 2066 Opc1 = AltB1.Opcode; 2067 C1 = cast<Constant>(AltB1.Op1); 2068 } 2069 } 2070 2071 if (Opc0 != Opc1) 2072 return nullptr; 2073 2074 // The opcodes must be the same. Use a new name to make that clear. 2075 BinaryOperator::BinaryOps BOpc = Opc0; 2076 2077 // Select the constant elements needed for the single binop. 2078 ArrayRef<int> Mask = Shuf.getShuffleMask(); 2079 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask); 2080 2081 // We are moving a binop after a shuffle. When a shuffle has an undefined 2082 // mask element, the result is undefined, but it is not poison or undefined 2083 // behavior. That is not necessarily true for div/rem/shift. 2084 bool MightCreatePoisonOrUB = 2085 is_contained(Mask, UndefMaskElem) && 2086 (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc)); 2087 if (MightCreatePoisonOrUB) 2088 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC, 2089 ConstantsAreOp1); 2090 2091 Value *V; 2092 if (X == Y) { 2093 // Remove a binop and the shuffle by rearranging the constant: 2094 // shuffle (op V, C0), (op V, C1), M --> op V, C' 2095 // shuffle (op C0, V), (op C1, V), M --> op C', V 2096 V = X; 2097 } else { 2098 // If there are 2 different variable operands, we must create a new shuffle 2099 // (select) first, so check uses to ensure that we don't end up with more 2100 // instructions than we started with. 2101 if (!B0->hasOneUse() && !B1->hasOneUse()) 2102 return nullptr; 2103 2104 // If we use the original shuffle mask and op1 is *variable*, we would be 2105 // putting an undef into operand 1 of div/rem/shift. This is either UB or 2106 // poison. We do not have to guard against UB when *constants* are op1 2107 // because safe constants guarantee that we do not overflow sdiv/srem (and 2108 // there's no danger for other opcodes). 2109 // TODO: To allow this case, create a new shuffle mask with no undefs. 2110 if (MightCreatePoisonOrUB && !ConstantsAreOp1) 2111 return nullptr; 2112 2113 // Note: In general, we do not create new shuffles in InstCombine because we 2114 // do not know if a target can lower an arbitrary shuffle optimally. In this 2115 // case, the shuffle uses the existing mask, so there is no additional risk. 2116 2117 // Select the variable vectors first, then perform the binop: 2118 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C' 2119 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M) 2120 V = Builder.CreateShuffleVector(X, Y, Mask); 2121 } 2122 2123 Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) : 2124 BinaryOperator::Create(BOpc, NewC, V); 2125 2126 // Flags are intersected from the 2 source binops. But there are 2 exceptions: 2127 // 1. If we changed an opcode, poison conditions might have changed. 2128 // 2. If the shuffle had undef mask elements, the new binop might have undefs 2129 // where the original code did not. But if we already made a safe constant, 2130 // then there's no danger. 2131 NewBO->copyIRFlags(B0); 2132 NewBO->andIRFlags(B1); 2133 if (DropNSW) 2134 NewBO->setHasNoSignedWrap(false); 2135 if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB) 2136 NewBO->dropPoisonGeneratingFlags(); 2137 return NewBO; 2138 } 2139 2140 /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate. 2141 /// Example (little endian): 2142 /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8> 2143 static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf, 2144 bool IsBigEndian) { 2145 // This must be a bitcasted shuffle of 1 vector integer operand. 2146 Type *DestType = Shuf.getType(); 2147 Value *X; 2148 if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) || 2149 !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy()) 2150 return nullptr; 2151 2152 // The source type must have the same number of elements as the shuffle, 2153 // and the source element type must be larger than the shuffle element type. 2154 Type *SrcType = X->getType(); 2155 if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() || 2156 cast<FixedVectorType>(SrcType)->getNumElements() != 2157 cast<FixedVectorType>(DestType)->getNumElements() || 2158 SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0) 2159 return nullptr; 2160 2161 assert(Shuf.changesLength() && !Shuf.increasesLength() && 2162 "Expected a shuffle that decreases length"); 2163 2164 // Last, check that the mask chooses the correct low bits for each narrow 2165 // element in the result. 2166 uint64_t TruncRatio = 2167 SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits(); 2168 ArrayRef<int> Mask = Shuf.getShuffleMask(); 2169 for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 2170 if (Mask[i] == UndefMaskElem) 2171 continue; 2172 uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio; 2173 assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits"); 2174 if (Mask[i] != (int)LSBIndex) 2175 return nullptr; 2176 } 2177 2178 return new TruncInst(X, DestType); 2179 } 2180 2181 /// Match a shuffle-select-shuffle pattern where the shuffles are widening and 2182 /// narrowing (concatenating with undef and extracting back to the original 2183 /// length). This allows replacing the wide select with a narrow select. 2184 static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf, 2185 InstCombiner::BuilderTy &Builder) { 2186 // This must be a narrowing identity shuffle. It extracts the 1st N elements 2187 // of the 1st vector operand of a shuffle. 2188 if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract()) 2189 return nullptr; 2190 2191 // The vector being shuffled must be a vector select that we can eliminate. 2192 // TODO: The one-use requirement could be eased if X and/or Y are constants. 2193 Value *Cond, *X, *Y; 2194 if (!match(Shuf.getOperand(0), 2195 m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y))))) 2196 return nullptr; 2197 2198 // We need a narrow condition value. It must be extended with undef elements 2199 // and have the same number of elements as this shuffle. 2200 unsigned NarrowNumElts = 2201 cast<FixedVectorType>(Shuf.getType())->getNumElements(); 2202 Value *NarrowCond; 2203 if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) || 2204 cast<FixedVectorType>(NarrowCond->getType())->getNumElements() != 2205 NarrowNumElts || 2206 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding()) 2207 return nullptr; 2208 2209 // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) --> 2210 // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask) 2211 Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask()); 2212 Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask()); 2213 return SelectInst::Create(NarrowCond, NarrowX, NarrowY); 2214 } 2215 2216 /// Try to fold an extract subvector operation. 2217 static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) { 2218 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1); 2219 if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef())) 2220 return nullptr; 2221 2222 // Check if we are extracting all bits of an inserted scalar: 2223 // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type 2224 Value *X; 2225 if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) && 2226 X->getType()->getPrimitiveSizeInBits() == 2227 Shuf.getType()->getPrimitiveSizeInBits()) 2228 return new BitCastInst(X, Shuf.getType()); 2229 2230 // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask. 2231 Value *Y; 2232 ArrayRef<int> Mask; 2233 if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) 2234 return nullptr; 2235 2236 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle, 2237 // then combining may result in worse codegen. 2238 if (!Op0->hasOneUse()) 2239 return nullptr; 2240 2241 // We are extracting a subvector from a shuffle. Remove excess elements from 2242 // the 1st shuffle mask to eliminate the extract. 2243 // 2244 // This transform is conservatively limited to identity extracts because we do 2245 // not allow arbitrary shuffle mask creation as a target-independent transform 2246 // (because we can't guarantee that will lower efficiently). 2247 // 2248 // If the extracting shuffle has an undef mask element, it transfers to the 2249 // new shuffle mask. Otherwise, copy the original mask element. Example: 2250 // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> --> 2251 // shuf X, Y, <C0, undef, C2, undef> 2252 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements(); 2253 SmallVector<int, 16> NewMask(NumElts); 2254 assert(NumElts < Mask.size() && 2255 "Identity with extract must have less elements than its inputs"); 2256 2257 for (unsigned i = 0; i != NumElts; ++i) { 2258 int ExtractMaskElt = Shuf.getMaskValue(i); 2259 int MaskElt = Mask[i]; 2260 NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt; 2261 } 2262 return new ShuffleVectorInst(X, Y, NewMask); 2263 } 2264 2265 /// Try to replace a shuffle with an insertelement or try to replace a shuffle 2266 /// operand with the operand of an insertelement. 2267 static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf, 2268 InstCombinerImpl &IC) { 2269 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1); 2270 SmallVector<int, 16> Mask; 2271 Shuf.getShuffleMask(Mask); 2272 2273 int NumElts = Mask.size(); 2274 int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements(); 2275 2276 // This is a specialization of a fold in SimplifyDemandedVectorElts. We may 2277 // not be able to handle it there if the insertelement has >1 use. 2278 // If the shuffle has an insertelement operand but does not choose the 2279 // inserted scalar element from that value, then we can replace that shuffle 2280 // operand with the source vector of the insertelement. 2281 Value *X; 2282 uint64_t IdxC; 2283 if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { 2284 // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask 2285 if (!is_contained(Mask, (int)IdxC)) 2286 return IC.replaceOperand(Shuf, 0, X); 2287 } 2288 if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) { 2289 // Offset the index constant by the vector width because we are checking for 2290 // accesses to the 2nd vector input of the shuffle. 2291 IdxC += InpNumElts; 2292 // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask 2293 if (!is_contained(Mask, (int)IdxC)) 2294 return IC.replaceOperand(Shuf, 1, X); 2295 } 2296 // For the rest of the transform, the shuffle must not change vector sizes. 2297 // TODO: This restriction could be removed if the insert has only one use 2298 // (because the transform would require a new length-changing shuffle). 2299 if (NumElts != InpNumElts) 2300 return nullptr; 2301 2302 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC' 2303 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) { 2304 // We need an insertelement with a constant index. 2305 if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar), 2306 m_ConstantInt(IndexC)))) 2307 return false; 2308 2309 // Test the shuffle mask to see if it splices the inserted scalar into the 2310 // operand 1 vector of the shuffle. 2311 int NewInsIndex = -1; 2312 for (int i = 0; i != NumElts; ++i) { 2313 // Ignore undef mask elements. 2314 if (Mask[i] == -1) 2315 continue; 2316 2317 // The shuffle takes elements of operand 1 without lane changes. 2318 if (Mask[i] == NumElts + i) 2319 continue; 2320 2321 // The shuffle must choose the inserted scalar exactly once. 2322 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue()) 2323 return false; 2324 2325 // The shuffle is placing the inserted scalar into element i. 2326 NewInsIndex = i; 2327 } 2328 2329 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?"); 2330 2331 // Index is updated to the potentially translated insertion lane. 2332 IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex); 2333 return true; 2334 }; 2335 2336 // If the shuffle is unnecessary, insert the scalar operand directly into 2337 // operand 1 of the shuffle. Example: 2338 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0 2339 Value *Scalar; 2340 ConstantInt *IndexC; 2341 if (isShufflingScalarIntoOp1(Scalar, IndexC)) 2342 return InsertElementInst::Create(V1, Scalar, IndexC); 2343 2344 // Try again after commuting shuffle. Example: 2345 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> --> 2346 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3 2347 std::swap(V0, V1); 2348 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts); 2349 if (isShufflingScalarIntoOp1(Scalar, IndexC)) 2350 return InsertElementInst::Create(V1, Scalar, IndexC); 2351 2352 return nullptr; 2353 } 2354 2355 static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) { 2356 // Match the operands as identity with padding (also known as concatenation 2357 // with undef) shuffles of the same source type. The backend is expected to 2358 // recreate these concatenations from a shuffle of narrow operands. 2359 auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0)); 2360 auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1)); 2361 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() || 2362 !Shuffle1 || !Shuffle1->isIdentityWithPadding()) 2363 return nullptr; 2364 2365 // We limit this transform to power-of-2 types because we expect that the 2366 // backend can convert the simplified IR patterns to identical nodes as the 2367 // original IR. 2368 // TODO: If we can verify the same behavior for arbitrary types, the 2369 // power-of-2 checks can be removed. 2370 Value *X = Shuffle0->getOperand(0); 2371 Value *Y = Shuffle1->getOperand(0); 2372 if (X->getType() != Y->getType() || 2373 !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) || 2374 !isPowerOf2_32( 2375 cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) || 2376 !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) || 2377 match(X, m_Undef()) || match(Y, m_Undef())) 2378 return nullptr; 2379 assert(match(Shuffle0->getOperand(1), m_Undef()) && 2380 match(Shuffle1->getOperand(1), m_Undef()) && 2381 "Unexpected operand for identity shuffle"); 2382 2383 // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source 2384 // operands directly by adjusting the shuffle mask to account for the narrower 2385 // types: 2386 // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask' 2387 int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements(); 2388 int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements(); 2389 assert(WideElts > NarrowElts && "Unexpected types for identity with padding"); 2390 2391 ArrayRef<int> Mask = Shuf.getShuffleMask(); 2392 SmallVector<int, 16> NewMask(Mask.size(), -1); 2393 for (int i = 0, e = Mask.size(); i != e; ++i) { 2394 if (Mask[i] == -1) 2395 continue; 2396 2397 // If this shuffle is choosing an undef element from 1 of the sources, that 2398 // element is undef. 2399 if (Mask[i] < WideElts) { 2400 if (Shuffle0->getMaskValue(Mask[i]) == -1) 2401 continue; 2402 } else { 2403 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1) 2404 continue; 2405 } 2406 2407 // If this shuffle is choosing from the 1st narrow op, the mask element is 2408 // the same. If this shuffle is choosing from the 2nd narrow op, the mask 2409 // element is offset down to adjust for the narrow vector widths. 2410 if (Mask[i] < WideElts) { 2411 assert(Mask[i] < NarrowElts && "Unexpected shuffle mask"); 2412 NewMask[i] = Mask[i]; 2413 } else { 2414 assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask"); 2415 NewMask[i] = Mask[i] - (WideElts - NarrowElts); 2416 } 2417 } 2418 return new ShuffleVectorInst(X, Y, NewMask); 2419 } 2420 2421 Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 2422 Value *LHS = SVI.getOperand(0); 2423 Value *RHS = SVI.getOperand(1); 2424 SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI); 2425 if (auto *V = SimplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(), 2426 SVI.getType(), ShufQuery)) 2427 return replaceInstUsesWith(SVI, V); 2428 2429 // Bail out for scalable vectors 2430 if (isa<ScalableVectorType>(LHS->getType())) 2431 return nullptr; 2432 2433 unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements(); 2434 unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements(); 2435 2436 // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask) 2437 // 2438 // if X and Y are of the same (vector) type, and the element size is not 2439 // changed by the bitcasts, we can distribute the bitcasts through the 2440 // shuffle, hopefully reducing the number of instructions. We make sure that 2441 // at least one bitcast only has one use, so we don't *increase* the number of 2442 // instructions here. 2443 Value *X, *Y; 2444 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) && 2445 X->getType()->isVectorTy() && X->getType() == Y->getType() && 2446 X->getType()->getScalarSizeInBits() == 2447 SVI.getType()->getScalarSizeInBits() && 2448 (LHS->hasOneUse() || RHS->hasOneUse())) { 2449 Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(), 2450 SVI.getName() + ".uncasted"); 2451 return new BitCastInst(V, SVI.getType()); 2452 } 2453 2454 ArrayRef<int> Mask = SVI.getShuffleMask(); 2455 Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 2456 2457 // Peek through a bitcasted shuffle operand by scaling the mask. If the 2458 // simulated shuffle can simplify, then this shuffle is unnecessary: 2459 // shuf (bitcast X), undef, Mask --> bitcast X' 2460 // TODO: This could be extended to allow length-changing shuffles. 2461 // The transform might also be obsoleted if we allowed canonicalization 2462 // of bitcasted shuffles. 2463 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) && 2464 X->getType()->isVectorTy() && VWidth == LHSWidth) { 2465 // Try to create a scaled mask constant. 2466 auto *XType = cast<FixedVectorType>(X->getType()); 2467 unsigned XNumElts = XType->getNumElements(); 2468 SmallVector<int, 16> ScaledMask; 2469 if (XNumElts >= VWidth) { 2470 assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast"); 2471 narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask); 2472 } else { 2473 assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast"); 2474 if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask)) 2475 ScaledMask.clear(); 2476 } 2477 if (!ScaledMask.empty()) { 2478 // If the shuffled source vector simplifies, cast that value to this 2479 // shuffle's type. 2480 if (auto *V = SimplifyShuffleVectorInst(X, UndefValue::get(XType), 2481 ScaledMask, XType, ShufQuery)) 2482 return BitCastInst::Create(Instruction::BitCast, V, SVI.getType()); 2483 } 2484 } 2485 2486 // shuffle x, x, mask --> shuffle x, undef, mask' 2487 if (LHS == RHS) { 2488 assert(!match(RHS, m_Undef()) && 2489 "Shuffle with 2 undef ops not simplified?"); 2490 return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth)); 2491 } 2492 2493 // shuffle undef, x, mask --> shuffle x, undef, mask' 2494 if (match(LHS, m_Undef())) { 2495 SVI.commute(); 2496 return &SVI; 2497 } 2498 2499 if (Instruction *I = canonicalizeInsertSplat(SVI, Builder)) 2500 return I; 2501 2502 if (Instruction *I = foldSelectShuffle(SVI, Builder, DL)) 2503 return I; 2504 2505 if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian())) 2506 return I; 2507 2508 if (Instruction *I = narrowVectorSelect(SVI, Builder)) 2509 return I; 2510 2511 APInt UndefElts(VWidth, 0); 2512 APInt AllOnesEltMask(APInt::getAllOnes(VWidth)); 2513 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 2514 if (V != &SVI) 2515 return replaceInstUsesWith(SVI, V); 2516 return &SVI; 2517 } 2518 2519 if (Instruction *I = foldIdentityExtractShuffle(SVI)) 2520 return I; 2521 2522 // These transforms have the potential to lose undef knowledge, so they are 2523 // intentionally placed after SimplifyDemandedVectorElts(). 2524 if (Instruction *I = foldShuffleWithInsert(SVI, *this)) 2525 return I; 2526 if (Instruction *I = foldIdentityPaddedShuffles(SVI)) 2527 return I; 2528 2529 if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) { 2530 Value *V = evaluateInDifferentElementOrder(LHS, Mask); 2531 return replaceInstUsesWith(SVI, V); 2532 } 2533 2534 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 2535 // a non-vector type. We can instead bitcast the original vector followed by 2536 // an extract of the desired element: 2537 // 2538 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 2539 // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 2540 // %1 = bitcast <4 x i8> %sroa to i32 2541 // Becomes: 2542 // %bc = bitcast <16 x i8> %in to <4 x i32> 2543 // %ext = extractelement <4 x i32> %bc, i32 0 2544 // 2545 // If the shuffle is extracting a contiguous range of values from the input 2546 // vector then each use which is a bitcast of the extracted size can be 2547 // replaced. This will work if the vector types are compatible, and the begin 2548 // index is aligned to a value in the casted vector type. If the begin index 2549 // isn't aligned then we can shuffle the original vector (keeping the same 2550 // vector type) before extracting. 2551 // 2552 // This code will bail out if the target type is fundamentally incompatible 2553 // with vectors of the source type. 2554 // 2555 // Example of <16 x i8>, target type i32: 2556 // Index range [4,8): v-----------v Will work. 2557 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 2558 // <16 x i8>: | | | | | | | | | | | | | | | | | 2559 // <4 x i32>: | | | | | 2560 // +-----------+-----------+-----------+-----------+ 2561 // Index range [6,10): ^-----------^ Needs an extra shuffle. 2562 // Target type i40: ^--------------^ Won't work, bail. 2563 bool MadeChange = false; 2564 if (isShuffleExtractingFromLHS(SVI, Mask)) { 2565 Value *V = LHS; 2566 unsigned MaskElems = Mask.size(); 2567 auto *SrcTy = cast<FixedVectorType>(V->getType()); 2568 unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedSize(); 2569 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 2570 assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 2571 unsigned SrcNumElems = SrcTy->getNumElements(); 2572 SmallVector<BitCastInst *, 8> BCs; 2573 DenseMap<Type *, Value *> NewBCs; 2574 for (User *U : SVI.users()) 2575 if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 2576 if (!BC->use_empty()) 2577 // Only visit bitcasts that weren't previously handled. 2578 BCs.push_back(BC); 2579 for (BitCastInst *BC : BCs) { 2580 unsigned BegIdx = Mask.front(); 2581 Type *TgtTy = BC->getDestTy(); 2582 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 2583 if (!TgtElemBitWidth) 2584 continue; 2585 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 2586 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 2587 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 2588 if (!VecBitWidthsEqual) 2589 continue; 2590 if (!VectorType::isValidElementType(TgtTy)) 2591 continue; 2592 auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems); 2593 if (!BegIsAligned) { 2594 // Shuffle the input so [0,NumElements) contains the output, and 2595 // [NumElems,SrcNumElems) is undef. 2596 SmallVector<int, 16> ShuffleMask(SrcNumElems, -1); 2597 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 2598 ShuffleMask[I] = Idx; 2599 V = Builder.CreateShuffleVector(V, ShuffleMask, 2600 SVI.getName() + ".extract"); 2601 BegIdx = 0; 2602 } 2603 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 2604 assert(SrcElemsPerTgtElem); 2605 BegIdx /= SrcElemsPerTgtElem; 2606 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 2607 auto *NewBC = 2608 BCAlreadyExists 2609 ? NewBCs[CastSrcTy] 2610 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 2611 if (!BCAlreadyExists) 2612 NewBCs[CastSrcTy] = NewBC; 2613 auto *Ext = Builder.CreateExtractElement( 2614 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 2615 // The shufflevector isn't being replaced: the bitcast that used it 2616 // is. InstCombine will visit the newly-created instructions. 2617 replaceInstUsesWith(*BC, Ext); 2618 MadeChange = true; 2619 } 2620 } 2621 2622 // If the LHS is a shufflevector itself, see if we can combine it with this 2623 // one without producing an unusual shuffle. 2624 // Cases that might be simplified: 2625 // 1. 2626 // x1=shuffle(v1,v2,mask1) 2627 // x=shuffle(x1,undef,mask) 2628 // ==> 2629 // x=shuffle(v1,undef,newMask) 2630 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 2631 // 2. 2632 // x1=shuffle(v1,undef,mask1) 2633 // x=shuffle(x1,x2,mask) 2634 // where v1.size() == mask1.size() 2635 // ==> 2636 // x=shuffle(v1,x2,newMask) 2637 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 2638 // 3. 2639 // x2=shuffle(v2,undef,mask2) 2640 // x=shuffle(x1,x2,mask) 2641 // where v2.size() == mask2.size() 2642 // ==> 2643 // x=shuffle(x1,v2,newMask) 2644 // newMask[i] = (mask[i] < x1.size()) 2645 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 2646 // 4. 2647 // x1=shuffle(v1,undef,mask1) 2648 // x2=shuffle(v2,undef,mask2) 2649 // x=shuffle(x1,x2,mask) 2650 // where v1.size() == v2.size() 2651 // ==> 2652 // x=shuffle(v1,v2,newMask) 2653 // newMask[i] = (mask[i] < x1.size()) 2654 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 2655 // 2656 // Here we are really conservative: 2657 // we are absolutely afraid of producing a shuffle mask not in the input 2658 // program, because the code gen may not be smart enough to turn a merged 2659 // shuffle into two specific shuffles: it may produce worse code. As such, 2660 // we only merge two shuffles if the result is either a splat or one of the 2661 // input shuffle masks. In this case, merging the shuffles just removes 2662 // one instruction, which we know is safe. This is good for things like 2663 // turning: (splat(splat)) -> splat, or 2664 // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 2665 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 2666 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 2667 if (LHSShuffle) 2668 if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef())) 2669 LHSShuffle = nullptr; 2670 if (RHSShuffle) 2671 if (!match(RHSShuffle->getOperand(1), m_Undef())) 2672 RHSShuffle = nullptr; 2673 if (!LHSShuffle && !RHSShuffle) 2674 return MadeChange ? &SVI : nullptr; 2675 2676 Value* LHSOp0 = nullptr; 2677 Value* LHSOp1 = nullptr; 2678 Value* RHSOp0 = nullptr; 2679 unsigned LHSOp0Width = 0; 2680 unsigned RHSOp0Width = 0; 2681 if (LHSShuffle) { 2682 LHSOp0 = LHSShuffle->getOperand(0); 2683 LHSOp1 = LHSShuffle->getOperand(1); 2684 LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements(); 2685 } 2686 if (RHSShuffle) { 2687 RHSOp0 = RHSShuffle->getOperand(0); 2688 RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements(); 2689 } 2690 Value* newLHS = LHS; 2691 Value* newRHS = RHS; 2692 if (LHSShuffle) { 2693 // case 1 2694 if (match(RHS, m_Undef())) { 2695 newLHS = LHSOp0; 2696 newRHS = LHSOp1; 2697 } 2698 // case 2 or 4 2699 else if (LHSOp0Width == LHSWidth) { 2700 newLHS = LHSOp0; 2701 } 2702 } 2703 // case 3 or 4 2704 if (RHSShuffle && RHSOp0Width == LHSWidth) { 2705 newRHS = RHSOp0; 2706 } 2707 // case 4 2708 if (LHSOp0 == RHSOp0) { 2709 newLHS = LHSOp0; 2710 newRHS = nullptr; 2711 } 2712 2713 if (newLHS == LHS && newRHS == RHS) 2714 return MadeChange ? &SVI : nullptr; 2715 2716 ArrayRef<int> LHSMask; 2717 ArrayRef<int> RHSMask; 2718 if (newLHS != LHS) 2719 LHSMask = LHSShuffle->getShuffleMask(); 2720 if (RHSShuffle && newRHS != RHS) 2721 RHSMask = RHSShuffle->getShuffleMask(); 2722 2723 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 2724 SmallVector<int, 16> newMask; 2725 bool isSplat = true; 2726 int SplatElt = -1; 2727 // Create a new mask for the new ShuffleVectorInst so that the new 2728 // ShuffleVectorInst is equivalent to the original one. 2729 for (unsigned i = 0; i < VWidth; ++i) { 2730 int eltMask; 2731 if (Mask[i] < 0) { 2732 // This element is an undef value. 2733 eltMask = -1; 2734 } else if (Mask[i] < (int)LHSWidth) { 2735 // This element is from left hand side vector operand. 2736 // 2737 // If LHS is going to be replaced (case 1, 2, or 4), calculate the 2738 // new mask value for the element. 2739 if (newLHS != LHS) { 2740 eltMask = LHSMask[Mask[i]]; 2741 // If the value selected is an undef value, explicitly specify it 2742 // with a -1 mask value. 2743 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 2744 eltMask = -1; 2745 } else 2746 eltMask = Mask[i]; 2747 } else { 2748 // This element is from right hand side vector operand 2749 // 2750 // If the value selected is an undef value, explicitly specify it 2751 // with a -1 mask value. (case 1) 2752 if (match(RHS, m_Undef())) 2753 eltMask = -1; 2754 // If RHS is going to be replaced (case 3 or 4), calculate the 2755 // new mask value for the element. 2756 else if (newRHS != RHS) { 2757 eltMask = RHSMask[Mask[i]-LHSWidth]; 2758 // If the value selected is an undef value, explicitly specify it 2759 // with a -1 mask value. 2760 if (eltMask >= (int)RHSOp0Width) { 2761 assert(match(RHSShuffle->getOperand(1), m_Undef()) && 2762 "should have been check above"); 2763 eltMask = -1; 2764 } 2765 } else 2766 eltMask = Mask[i]-LHSWidth; 2767 2768 // If LHS's width is changed, shift the mask value accordingly. 2769 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any 2770 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 2771 // If newRHS == newLHS, we want to remap any references from newRHS to 2772 // newLHS so that we can properly identify splats that may occur due to 2773 // obfuscation across the two vectors. 2774 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 2775 eltMask += newLHSWidth; 2776 } 2777 2778 // Check if this could still be a splat. 2779 if (eltMask >= 0) { 2780 if (SplatElt >= 0 && SplatElt != eltMask) 2781 isSplat = false; 2782 SplatElt = eltMask; 2783 } 2784 2785 newMask.push_back(eltMask); 2786 } 2787 2788 // If the result mask is equal to one of the original shuffle masks, 2789 // or is a splat, do the replacement. 2790 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 2791 if (!newRHS) 2792 newRHS = UndefValue::get(newLHS->getType()); 2793 return new ShuffleVectorInst(newLHS, newRHS, newMask); 2794 } 2795 2796 return MadeChange ? &SVI : nullptr; 2797 } 2798