1 //===- InstCombineVectorOps.cpp -------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements instcombine for ExtractElement, InsertElement and 11 // ShuffleVector. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstCombineInternal.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/VectorUtils.h" 19 #include "llvm/IR/PatternMatch.h" 20 using namespace llvm; 21 using namespace PatternMatch; 22 23 #define DEBUG_TYPE "instcombine" 24 25 /// Return true if the value is cheaper to scalarize than it is to leave as a 26 /// vector operation. isConstant indicates whether we're extracting one known 27 /// element. If false we're extracting a variable index. 28 static bool cheapToScalarize(Value *V, bool isConstant) { 29 if (Constant *C = dyn_cast<Constant>(V)) { 30 if (isConstant) return true; 31 32 // If all elts are the same, we can extract it and use any of the values. 33 if (Constant *Op0 = C->getAggregateElement(0U)) { 34 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; 35 ++i) 36 if (C->getAggregateElement(i) != Op0) 37 return false; 38 return true; 39 } 40 } 41 Instruction *I = dyn_cast<Instruction>(V); 42 if (!I) return false; 43 44 // Insert element gets simplified to the inserted element or is deleted if 45 // this is constant idx extract element and its a constant idx insertelt. 46 if (I->getOpcode() == Instruction::InsertElement && isConstant && 47 isa<ConstantInt>(I->getOperand(2))) 48 return true; 49 if (I->getOpcode() == Instruction::Load && I->hasOneUse()) 50 return true; 51 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) 52 if (BO->hasOneUse() && 53 (cheapToScalarize(BO->getOperand(0), isConstant) || 54 cheapToScalarize(BO->getOperand(1), isConstant))) 55 return true; 56 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 57 if (CI->hasOneUse() && 58 (cheapToScalarize(CI->getOperand(0), isConstant) || 59 cheapToScalarize(CI->getOperand(1), isConstant))) 60 return true; 61 62 return false; 63 } 64 65 // If we have a PHI node with a vector type that is only used to feed 66 // itself and be an operand of extractelement at a constant location, 67 // try to replace the PHI of the vector type with a PHI of a scalar type. 68 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { 69 SmallVector<Instruction *, 2> Extracts; 70 // The users we want the PHI to have are: 71 // 1) The EI ExtractElement (we already know this) 72 // 2) Possibly more ExtractElements with the same index. 73 // 3) Another operand, which will feed back into the PHI. 74 Instruction *PHIUser = nullptr; 75 for (auto U : PN->users()) { 76 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 77 if (EI.getIndexOperand() == EU->getIndexOperand()) 78 Extracts.push_back(EU); 79 else 80 return nullptr; 81 } else if (!PHIUser) { 82 PHIUser = cast<Instruction>(U); 83 } else { 84 return nullptr; 85 } 86 } 87 88 if (!PHIUser) 89 return nullptr; 90 91 // Verify that this PHI user has one use, which is the PHI itself, 92 // and that it is a binary operation which is cheap to scalarize. 93 // otherwise return NULL. 94 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 95 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) 96 return nullptr; 97 98 // Create a scalar PHI node that will replace the vector PHI node 99 // just before the current PHI node. 100 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 101 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 102 // Scalarize each PHI operand. 103 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 104 Value *PHIInVal = PN->getIncomingValue(i); 105 BasicBlock *inBB = PN->getIncomingBlock(i); 106 Value *Elt = EI.getIndexOperand(); 107 // If the operand is the PHI induction variable: 108 if (PHIInVal == PHIUser) { 109 // Scalarize the binary operation. Its first operand is the 110 // scalar PHI, and the second operand is extracted from the other 111 // vector operand. 112 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 113 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 114 Value *Op = InsertNewInstWith( 115 ExtractElementInst::Create(B0->getOperand(opId), Elt, 116 B0->getOperand(opId)->getName() + ".Elt"), 117 *B0); 118 Value *newPHIUser = InsertNewInstWith( 119 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 120 scalarPHI, Op, B0), *B0); 121 scalarPHI->addIncoming(newPHIUser, inBB); 122 } else { 123 // Scalarize PHI input: 124 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 125 // Insert the new instruction into the predecessor basic block. 126 Instruction *pos = dyn_cast<Instruction>(PHIInVal); 127 BasicBlock::iterator InsertPos; 128 if (pos && !isa<PHINode>(pos)) { 129 InsertPos = ++pos->getIterator(); 130 } else { 131 InsertPos = inBB->getFirstInsertionPt(); 132 } 133 134 InsertNewInstWith(newEI, *InsertPos); 135 136 scalarPHI->addIncoming(newEI, inBB); 137 } 138 } 139 140 for (auto E : Extracts) 141 replaceInstUsesWith(*E, scalarPHI); 142 143 return &EI; 144 } 145 146 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { 147 if (Value *V = SimplifyExtractElementInst( 148 EI.getVectorOperand(), EI.getIndexOperand(), DL, &TLI, &DT, &AC)) 149 return replaceInstUsesWith(EI, V); 150 151 // If vector val is constant with all elements the same, replace EI with 152 // that element. We handle a known element # below. 153 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 154 if (cheapToScalarize(C, false)) 155 return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 156 157 // If extracting a specified index from the vector, see if we can recursively 158 // find a previously computed scalar that was inserted into the vector. 159 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 160 unsigned IndexVal = IdxC->getZExtValue(); 161 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 162 163 // InstSimplify handles cases where the index is invalid. 164 assert(IndexVal < VectorWidth); 165 166 // This instruction only demands the single element from the input vector. 167 // If the input vector has a single use, simplify it based on this use 168 // property. 169 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 170 APInt UndefElts(VectorWidth, 0); 171 APInt DemandedMask(VectorWidth, 0); 172 DemandedMask.setBit(IndexVal); 173 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 174 UndefElts)) { 175 EI.setOperand(0, V); 176 return &EI; 177 } 178 } 179 180 // If this extractelement is directly using a bitcast from a vector of 181 // the same number of elements, see if we can find the source element from 182 // it. In this case, we will end up needing to bitcast the scalars. 183 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 184 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 185 if (VT->getNumElements() == VectorWidth) 186 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 187 return new BitCastInst(Elt, EI.getType()); 188 } 189 190 // If there's a vector PHI feeding a scalar use through this extractelement 191 // instruction, try to scalarize the PHI. 192 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 193 Instruction *scalarPHI = scalarizePHI(EI, PN); 194 if (scalarPHI) 195 return scalarPHI; 196 } 197 } 198 199 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 200 // Push extractelement into predecessor operation if legal and 201 // profitable to do so. 202 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 203 if (I->hasOneUse() && 204 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 205 Value *newEI0 = 206 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 207 EI.getName()+".lhs"); 208 Value *newEI1 = 209 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 210 EI.getName()+".rhs"); 211 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 212 newEI0, newEI1, BO); 213 } 214 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 215 // Extracting the inserted element? 216 if (IE->getOperand(2) == EI.getOperand(1)) 217 return replaceInstUsesWith(EI, IE->getOperand(1)); 218 // If the inserted and extracted elements are constants, they must not 219 // be the same value, extract from the pre-inserted value instead. 220 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 221 Worklist.AddValue(EI.getOperand(0)); 222 EI.setOperand(0, IE->getOperand(0)); 223 return &EI; 224 } 225 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 226 // If this is extracting an element from a shufflevector, figure out where 227 // it came from and extract from the appropriate input element instead. 228 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 229 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 230 Value *Src; 231 unsigned LHSWidth = 232 SVI->getOperand(0)->getType()->getVectorNumElements(); 233 234 if (SrcIdx < 0) 235 return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 236 if (SrcIdx < (int)LHSWidth) 237 Src = SVI->getOperand(0); 238 else { 239 SrcIdx -= LHSWidth; 240 Src = SVI->getOperand(1); 241 } 242 Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 243 return ExtractElementInst::Create(Src, 244 ConstantInt::get(Int32Ty, 245 SrcIdx, false)); 246 } 247 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 248 // Canonicalize extractelement(cast) -> cast(extractelement). 249 // Bitcasts can change the number of vector elements, and they cost 250 // nothing. 251 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 252 Value *EE = Builder->CreateExtractElement(CI->getOperand(0), 253 EI.getIndexOperand()); 254 Worklist.AddValue(EE); 255 return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 256 } 257 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 258 if (SI->hasOneUse()) { 259 // TODO: For a select on vectors, it might be useful to do this if it 260 // has multiple extractelement uses. For vector select, that seems to 261 // fight the vectorizer. 262 263 // If we are extracting an element from a vector select or a select on 264 // vectors, create a select on the scalars extracted from the vector 265 // arguments. 266 Value *TrueVal = SI->getTrueValue(); 267 Value *FalseVal = SI->getFalseValue(); 268 269 Value *Cond = SI->getCondition(); 270 if (Cond->getType()->isVectorTy()) { 271 Cond = Builder->CreateExtractElement(Cond, 272 EI.getIndexOperand(), 273 Cond->getName() + ".elt"); 274 } 275 276 Value *V1Elem 277 = Builder->CreateExtractElement(TrueVal, 278 EI.getIndexOperand(), 279 TrueVal->getName() + ".elt"); 280 281 Value *V2Elem 282 = Builder->CreateExtractElement(FalseVal, 283 EI.getIndexOperand(), 284 FalseVal->getName() + ".elt"); 285 return SelectInst::Create(Cond, 286 V1Elem, 287 V2Elem, 288 SI->getName() + ".elt"); 289 } 290 } 291 } 292 return nullptr; 293 } 294 295 /// If V is a shuffle of values that ONLY returns elements from either LHS or 296 /// RHS, return the shuffle mask and true. Otherwise, return false. 297 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 298 SmallVectorImpl<Constant*> &Mask) { 299 assert(LHS->getType() == RHS->getType() && 300 "Invalid CollectSingleShuffleElements"); 301 unsigned NumElts = V->getType()->getVectorNumElements(); 302 303 if (isa<UndefValue>(V)) { 304 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 305 return true; 306 } 307 308 if (V == LHS) { 309 for (unsigned i = 0; i != NumElts; ++i) 310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 311 return true; 312 } 313 314 if (V == RHS) { 315 for (unsigned i = 0; i != NumElts; ++i) 316 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 317 i+NumElts)); 318 return true; 319 } 320 321 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 322 // If this is an insert of an extract from some other vector, include it. 323 Value *VecOp = IEI->getOperand(0); 324 Value *ScalarOp = IEI->getOperand(1); 325 Value *IdxOp = IEI->getOperand(2); 326 327 if (!isa<ConstantInt>(IdxOp)) 328 return false; 329 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 330 331 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 332 // We can handle this if the vector we are inserting into is 333 // transitively ok. 334 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 335 // If so, update the mask to reflect the inserted undef. 336 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 337 return true; 338 } 339 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 340 if (isa<ConstantInt>(EI->getOperand(1))) { 341 unsigned ExtractedIdx = 342 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 343 unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 344 345 // This must be extracting from either LHS or RHS. 346 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 347 // We can handle this if the vector we are inserting into is 348 // transitively ok. 349 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 350 // If so, update the mask to reflect the inserted value. 351 if (EI->getOperand(0) == LHS) { 352 Mask[InsertedIdx % NumElts] = 353 ConstantInt::get(Type::getInt32Ty(V->getContext()), 354 ExtractedIdx); 355 } else { 356 assert(EI->getOperand(0) == RHS); 357 Mask[InsertedIdx % NumElts] = 358 ConstantInt::get(Type::getInt32Ty(V->getContext()), 359 ExtractedIdx + NumLHSElts); 360 } 361 return true; 362 } 363 } 364 } 365 } 366 } 367 368 return false; 369 } 370 371 /// If we have insertion into a vector that is wider than the vector that we 372 /// are extracting from, try to widen the source vector to allow a single 373 /// shufflevector to replace one or more insert/extract pairs. 374 static void replaceExtractElements(InsertElementInst *InsElt, 375 ExtractElementInst *ExtElt, 376 InstCombiner &IC) { 377 VectorType *InsVecType = InsElt->getType(); 378 VectorType *ExtVecType = ExtElt->getVectorOperandType(); 379 unsigned NumInsElts = InsVecType->getVectorNumElements(); 380 unsigned NumExtElts = ExtVecType->getVectorNumElements(); 381 382 // The inserted-to vector must be wider than the extracted-from vector. 383 if (InsVecType->getElementType() != ExtVecType->getElementType() || 384 NumExtElts >= NumInsElts) 385 return; 386 387 // Create a shuffle mask to widen the extended-from vector using undefined 388 // values. The mask selects all of the values of the original vector followed 389 // by as many undefined values as needed to create a vector of the same length 390 // as the inserted-to vector. 391 SmallVector<Constant *, 16> ExtendMask; 392 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 393 for (unsigned i = 0; i < NumExtElts; ++i) 394 ExtendMask.push_back(ConstantInt::get(IntType, i)); 395 for (unsigned i = NumExtElts; i < NumInsElts; ++i) 396 ExtendMask.push_back(UndefValue::get(IntType)); 397 398 Value *ExtVecOp = ExtElt->getVectorOperand(); 399 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 400 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 401 ? ExtVecOpInst->getParent() 402 : ExtElt->getParent(); 403 404 // TODO: This restriction matches the basic block check below when creating 405 // new extractelement instructions. If that limitation is removed, this one 406 // could also be removed. But for now, we just bail out to ensure that we 407 // will replace the extractelement instruction that is feeding our 408 // insertelement instruction. This allows the insertelement to then be 409 // replaced by a shufflevector. If the insertelement is not replaced, we can 410 // induce infinite looping because there's an optimization for extractelement 411 // that will delete our widening shuffle. This would trigger another attempt 412 // here to create that shuffle, and we spin forever. 413 if (InsertionBlock != InsElt->getParent()) 414 return; 415 416 // TODO: This restriction matches the check in visitInsertElementInst() and 417 // prevents an infinite loop caused by not turning the extract/insert pair 418 // into a shuffle. We really should not need either check, but we're lacking 419 // folds for shufflevectors because we're afraid to generate shuffle masks 420 // that the backend can't handle. 421 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 422 return; 423 424 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 425 ConstantVector::get(ExtendMask)); 426 427 // Insert the new shuffle after the vector operand of the extract is defined 428 // (as long as it's not a PHI) or at the start of the basic block of the 429 // extract, so any subsequent extracts in the same basic block can use it. 430 // TODO: Insert before the earliest ExtractElementInst that is replaced. 431 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 432 WideVec->insertAfter(ExtVecOpInst); 433 else 434 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 435 436 // Replace extracts from the original narrow vector with extracts from the new 437 // wide vector. 438 for (User *U : ExtVecOp->users()) { 439 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 440 if (!OldExt || OldExt->getParent() != WideVec->getParent()) 441 continue; 442 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 443 NewExt->insertAfter(WideVec); 444 IC.replaceInstUsesWith(*OldExt, NewExt); 445 } 446 } 447 448 /// We are building a shuffle to create V, which is a sequence of insertelement, 449 /// extractelement pairs. If PermittedRHS is set, then we must either use it or 450 /// not rely on the second vector source. Return a std::pair containing the 451 /// left and right vectors of the proposed shuffle (or 0), and set the Mask 452 /// parameter as required. 453 /// 454 /// Note: we intentionally don't try to fold earlier shuffles since they have 455 /// often been chosen carefully to be efficiently implementable on the target. 456 typedef std::pair<Value *, Value *> ShuffleOps; 457 458 static ShuffleOps collectShuffleElements(Value *V, 459 SmallVectorImpl<Constant *> &Mask, 460 Value *PermittedRHS, 461 InstCombiner &IC) { 462 assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 463 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); 464 465 if (isa<UndefValue>(V)) { 466 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 467 return std::make_pair( 468 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 469 } 470 471 if (isa<ConstantAggregateZero>(V)) { 472 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 473 return std::make_pair(V, nullptr); 474 } 475 476 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 477 // If this is an insert of an extract from some other vector, include it. 478 Value *VecOp = IEI->getOperand(0); 479 Value *ScalarOp = IEI->getOperand(1); 480 Value *IdxOp = IEI->getOperand(2); 481 482 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 483 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 484 unsigned ExtractedIdx = 485 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 486 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 487 488 // Either the extracted from or inserted into vector must be RHSVec, 489 // otherwise we'd end up with a shuffle of three inputs. 490 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 491 Value *RHS = EI->getOperand(0); 492 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 493 assert(LR.second == nullptr || LR.second == RHS); 494 495 if (LR.first->getType() != RHS->getType()) { 496 // Although we are giving up for now, see if we can create extracts 497 // that match the inserts for another round of combining. 498 replaceExtractElements(IEI, EI, IC); 499 500 // We tried our best, but we can't find anything compatible with RHS 501 // further up the chain. Return a trivial shuffle. 502 for (unsigned i = 0; i < NumElts; ++i) 503 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 504 return std::make_pair(V, nullptr); 505 } 506 507 unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 508 Mask[InsertedIdx % NumElts] = 509 ConstantInt::get(Type::getInt32Ty(V->getContext()), 510 NumLHSElts+ExtractedIdx); 511 return std::make_pair(LR.first, RHS); 512 } 513 514 if (VecOp == PermittedRHS) { 515 // We've gone as far as we can: anything on the other side of the 516 // extractelement will already have been converted into a shuffle. 517 unsigned NumLHSElts = 518 EI->getOperand(0)->getType()->getVectorNumElements(); 519 for (unsigned i = 0; i != NumElts; ++i) 520 Mask.push_back(ConstantInt::get( 521 Type::getInt32Ty(V->getContext()), 522 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 523 return std::make_pair(EI->getOperand(0), PermittedRHS); 524 } 525 526 // If this insertelement is a chain that comes from exactly these two 527 // vectors, return the vector and the effective shuffle. 528 if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 529 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 530 Mask)) 531 return std::make_pair(EI->getOperand(0), PermittedRHS); 532 } 533 } 534 } 535 536 // Otherwise, we can't do anything fancy. Return an identity vector. 537 for (unsigned i = 0; i != NumElts; ++i) 538 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 539 return std::make_pair(V, nullptr); 540 } 541 542 /// Try to find redundant insertvalue instructions, like the following ones: 543 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 544 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 545 /// Here the second instruction inserts values at the same indices, as the 546 /// first one, making the first one redundant. 547 /// It should be transformed to: 548 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 549 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 550 bool IsRedundant = false; 551 ArrayRef<unsigned int> FirstIndices = I.getIndices(); 552 553 // If there is a chain of insertvalue instructions (each of them except the 554 // last one has only one use and it's another insertvalue insn from this 555 // chain), check if any of the 'children' uses the same indices as the first 556 // instruction. In this case, the first one is redundant. 557 Value *V = &I; 558 unsigned Depth = 0; 559 while (V->hasOneUse() && Depth < 10) { 560 User *U = V->user_back(); 561 auto UserInsInst = dyn_cast<InsertValueInst>(U); 562 if (!UserInsInst || U->getOperand(0) != V) 563 break; 564 if (UserInsInst->getIndices() == FirstIndices) { 565 IsRedundant = true; 566 break; 567 } 568 V = UserInsInst; 569 Depth++; 570 } 571 572 if (IsRedundant) 573 return replaceInstUsesWith(I, I.getOperand(0)); 574 return nullptr; 575 } 576 577 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 578 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); 579 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); 580 581 // A vector select does not change the size of the operands. 582 if (MaskSize != VecSize) 583 return false; 584 585 // Each mask element must be undefined or choose a vector element from one of 586 // the source operands without crossing vector lanes. 587 for (int i = 0; i != MaskSize; ++i) { 588 int Elt = Shuf.getMaskValue(i); 589 if (Elt != -1 && Elt != i && Elt != i + VecSize) 590 return false; 591 } 592 593 return true; 594 } 595 596 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 597 /// --> shufflevector X, CVec', Mask' 598 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 599 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 600 // Bail out if the parent has more than one use. In that case, we'd be 601 // replacing the insertelt with a shuffle, and that's not a clear win. 602 if (!Inst || !Inst->hasOneUse()) 603 return nullptr; 604 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 605 // The shuffle must have a constant vector operand. The insertelt must have 606 // a constant scalar being inserted at a constant position in the vector. 607 Constant *ShufConstVec, *InsEltScalar; 608 uint64_t InsEltIndex; 609 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 610 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 611 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 612 return nullptr; 613 614 // Adding an element to an arbitrary shuffle could be expensive, but a 615 // shuffle that selects elements from vectors without crossing lanes is 616 // assumed cheap. 617 // If we're just adding a constant into that shuffle, it will still be 618 // cheap. 619 if (!isShuffleEquivalentToSelect(*Shuf)) 620 return nullptr; 621 622 // From the above 'select' check, we know that the mask has the same number 623 // of elements as the vector input operands. We also know that each constant 624 // input element is used in its lane and can not be used more than once by 625 // the shuffle. Therefore, replace the constant in the shuffle's constant 626 // vector with the insertelt constant. Replace the constant in the shuffle's 627 // mask vector with the insertelt index plus the length of the vector 628 // (because the constant vector operand of a shuffle is always the 2nd 629 // operand). 630 Constant *Mask = Shuf->getMask(); 631 unsigned NumElts = Mask->getType()->getVectorNumElements(); 632 SmallVector<Constant *, 16> NewShufElts(NumElts); 633 SmallVector<Constant *, 16> NewMaskElts(NumElts); 634 for (unsigned I = 0; I != NumElts; ++I) { 635 if (I == InsEltIndex) { 636 NewShufElts[I] = InsEltScalar; 637 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); 638 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); 639 } else { 640 // Copy over the existing values. 641 NewShufElts[I] = ShufConstVec->getAggregateElement(I); 642 NewMaskElts[I] = Mask->getAggregateElement(I); 643 } 644 } 645 646 // Create new operands for a shuffle that includes the constant of the 647 // original insertelt. The old shuffle will be dead now. 648 return new ShuffleVectorInst(Shuf->getOperand(0), 649 ConstantVector::get(NewShufElts), 650 ConstantVector::get(NewMaskElts)); 651 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 652 // Transform sequences of insertelements ops with constant data/indexes into 653 // a single shuffle op. 654 unsigned NumElts = InsElt.getType()->getNumElements(); 655 656 uint64_t InsertIdx[2]; 657 Constant *Val[2]; 658 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 659 !match(InsElt.getOperand(1), m_Constant(Val[0])) || 660 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 661 !match(IEI->getOperand(1), m_Constant(Val[1]))) 662 return nullptr; 663 SmallVector<Constant *, 16> Values(NumElts); 664 SmallVector<Constant *, 16> Mask(NumElts); 665 auto ValI = std::begin(Val); 666 // Generate new constant vector and mask. 667 // We have 2 values/masks from the insertelements instructions. Insert them 668 // into new value/mask vectors. 669 for (uint64_t I : InsertIdx) { 670 if (!Values[I]) { 671 assert(!Mask[I]); 672 Values[I] = *ValI; 673 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 674 NumElts + I); 675 } 676 ++ValI; 677 } 678 // Remaining values are filled with 'undef' values. 679 for (unsigned I = 0; I < NumElts; ++I) { 680 if (!Values[I]) { 681 assert(!Mask[I]); 682 Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 683 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); 684 } 685 } 686 // Create new operands for a shuffle that includes the constant of the 687 // original insertelt. 688 return new ShuffleVectorInst(IEI->getOperand(0), 689 ConstantVector::get(Values), 690 ConstantVector::get(Mask)); 691 } 692 return nullptr; 693 } 694 695 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 696 Value *VecOp = IE.getOperand(0); 697 Value *ScalarOp = IE.getOperand(1); 698 Value *IdxOp = IE.getOperand(2); 699 700 // Inserting an undef or into an undefined place, remove this. 701 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 702 replaceInstUsesWith(IE, VecOp); 703 704 // If the inserted element was extracted from some other vector, and if the 705 // indexes are constant, try to turn this into a shufflevector operation. 706 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 707 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 708 unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 709 unsigned NumExtractVectorElts = 710 EI->getOperand(0)->getType()->getVectorNumElements(); 711 unsigned ExtractedIdx = 712 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 713 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 714 715 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 716 return replaceInstUsesWith(IE, VecOp); 717 718 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 719 return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 720 721 // If we are extracting a value from a vector, then inserting it right 722 // back into the same place, just use the input vector. 723 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 724 return replaceInstUsesWith(IE, VecOp); 725 726 // If this insertelement isn't used by some other insertelement, turn it 727 // (and any insertelements it points to), into one big shuffle. 728 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 729 SmallVector<Constant*, 16> Mask; 730 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 731 732 // The proposed shuffle may be trivial, in which case we shouldn't 733 // perform the combine. 734 if (LR.first != &IE && LR.second != &IE) { 735 // We now have a shuffle of LHS, RHS, Mask. 736 if (LR.second == nullptr) 737 LR.second = UndefValue::get(LR.first->getType()); 738 return new ShuffleVectorInst(LR.first, LR.second, 739 ConstantVector::get(Mask)); 740 } 741 } 742 } 743 } 744 745 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements(); 746 APInt UndefElts(VWidth, 0); 747 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 748 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 749 if (V != &IE) 750 return replaceInstUsesWith(IE, V); 751 return &IE; 752 } 753 754 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 755 return Shuf; 756 757 return nullptr; 758 } 759 760 /// Return true if we can evaluate the specified expression tree if the vector 761 /// elements were shuffled in a different order. 762 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 763 unsigned Depth = 5) { 764 // We can always reorder the elements of a constant. 765 if (isa<Constant>(V)) 766 return true; 767 768 // We won't reorder vector arguments. No IPO here. 769 Instruction *I = dyn_cast<Instruction>(V); 770 if (!I) return false; 771 772 // Two users may expect different orders of the elements. Don't try it. 773 if (!I->hasOneUse()) 774 return false; 775 776 if (Depth == 0) return false; 777 778 switch (I->getOpcode()) { 779 case Instruction::Add: 780 case Instruction::FAdd: 781 case Instruction::Sub: 782 case Instruction::FSub: 783 case Instruction::Mul: 784 case Instruction::FMul: 785 case Instruction::UDiv: 786 case Instruction::SDiv: 787 case Instruction::FDiv: 788 case Instruction::URem: 789 case Instruction::SRem: 790 case Instruction::FRem: 791 case Instruction::Shl: 792 case Instruction::LShr: 793 case Instruction::AShr: 794 case Instruction::And: 795 case Instruction::Or: 796 case Instruction::Xor: 797 case Instruction::ICmp: 798 case Instruction::FCmp: 799 case Instruction::Trunc: 800 case Instruction::ZExt: 801 case Instruction::SExt: 802 case Instruction::FPToUI: 803 case Instruction::FPToSI: 804 case Instruction::UIToFP: 805 case Instruction::SIToFP: 806 case Instruction::FPTrunc: 807 case Instruction::FPExt: 808 case Instruction::GetElementPtr: { 809 for (Value *Operand : I->operands()) { 810 if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 811 return false; 812 } 813 return true; 814 } 815 case Instruction::InsertElement: { 816 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 817 if (!CI) return false; 818 int ElementNumber = CI->getLimitedValue(); 819 820 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 821 // can't put an element into multiple indices. 822 bool SeenOnce = false; 823 for (int i = 0, e = Mask.size(); i != e; ++i) { 824 if (Mask[i] == ElementNumber) { 825 if (SeenOnce) 826 return false; 827 SeenOnce = true; 828 } 829 } 830 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 831 } 832 } 833 return false; 834 } 835 836 /// Rebuild a new instruction just like 'I' but with the new operands given. 837 /// In the event of type mismatch, the type of the operands is correct. 838 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 839 // We don't want to use the IRBuilder here because we want the replacement 840 // instructions to appear next to 'I', not the builder's insertion point. 841 switch (I->getOpcode()) { 842 case Instruction::Add: 843 case Instruction::FAdd: 844 case Instruction::Sub: 845 case Instruction::FSub: 846 case Instruction::Mul: 847 case Instruction::FMul: 848 case Instruction::UDiv: 849 case Instruction::SDiv: 850 case Instruction::FDiv: 851 case Instruction::URem: 852 case Instruction::SRem: 853 case Instruction::FRem: 854 case Instruction::Shl: 855 case Instruction::LShr: 856 case Instruction::AShr: 857 case Instruction::And: 858 case Instruction::Or: 859 case Instruction::Xor: { 860 BinaryOperator *BO = cast<BinaryOperator>(I); 861 assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 862 BinaryOperator *New = 863 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 864 NewOps[0], NewOps[1], "", BO); 865 if (isa<OverflowingBinaryOperator>(BO)) { 866 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 867 New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 868 } 869 if (isa<PossiblyExactOperator>(BO)) { 870 New->setIsExact(BO->isExact()); 871 } 872 if (isa<FPMathOperator>(BO)) 873 New->copyFastMathFlags(I); 874 return New; 875 } 876 case Instruction::ICmp: 877 assert(NewOps.size() == 2 && "icmp with #ops != 2"); 878 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 879 NewOps[0], NewOps[1]); 880 case Instruction::FCmp: 881 assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 882 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 883 NewOps[0], NewOps[1]); 884 case Instruction::Trunc: 885 case Instruction::ZExt: 886 case Instruction::SExt: 887 case Instruction::FPToUI: 888 case Instruction::FPToSI: 889 case Instruction::UIToFP: 890 case Instruction::SIToFP: 891 case Instruction::FPTrunc: 892 case Instruction::FPExt: { 893 // It's possible that the mask has a different number of elements from 894 // the original cast. We recompute the destination type to match the mask. 895 Type *DestTy = 896 VectorType::get(I->getType()->getScalarType(), 897 NewOps[0]->getType()->getVectorNumElements()); 898 assert(NewOps.size() == 1 && "cast with #ops != 1"); 899 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 900 "", I); 901 } 902 case Instruction::GetElementPtr: { 903 Value *Ptr = NewOps[0]; 904 ArrayRef<Value*> Idx = NewOps.slice(1); 905 GetElementPtrInst *GEP = GetElementPtrInst::Create( 906 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 907 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 908 return GEP; 909 } 910 } 911 llvm_unreachable("failed to rebuild vector instructions"); 912 } 913 914 Value * 915 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 916 // Mask.size() does not need to be equal to the number of vector elements. 917 918 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 919 if (isa<UndefValue>(V)) { 920 return UndefValue::get(VectorType::get(V->getType()->getScalarType(), 921 Mask.size())); 922 } 923 if (isa<ConstantAggregateZero>(V)) { 924 return ConstantAggregateZero::get( 925 VectorType::get(V->getType()->getScalarType(), 926 Mask.size())); 927 } 928 if (Constant *C = dyn_cast<Constant>(V)) { 929 SmallVector<Constant *, 16> MaskValues; 930 for (int i = 0, e = Mask.size(); i != e; ++i) { 931 if (Mask[i] == -1) 932 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty())); 933 else 934 MaskValues.push_back(Builder->getInt32(Mask[i])); 935 } 936 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 937 ConstantVector::get(MaskValues)); 938 } 939 940 Instruction *I = cast<Instruction>(V); 941 switch (I->getOpcode()) { 942 case Instruction::Add: 943 case Instruction::FAdd: 944 case Instruction::Sub: 945 case Instruction::FSub: 946 case Instruction::Mul: 947 case Instruction::FMul: 948 case Instruction::UDiv: 949 case Instruction::SDiv: 950 case Instruction::FDiv: 951 case Instruction::URem: 952 case Instruction::SRem: 953 case Instruction::FRem: 954 case Instruction::Shl: 955 case Instruction::LShr: 956 case Instruction::AShr: 957 case Instruction::And: 958 case Instruction::Or: 959 case Instruction::Xor: 960 case Instruction::ICmp: 961 case Instruction::FCmp: 962 case Instruction::Trunc: 963 case Instruction::ZExt: 964 case Instruction::SExt: 965 case Instruction::FPToUI: 966 case Instruction::FPToSI: 967 case Instruction::UIToFP: 968 case Instruction::SIToFP: 969 case Instruction::FPTrunc: 970 case Instruction::FPExt: 971 case Instruction::Select: 972 case Instruction::GetElementPtr: { 973 SmallVector<Value*, 8> NewOps; 974 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 975 for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 976 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 977 NewOps.push_back(V); 978 NeedsRebuild |= (V != I->getOperand(i)); 979 } 980 if (NeedsRebuild) { 981 return buildNew(I, NewOps); 982 } 983 return I; 984 } 985 case Instruction::InsertElement: { 986 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 987 988 // The insertelement was inserting at Element. Figure out which element 989 // that becomes after shuffling. The answer is guaranteed to be unique 990 // by CanEvaluateShuffled. 991 bool Found = false; 992 int Index = 0; 993 for (int e = Mask.size(); Index != e; ++Index) { 994 if (Mask[Index] == Element) { 995 Found = true; 996 break; 997 } 998 } 999 1000 // If element is not in Mask, no need to handle the operand 1 (element to 1001 // be inserted). Just evaluate values in operand 0 according to Mask. 1002 if (!Found) 1003 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1004 1005 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1006 return InsertElementInst::Create(V, I->getOperand(1), 1007 Builder->getInt32(Index), "", I); 1008 } 1009 } 1010 llvm_unreachable("failed to reorder elements of vector instruction!"); 1011 } 1012 1013 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 1014 bool &isLHSID, bool &isRHSID) { 1015 isLHSID = isRHSID = true; 1016 1017 for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 1018 if (Mask[i] < 0) continue; // Ignore undef values. 1019 // Is this an identity shuffle of the LHS value? 1020 isLHSID &= (Mask[i] == (int)i); 1021 1022 // Is this an identity shuffle of the RHS value? 1023 isRHSID &= (Mask[i]-e == i); 1024 } 1025 } 1026 1027 // Returns true if the shuffle is extracting a contiguous range of values from 1028 // LHS, for example: 1029 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1030 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1031 // Shuffles to: |EE|FF|GG|HH| 1032 // +--+--+--+--+ 1033 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1034 SmallVector<int, 16> &Mask) { 1035 unsigned LHSElems = 1036 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements(); 1037 unsigned MaskElems = Mask.size(); 1038 unsigned BegIdx = Mask.front(); 1039 unsigned EndIdx = Mask.back(); 1040 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1041 return false; 1042 for (unsigned I = 0; I != MaskElems; ++I) 1043 if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1044 return false; 1045 return true; 1046 } 1047 1048 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 1049 Value *LHS = SVI.getOperand(0); 1050 Value *RHS = SVI.getOperand(1); 1051 SmallVector<int, 16> Mask = SVI.getShuffleMask(); 1052 Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 1053 1054 bool MadeChange = false; 1055 1056 // Undefined shuffle mask -> undefined value. 1057 if (isa<UndefValue>(SVI.getOperand(2))) 1058 return replaceInstUsesWith(SVI, UndefValue::get(SVI.getType())); 1059 1060 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements(); 1061 1062 APInt UndefElts(VWidth, 0); 1063 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1064 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 1065 if (V != &SVI) 1066 return replaceInstUsesWith(SVI, V); 1067 LHS = SVI.getOperand(0); 1068 RHS = SVI.getOperand(1); 1069 MadeChange = true; 1070 } 1071 1072 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements(); 1073 1074 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 1075 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 1076 if (LHS == RHS || isa<UndefValue>(LHS)) { 1077 if (isa<UndefValue>(LHS) && LHS == RHS) { 1078 // shuffle(undef,undef,mask) -> undef. 1079 Value *Result = (VWidth == LHSWidth) 1080 ? LHS : UndefValue::get(SVI.getType()); 1081 return replaceInstUsesWith(SVI, Result); 1082 } 1083 1084 // Remap any references to RHS to use LHS. 1085 SmallVector<Constant*, 16> Elts; 1086 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 1087 if (Mask[i] < 0) { 1088 Elts.push_back(UndefValue::get(Int32Ty)); 1089 continue; 1090 } 1091 1092 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 1093 (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 1094 Mask[i] = -1; // Turn into undef. 1095 Elts.push_back(UndefValue::get(Int32Ty)); 1096 } else { 1097 Mask[i] = Mask[i] % e; // Force to LHS. 1098 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 1099 } 1100 } 1101 SVI.setOperand(0, SVI.getOperand(1)); 1102 SVI.setOperand(1, UndefValue::get(RHS->getType())); 1103 SVI.setOperand(2, ConstantVector::get(Elts)); 1104 LHS = SVI.getOperand(0); 1105 RHS = SVI.getOperand(1); 1106 MadeChange = true; 1107 } 1108 1109 if (VWidth == LHSWidth) { 1110 // Analyze the shuffle, are the LHS or RHS and identity shuffles? 1111 bool isLHSID, isRHSID; 1112 recognizeIdentityMask(Mask, isLHSID, isRHSID); 1113 1114 // Eliminate identity shuffles. 1115 if (isLHSID) return replaceInstUsesWith(SVI, LHS); 1116 if (isRHSID) return replaceInstUsesWith(SVI, RHS); 1117 } 1118 1119 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 1120 Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 1121 return replaceInstUsesWith(SVI, V); 1122 } 1123 1124 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 1125 // a non-vector type. We can instead bitcast the original vector followed by 1126 // an extract of the desired element: 1127 // 1128 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1129 // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1130 // %1 = bitcast <4 x i8> %sroa to i32 1131 // Becomes: 1132 // %bc = bitcast <16 x i8> %in to <4 x i32> 1133 // %ext = extractelement <4 x i32> %bc, i32 0 1134 // 1135 // If the shuffle is extracting a contiguous range of values from the input 1136 // vector then each use which is a bitcast of the extracted size can be 1137 // replaced. This will work if the vector types are compatible, and the begin 1138 // index is aligned to a value in the casted vector type. If the begin index 1139 // isn't aligned then we can shuffle the original vector (keeping the same 1140 // vector type) before extracting. 1141 // 1142 // This code will bail out if the target type is fundamentally incompatible 1143 // with vectors of the source type. 1144 // 1145 // Example of <16 x i8>, target type i32: 1146 // Index range [4,8): v-----------v Will work. 1147 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1148 // <16 x i8>: | | | | | | | | | | | | | | | | | 1149 // <4 x i32>: | | | | | 1150 // +-----------+-----------+-----------+-----------+ 1151 // Index range [6,10): ^-----------^ Needs an extra shuffle. 1152 // Target type i40: ^--------------^ Won't work, bail. 1153 if (isShuffleExtractingFromLHS(SVI, Mask)) { 1154 Value *V = LHS; 1155 unsigned MaskElems = Mask.size(); 1156 unsigned BegIdx = Mask.front(); 1157 VectorType *SrcTy = cast<VectorType>(V->getType()); 1158 unsigned VecBitWidth = SrcTy->getBitWidth(); 1159 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1160 assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1161 unsigned SrcNumElems = SrcTy->getNumElements(); 1162 SmallVector<BitCastInst *, 8> BCs; 1163 DenseMap<Type *, Value *> NewBCs; 1164 for (User *U : SVI.users()) 1165 if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1166 if (!BC->use_empty()) 1167 // Only visit bitcasts that weren't previously handled. 1168 BCs.push_back(BC); 1169 for (BitCastInst *BC : BCs) { 1170 Type *TgtTy = BC->getDestTy(); 1171 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1172 if (!TgtElemBitWidth) 1173 continue; 1174 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1175 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1176 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1177 if (!VecBitWidthsEqual) 1178 continue; 1179 if (!VectorType::isValidElementType(TgtTy)) 1180 continue; 1181 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1182 if (!BegIsAligned) { 1183 // Shuffle the input so [0,NumElements) contains the output, and 1184 // [NumElems,SrcNumElems) is undef. 1185 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1186 UndefValue::get(Int32Ty)); 1187 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1188 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1189 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()), 1190 ConstantVector::get(ShuffleMask), 1191 SVI.getName() + ".extract"); 1192 BegIdx = 0; 1193 } 1194 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1195 assert(SrcElemsPerTgtElem); 1196 BegIdx /= SrcElemsPerTgtElem; 1197 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1198 auto *NewBC = 1199 BCAlreadyExists 1200 ? NewBCs[CastSrcTy] 1201 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1202 if (!BCAlreadyExists) 1203 NewBCs[CastSrcTy] = NewBC; 1204 auto *Ext = Builder->CreateExtractElement( 1205 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1206 // The shufflevector isn't being replaced: the bitcast that used it 1207 // is. InstCombine will visit the newly-created instructions. 1208 replaceInstUsesWith(*BC, Ext); 1209 MadeChange = true; 1210 } 1211 } 1212 1213 // If the LHS is a shufflevector itself, see if we can combine it with this 1214 // one without producing an unusual shuffle. 1215 // Cases that might be simplified: 1216 // 1. 1217 // x1=shuffle(v1,v2,mask1) 1218 // x=shuffle(x1,undef,mask) 1219 // ==> 1220 // x=shuffle(v1,undef,newMask) 1221 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1222 // 2. 1223 // x1=shuffle(v1,undef,mask1) 1224 // x=shuffle(x1,x2,mask) 1225 // where v1.size() == mask1.size() 1226 // ==> 1227 // x=shuffle(v1,x2,newMask) 1228 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1229 // 3. 1230 // x2=shuffle(v2,undef,mask2) 1231 // x=shuffle(x1,x2,mask) 1232 // where v2.size() == mask2.size() 1233 // ==> 1234 // x=shuffle(x1,v2,newMask) 1235 // newMask[i] = (mask[i] < x1.size()) 1236 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1237 // 4. 1238 // x1=shuffle(v1,undef,mask1) 1239 // x2=shuffle(v2,undef,mask2) 1240 // x=shuffle(x1,x2,mask) 1241 // where v1.size() == v2.size() 1242 // ==> 1243 // x=shuffle(v1,v2,newMask) 1244 // newMask[i] = (mask[i] < x1.size()) 1245 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1246 // 1247 // Here we are really conservative: 1248 // we are absolutely afraid of producing a shuffle mask not in the input 1249 // program, because the code gen may not be smart enough to turn a merged 1250 // shuffle into two specific shuffles: it may produce worse code. As such, 1251 // we only merge two shuffles if the result is either a splat or one of the 1252 // input shuffle masks. In this case, merging the shuffles just removes 1253 // one instruction, which we know is safe. This is good for things like 1254 // turning: (splat(splat)) -> splat, or 1255 // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1256 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1257 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1258 if (LHSShuffle) 1259 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 1260 LHSShuffle = nullptr; 1261 if (RHSShuffle) 1262 if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 1263 RHSShuffle = nullptr; 1264 if (!LHSShuffle && !RHSShuffle) 1265 return MadeChange ? &SVI : nullptr; 1266 1267 Value* LHSOp0 = nullptr; 1268 Value* LHSOp1 = nullptr; 1269 Value* RHSOp0 = nullptr; 1270 unsigned LHSOp0Width = 0; 1271 unsigned RHSOp0Width = 0; 1272 if (LHSShuffle) { 1273 LHSOp0 = LHSShuffle->getOperand(0); 1274 LHSOp1 = LHSShuffle->getOperand(1); 1275 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements(); 1276 } 1277 if (RHSShuffle) { 1278 RHSOp0 = RHSShuffle->getOperand(0); 1279 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements(); 1280 } 1281 Value* newLHS = LHS; 1282 Value* newRHS = RHS; 1283 if (LHSShuffle) { 1284 // case 1 1285 if (isa<UndefValue>(RHS)) { 1286 newLHS = LHSOp0; 1287 newRHS = LHSOp1; 1288 } 1289 // case 2 or 4 1290 else if (LHSOp0Width == LHSWidth) { 1291 newLHS = LHSOp0; 1292 } 1293 } 1294 // case 3 or 4 1295 if (RHSShuffle && RHSOp0Width == LHSWidth) { 1296 newRHS = RHSOp0; 1297 } 1298 // case 4 1299 if (LHSOp0 == RHSOp0) { 1300 newLHS = LHSOp0; 1301 newRHS = nullptr; 1302 } 1303 1304 if (newLHS == LHS && newRHS == RHS) 1305 return MadeChange ? &SVI : nullptr; 1306 1307 SmallVector<int, 16> LHSMask; 1308 SmallVector<int, 16> RHSMask; 1309 if (newLHS != LHS) 1310 LHSMask = LHSShuffle->getShuffleMask(); 1311 if (RHSShuffle && newRHS != RHS) 1312 RHSMask = RHSShuffle->getShuffleMask(); 1313 1314 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1315 SmallVector<int, 16> newMask; 1316 bool isSplat = true; 1317 int SplatElt = -1; 1318 // Create a new mask for the new ShuffleVectorInst so that the new 1319 // ShuffleVectorInst is equivalent to the original one. 1320 for (unsigned i = 0; i < VWidth; ++i) { 1321 int eltMask; 1322 if (Mask[i] < 0) { 1323 // This element is an undef value. 1324 eltMask = -1; 1325 } else if (Mask[i] < (int)LHSWidth) { 1326 // This element is from left hand side vector operand. 1327 // 1328 // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1329 // new mask value for the element. 1330 if (newLHS != LHS) { 1331 eltMask = LHSMask[Mask[i]]; 1332 // If the value selected is an undef value, explicitly specify it 1333 // with a -1 mask value. 1334 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1335 eltMask = -1; 1336 } else 1337 eltMask = Mask[i]; 1338 } else { 1339 // This element is from right hand side vector operand 1340 // 1341 // If the value selected is an undef value, explicitly specify it 1342 // with a -1 mask value. (case 1) 1343 if (isa<UndefValue>(RHS)) 1344 eltMask = -1; 1345 // If RHS is going to be replaced (case 3 or 4), calculate the 1346 // new mask value for the element. 1347 else if (newRHS != RHS) { 1348 eltMask = RHSMask[Mask[i]-LHSWidth]; 1349 // If the value selected is an undef value, explicitly specify it 1350 // with a -1 mask value. 1351 if (eltMask >= (int)RHSOp0Width) { 1352 assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1353 && "should have been check above"); 1354 eltMask = -1; 1355 } 1356 } else 1357 eltMask = Mask[i]-LHSWidth; 1358 1359 // If LHS's width is changed, shift the mask value accordingly. 1360 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any 1361 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 1362 // If newRHS == newLHS, we want to remap any references from newRHS to 1363 // newLHS so that we can properly identify splats that may occur due to 1364 // obfuscation across the two vectors. 1365 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1366 eltMask += newLHSWidth; 1367 } 1368 1369 // Check if this could still be a splat. 1370 if (eltMask >= 0) { 1371 if (SplatElt >= 0 && SplatElt != eltMask) 1372 isSplat = false; 1373 SplatElt = eltMask; 1374 } 1375 1376 newMask.push_back(eltMask); 1377 } 1378 1379 // If the result mask is equal to one of the original shuffle masks, 1380 // or is a splat, do the replacement. 1381 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1382 SmallVector<Constant*, 16> Elts; 1383 for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1384 if (newMask[i] < 0) { 1385 Elts.push_back(UndefValue::get(Int32Ty)); 1386 } else { 1387 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1388 } 1389 } 1390 if (!newRHS) 1391 newRHS = UndefValue::get(newLHS->getType()); 1392 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1393 } 1394 1395 // If the result mask is an identity, replace uses of this instruction with 1396 // corresponding argument. 1397 bool isLHSID, isRHSID; 1398 recognizeIdentityMask(newMask, isLHSID, isRHSID); 1399 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 1400 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 1401 1402 return MadeChange ? &SVI : nullptr; 1403 } 1404