1 //===------- VectorCombine.cpp - Optimize partial vector operations -------===// 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 pass optimizes scalar/vector interactions using target cost models. The 10 // transforms implemented here may not fit in traditional loop-based or SLP 11 // vectorization passes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Vectorize/VectorCombine.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/ScopeExit.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AssumptionCache.h" 21 #include "llvm/Analysis/BasicAliasAnalysis.h" 22 #include "llvm/Analysis/GlobalsModRef.h" 23 #include "llvm/Analysis/Loads.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/Analysis/VectorUtils.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/IRBuilder.h" 30 #include "llvm/IR/PatternMatch.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 #include "llvm/Transforms/Utils/LoopUtils.h" 34 #include <numeric> 35 #include <queue> 36 37 #define DEBUG_TYPE "vector-combine" 38 #include "llvm/Transforms/Utils/InstructionWorklist.h" 39 40 using namespace llvm; 41 using namespace llvm::PatternMatch; 42 43 STATISTIC(NumVecLoad, "Number of vector loads formed"); 44 STATISTIC(NumVecCmp, "Number of vector compares formed"); 45 STATISTIC(NumVecBO, "Number of vector binops formed"); 46 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed"); 47 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast"); 48 STATISTIC(NumScalarBO, "Number of scalar binops formed"); 49 STATISTIC(NumScalarCmp, "Number of scalar compares formed"); 50 51 static cl::opt<bool> DisableVectorCombine( 52 "disable-vector-combine", cl::init(false), cl::Hidden, 53 cl::desc("Disable all vector combine transforms")); 54 55 static cl::opt<bool> DisableBinopExtractShuffle( 56 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden, 57 cl::desc("Disable binop extract to shuffle transforms")); 58 59 static cl::opt<unsigned> MaxInstrsToScan( 60 "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden, 61 cl::desc("Max number of instructions to scan for vector combining.")); 62 63 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max(); 64 65 namespace { 66 class VectorCombine { 67 public: 68 VectorCombine(Function &F, const TargetTransformInfo &TTI, 69 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC, 70 const DataLayout *DL, TTI::TargetCostKind CostKind, 71 bool TryEarlyFoldsOnly) 72 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC), DL(DL), 73 CostKind(CostKind), TryEarlyFoldsOnly(TryEarlyFoldsOnly) {} 74 75 bool run(); 76 77 private: 78 Function &F; 79 IRBuilder<> Builder; 80 const TargetTransformInfo &TTI; 81 const DominatorTree &DT; 82 AAResults &AA; 83 AssumptionCache &AC; 84 const DataLayout *DL; 85 TTI::TargetCostKind CostKind; 86 87 /// If true, only perform beneficial early IR transforms. Do not introduce new 88 /// vector operations. 89 bool TryEarlyFoldsOnly; 90 91 InstructionWorklist Worklist; 92 93 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction" 94 // parameter. That should be updated to specific sub-classes because the 95 // run loop was changed to dispatch on opcode. 96 bool vectorizeLoadInsert(Instruction &I); 97 bool widenSubvectorLoad(Instruction &I); 98 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0, 99 ExtractElementInst *Ext1, 100 unsigned PreferredExtractIndex) const; 101 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 102 const Instruction &I, 103 ExtractElementInst *&ConvertToShuffle, 104 unsigned PreferredExtractIndex); 105 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 106 Instruction &I); 107 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 108 Instruction &I); 109 bool foldExtractExtract(Instruction &I); 110 bool foldInsExtFNeg(Instruction &I); 111 bool foldInsExtVectorToShuffle(Instruction &I); 112 bool foldBitcastShuffle(Instruction &I); 113 bool scalarizeBinopOrCmp(Instruction &I); 114 bool scalarizeVPIntrinsic(Instruction &I); 115 bool foldExtractedCmps(Instruction &I); 116 bool foldSingleElementStore(Instruction &I); 117 bool scalarizeLoadExtract(Instruction &I); 118 bool foldConcatOfBoolMasks(Instruction &I); 119 bool foldPermuteOfBinops(Instruction &I); 120 bool foldShuffleOfBinops(Instruction &I); 121 bool foldShuffleOfCastops(Instruction &I); 122 bool foldShuffleOfShuffles(Instruction &I); 123 bool foldShuffleOfIntrinsics(Instruction &I); 124 bool foldShuffleToIdentity(Instruction &I); 125 bool foldShuffleFromReductions(Instruction &I); 126 bool foldCastFromReductions(Instruction &I); 127 bool foldSelectShuffle(Instruction &I, bool FromReduction = false); 128 bool shrinkType(Instruction &I); 129 130 void replaceValue(Value &Old, Value &New) { 131 LLVM_DEBUG(dbgs() << "VC: Replacing: " << Old << '\n'); 132 LLVM_DEBUG(dbgs() << " With: " << New << '\n'); 133 Old.replaceAllUsesWith(&New); 134 if (auto *NewI = dyn_cast<Instruction>(&New)) { 135 New.takeName(&Old); 136 Worklist.pushUsersToWorkList(*NewI); 137 Worklist.pushValue(NewI); 138 } 139 Worklist.pushValue(&Old); 140 } 141 142 void eraseInstruction(Instruction &I) { 143 LLVM_DEBUG(dbgs() << "VC: Erasing: " << I << '\n'); 144 SmallVector<Value *> Ops(I.operands()); 145 Worklist.remove(&I); 146 I.eraseFromParent(); 147 148 // Push remaining users of the operands and then the operand itself - allows 149 // further folds that were hindered by OneUse limits. 150 for (Value *Op : Ops) 151 if (auto *OpI = dyn_cast<Instruction>(Op)) { 152 Worklist.pushUsersToWorkList(*OpI); 153 Worklist.pushValue(OpI); 154 } 155 } 156 }; 157 } // namespace 158 159 /// Return the source operand of a potentially bitcasted value. If there is no 160 /// bitcast, return the input value itself. 161 static Value *peekThroughBitcasts(Value *V) { 162 while (auto *BitCast = dyn_cast<BitCastInst>(V)) 163 V = BitCast->getOperand(0); 164 return V; 165 } 166 167 static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) { 168 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan. 169 // The widened load may load data from dirty regions or create data races 170 // non-existent in the source. 171 if (!Load || !Load->isSimple() || !Load->hasOneUse() || 172 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) || 173 mustSuppressSpeculation(*Load)) 174 return false; 175 176 // We are potentially transforming byte-sized (8-bit) memory accesses, so make 177 // sure we have all of our type-based constraints in place for this target. 178 Type *ScalarTy = Load->getType()->getScalarType(); 179 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits(); 180 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth(); 181 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 || 182 ScalarSize % 8 != 0) 183 return false; 184 185 return true; 186 } 187 188 bool VectorCombine::vectorizeLoadInsert(Instruction &I) { 189 // Match insert into fixed vector of scalar value. 190 // TODO: Handle non-zero insert index. 191 Value *Scalar; 192 if (!match(&I, 193 m_InsertElt(m_Poison(), m_OneUse(m_Value(Scalar)), m_ZeroInt()))) 194 return false; 195 196 // Optionally match an extract from another vector. 197 Value *X; 198 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt())); 199 if (!HasExtract) 200 X = Scalar; 201 202 auto *Load = dyn_cast<LoadInst>(X); 203 if (!canWidenLoad(Load, TTI)) 204 return false; 205 206 Type *ScalarTy = Scalar->getType(); 207 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits(); 208 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth(); 209 210 // Check safety of replacing the scalar load with a larger vector load. 211 // We use minimal alignment (maximum flexibility) because we only care about 212 // the dereferenceable region. When calculating cost and creating a new op, 213 // we may use a larger value based on alignment attributes. 214 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts(); 215 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type"); 216 217 unsigned MinVecNumElts = MinVectorSize / ScalarSize; 218 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false); 219 unsigned OffsetEltIndex = 0; 220 Align Alignment = Load->getAlign(); 221 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC, 222 &DT)) { 223 // It is not safe to load directly from the pointer, but we can still peek 224 // through gep offsets and check if it safe to load from a base address with 225 // updated alignment. If it is, we can shuffle the element(s) into place 226 // after loading. 227 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType()); 228 APInt Offset(OffsetBitWidth, 0); 229 SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); 230 231 // We want to shuffle the result down from a high element of a vector, so 232 // the offset must be positive. 233 if (Offset.isNegative()) 234 return false; 235 236 // The offset must be a multiple of the scalar element to shuffle cleanly 237 // in the element's size. 238 uint64_t ScalarSizeInBytes = ScalarSize / 8; 239 if (Offset.urem(ScalarSizeInBytes) != 0) 240 return false; 241 242 // If we load MinVecNumElts, will our target element still be loaded? 243 OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue(); 244 if (OffsetEltIndex >= MinVecNumElts) 245 return false; 246 247 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC, 248 &DT)) 249 return false; 250 251 // Update alignment with offset value. Note that the offset could be negated 252 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but 253 // negation does not change the result of the alignment calculation. 254 Alignment = commonAlignment(Alignment, Offset.getZExtValue()); 255 } 256 257 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0 258 // Use the greater of the alignment on the load or its source pointer. 259 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment); 260 Type *LoadTy = Load->getType(); 261 unsigned AS = Load->getPointerAddressSpace(); 262 InstructionCost OldCost = 263 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind); 264 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0); 265 OldCost += 266 TTI.getScalarizationOverhead(MinVecTy, DemandedElts, 267 /* Insert */ true, HasExtract, CostKind); 268 269 // New pattern: load VecPtr 270 InstructionCost NewCost = 271 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS, CostKind); 272 // Optionally, we are shuffling the loaded vector element(s) into place. 273 // For the mask set everything but element 0 to undef to prevent poison from 274 // propagating from the extra loaded memory. This will also optionally 275 // shrink/grow the vector from the loaded size to the output size. 276 // We assume this operation has no cost in codegen if there was no offset. 277 // Note that we could use freeze to avoid poison problems, but then we might 278 // still need a shuffle to change the vector size. 279 auto *Ty = cast<FixedVectorType>(I.getType()); 280 unsigned OutputNumElts = Ty->getNumElements(); 281 SmallVector<int, 16> Mask(OutputNumElts, PoisonMaskElem); 282 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big"); 283 Mask[0] = OffsetEltIndex; 284 if (OffsetEltIndex) 285 NewCost += 286 TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask, CostKind); 287 288 // We can aggressively convert to the vector form because the backend can 289 // invert this transform if it does not result in a performance win. 290 if (OldCost < NewCost || !NewCost.isValid()) 291 return false; 292 293 // It is safe and potentially profitable to load a vector directly: 294 // inselt undef, load Scalar, 0 --> load VecPtr 295 IRBuilder<> Builder(Load); 296 Value *CastedPtr = 297 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS)); 298 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment); 299 VecLd = Builder.CreateShuffleVector(VecLd, Mask); 300 301 replaceValue(I, *VecLd); 302 ++NumVecLoad; 303 return true; 304 } 305 306 /// If we are loading a vector and then inserting it into a larger vector with 307 /// undefined elements, try to load the larger vector and eliminate the insert. 308 /// This removes a shuffle in IR and may allow combining of other loaded values. 309 bool VectorCombine::widenSubvectorLoad(Instruction &I) { 310 // Match subvector insert of fixed vector. 311 auto *Shuf = cast<ShuffleVectorInst>(&I); 312 if (!Shuf->isIdentityWithPadding()) 313 return false; 314 315 // Allow a non-canonical shuffle mask that is choosing elements from op1. 316 unsigned NumOpElts = 317 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements(); 318 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) { 319 return M >= (int)(NumOpElts); 320 }); 321 322 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex)); 323 if (!canWidenLoad(Load, TTI)) 324 return false; 325 326 // We use minimal alignment (maximum flexibility) because we only care about 327 // the dereferenceable region. When calculating cost and creating a new op, 328 // we may use a larger value based on alignment attributes. 329 auto *Ty = cast<FixedVectorType>(I.getType()); 330 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts(); 331 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type"); 332 Align Alignment = Load->getAlign(); 333 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), *DL, Load, &AC, &DT)) 334 return false; 335 336 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment); 337 Type *LoadTy = Load->getType(); 338 unsigned AS = Load->getPointerAddressSpace(); 339 340 // Original pattern: insert_subvector (load PtrOp) 341 // This conservatively assumes that the cost of a subvector insert into an 342 // undef value is 0. We could add that cost if the cost model accurately 343 // reflects the real cost of that operation. 344 InstructionCost OldCost = 345 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind); 346 347 // New pattern: load PtrOp 348 InstructionCost NewCost = 349 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS, CostKind); 350 351 // We can aggressively convert to the vector form because the backend can 352 // invert this transform if it does not result in a performance win. 353 if (OldCost < NewCost || !NewCost.isValid()) 354 return false; 355 356 IRBuilder<> Builder(Load); 357 Value *CastedPtr = 358 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS)); 359 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment); 360 replaceValue(I, *VecLd); 361 ++NumVecLoad; 362 return true; 363 } 364 365 /// Determine which, if any, of the inputs should be replaced by a shuffle 366 /// followed by extract from a different index. 367 ExtractElementInst *VectorCombine::getShuffleExtract( 368 ExtractElementInst *Ext0, ExtractElementInst *Ext1, 369 unsigned PreferredExtractIndex = InvalidIndex) const { 370 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand()); 371 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand()); 372 assert(Index0C && Index1C && "Expected constant extract indexes"); 373 374 unsigned Index0 = Index0C->getZExtValue(); 375 unsigned Index1 = Index1C->getZExtValue(); 376 377 // If the extract indexes are identical, no shuffle is needed. 378 if (Index0 == Index1) 379 return nullptr; 380 381 Type *VecTy = Ext0->getVectorOperand()->getType(); 382 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types"); 383 InstructionCost Cost0 = 384 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0); 385 InstructionCost Cost1 = 386 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1); 387 388 // If both costs are invalid no shuffle is needed 389 if (!Cost0.isValid() && !Cost1.isValid()) 390 return nullptr; 391 392 // We are extracting from 2 different indexes, so one operand must be shuffled 393 // before performing a vector operation and/or extract. The more expensive 394 // extract will be replaced by a shuffle. 395 if (Cost0 > Cost1) 396 return Ext0; 397 if (Cost1 > Cost0) 398 return Ext1; 399 400 // If the costs are equal and there is a preferred extract index, shuffle the 401 // opposite operand. 402 if (PreferredExtractIndex == Index0) 403 return Ext1; 404 if (PreferredExtractIndex == Index1) 405 return Ext0; 406 407 // Otherwise, replace the extract with the higher index. 408 return Index0 > Index1 ? Ext0 : Ext1; 409 } 410 411 /// Compare the relative costs of 2 extracts followed by scalar operation vs. 412 /// vector operation(s) followed by extract. Return true if the existing 413 /// instructions are cheaper than a vector alternative. Otherwise, return false 414 /// and if one of the extracts should be transformed to a shufflevector, set 415 /// \p ConvertToShuffle to that extract instruction. 416 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0, 417 ExtractElementInst *Ext1, 418 const Instruction &I, 419 ExtractElementInst *&ConvertToShuffle, 420 unsigned PreferredExtractIndex) { 421 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getIndexOperand()); 422 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getIndexOperand()); 423 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes"); 424 425 unsigned Opcode = I.getOpcode(); 426 Value *Ext0Src = Ext0->getVectorOperand(); 427 Value *Ext1Src = Ext1->getVectorOperand(); 428 Type *ScalarTy = Ext0->getType(); 429 auto *VecTy = cast<VectorType>(Ext0Src->getType()); 430 InstructionCost ScalarOpCost, VectorOpCost; 431 432 // Get cost estimates for scalar and vector versions of the operation. 433 bool IsBinOp = Instruction::isBinaryOp(Opcode); 434 if (IsBinOp) { 435 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind); 436 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind); 437 } else { 438 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 439 "Expected a compare"); 440 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate(); 441 ScalarOpCost = TTI.getCmpSelInstrCost( 442 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind); 443 VectorOpCost = TTI.getCmpSelInstrCost( 444 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind); 445 } 446 447 // Get cost estimates for the extract elements. These costs will factor into 448 // both sequences. 449 unsigned Ext0Index = Ext0IndexC->getZExtValue(); 450 unsigned Ext1Index = Ext1IndexC->getZExtValue(); 451 452 InstructionCost Extract0Cost = 453 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index); 454 InstructionCost Extract1Cost = 455 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index); 456 457 // A more expensive extract will always be replaced by a splat shuffle. 458 // For example, if Ext0 is more expensive: 459 // opcode (extelt V0, Ext0), (ext V1, Ext1) --> 460 // extelt (opcode (splat V0, Ext0), V1), Ext1 461 // TODO: Evaluate whether that always results in lowest cost. Alternatively, 462 // check the cost of creating a broadcast shuffle and shuffling both 463 // operands to element 0. 464 unsigned BestExtIndex = Extract0Cost > Extract1Cost ? Ext0Index : Ext1Index; 465 unsigned BestInsIndex = Extract0Cost > Extract1Cost ? Ext1Index : Ext0Index; 466 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost); 467 468 // Extra uses of the extracts mean that we include those costs in the 469 // vector total because those instructions will not be eliminated. 470 InstructionCost OldCost, NewCost; 471 if (Ext0Src == Ext1Src && Ext0Index == Ext1Index) { 472 // Handle a special case. If the 2 extracts are identical, adjust the 473 // formulas to account for that. The extra use charge allows for either the 474 // CSE'd pattern or an unoptimized form with identical values: 475 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C 476 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2) 477 : !Ext0->hasOneUse() || !Ext1->hasOneUse(); 478 OldCost = CheapExtractCost + ScalarOpCost; 479 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost; 480 } else { 481 // Handle the general case. Each extract is actually a different value: 482 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C 483 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost; 484 NewCost = VectorOpCost + CheapExtractCost + 485 !Ext0->hasOneUse() * Extract0Cost + 486 !Ext1->hasOneUse() * Extract1Cost; 487 } 488 489 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex); 490 if (ConvertToShuffle) { 491 if (IsBinOp && DisableBinopExtractShuffle) 492 return true; 493 494 // If we are extracting from 2 different indexes, then one operand must be 495 // shuffled before performing the vector operation. The shuffle mask is 496 // poison except for 1 lane that is being translated to the remaining 497 // extraction lane. Therefore, it is a splat shuffle. Ex: 498 // ShufMask = { poison, poison, 0, poison } 499 // TODO: The cost model has an option for a "broadcast" shuffle 500 // (splat-from-element-0), but no option for a more general splat. 501 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(VecTy)) { 502 SmallVector<int> ShuffleMask(FixedVecTy->getNumElements(), 503 PoisonMaskElem); 504 ShuffleMask[BestInsIndex] = BestExtIndex; 505 NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 506 VecTy, ShuffleMask, CostKind, 0, nullptr, 507 {ConvertToShuffle}); 508 } else { 509 NewCost += 510 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy, 511 {}, CostKind, 0, nullptr, {ConvertToShuffle}); 512 } 513 } 514 515 // Aggressively form a vector op if the cost is equal because the transform 516 // may enable further optimization. 517 // Codegen can reverse this transform (scalarize) if it was not profitable. 518 return OldCost < NewCost; 519 } 520 521 /// Create a shuffle that translates (shifts) 1 element from the input vector 522 /// to a new element location. 523 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex, 524 unsigned NewIndex, IRBuilder<> &Builder) { 525 // The shuffle mask is poison except for 1 lane that is being translated 526 // to the new element index. Example for OldIndex == 2 and NewIndex == 0: 527 // ShufMask = { 2, poison, poison, poison } 528 auto *VecTy = cast<FixedVectorType>(Vec->getType()); 529 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem); 530 ShufMask[NewIndex] = OldIndex; 531 return Builder.CreateShuffleVector(Vec, ShufMask, "shift"); 532 } 533 534 /// Given an extract element instruction with constant index operand, shuffle 535 /// the source vector (shift the scalar element) to a NewIndex for extraction. 536 /// Return null if the input can be constant folded, so that we are not creating 537 /// unnecessary instructions. 538 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt, 539 unsigned NewIndex, 540 IRBuilder<> &Builder) { 541 // Shufflevectors can only be created for fixed-width vectors. 542 Value *X = ExtElt->getVectorOperand(); 543 if (!isa<FixedVectorType>(X->getType())) 544 return nullptr; 545 546 // If the extract can be constant-folded, this code is unsimplified. Defer 547 // to other passes to handle that. 548 Value *C = ExtElt->getIndexOperand(); 549 assert(isa<ConstantInt>(C) && "Expected a constant index operand"); 550 if (isa<Constant>(X)) 551 return nullptr; 552 553 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(), 554 NewIndex, Builder); 555 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex)); 556 } 557 558 /// Try to reduce extract element costs by converting scalar compares to vector 559 /// compares followed by extract. 560 /// cmp (ext0 V0, C), (ext1 V1, C) 561 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0, 562 ExtractElementInst *Ext1, Instruction &I) { 563 assert(isa<CmpInst>(&I) && "Expected a compare"); 564 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 565 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 566 "Expected matching constant extract indexes"); 567 568 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C 569 ++NumVecCmp; 570 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate(); 571 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 572 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1); 573 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand()); 574 replaceValue(I, *NewExt); 575 } 576 577 /// Try to reduce extract element costs by converting scalar binops to vector 578 /// binops followed by extract. 579 /// bo (ext0 V0, C), (ext1 V1, C) 580 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0, 581 ExtractElementInst *Ext1, Instruction &I) { 582 assert(isa<BinaryOperator>(&I) && "Expected a binary operator"); 583 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 584 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 585 "Expected matching constant extract indexes"); 586 587 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C 588 ++NumVecBO; 589 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 590 Value *VecBO = 591 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1); 592 593 // All IR flags are safe to back-propagate because any potential poison 594 // created in unused vector elements is discarded by the extract. 595 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO)) 596 VecBOInst->copyIRFlags(&I); 597 598 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand()); 599 replaceValue(I, *NewExt); 600 } 601 602 /// Match an instruction with extracted vector operands. 603 bool VectorCombine::foldExtractExtract(Instruction &I) { 604 // It is not safe to transform things like div, urem, etc. because we may 605 // create undefined behavior when executing those on unknown vector elements. 606 if (!isSafeToSpeculativelyExecute(&I)) 607 return false; 608 609 Instruction *I0, *I1; 610 CmpPredicate Pred = CmpInst::BAD_ICMP_PREDICATE; 611 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) && 612 !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1)))) 613 return false; 614 615 Value *V0, *V1; 616 uint64_t C0, C1; 617 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) || 618 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) || 619 V0->getType() != V1->getType()) 620 return false; 621 622 // If the scalar value 'I' is going to be re-inserted into a vector, then try 623 // to create an extract to that same element. The extract/insert can be 624 // reduced to a "select shuffle". 625 // TODO: If we add a larger pattern match that starts from an insert, this 626 // probably becomes unnecessary. 627 auto *Ext0 = cast<ExtractElementInst>(I0); 628 auto *Ext1 = cast<ExtractElementInst>(I1); 629 uint64_t InsertIndex = InvalidIndex; 630 if (I.hasOneUse()) 631 match(I.user_back(), 632 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex))); 633 634 ExtractElementInst *ExtractToChange; 635 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex)) 636 return false; 637 638 if (ExtractToChange) { 639 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0; 640 ExtractElementInst *NewExtract = 641 translateExtract(ExtractToChange, CheapExtractIdx, Builder); 642 if (!NewExtract) 643 return false; 644 if (ExtractToChange == Ext0) 645 Ext0 = NewExtract; 646 else 647 Ext1 = NewExtract; 648 } 649 650 if (Pred != CmpInst::BAD_ICMP_PREDICATE) 651 foldExtExtCmp(Ext0, Ext1, I); 652 else 653 foldExtExtBinop(Ext0, Ext1, I); 654 655 Worklist.push(Ext0); 656 Worklist.push(Ext1); 657 return true; 658 } 659 660 /// Try to replace an extract + scalar fneg + insert with a vector fneg + 661 /// shuffle. 662 bool VectorCombine::foldInsExtFNeg(Instruction &I) { 663 // Match an insert (op (extract)) pattern. 664 Value *DestVec; 665 uint64_t Index; 666 Instruction *FNeg; 667 if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)), 668 m_ConstantInt(Index)))) 669 return false; 670 671 // Note: This handles the canonical fneg instruction and "fsub -0.0, X". 672 Value *SrcVec; 673 Instruction *Extract; 674 if (!match(FNeg, m_FNeg(m_CombineAnd( 675 m_Instruction(Extract), 676 m_ExtractElt(m_Value(SrcVec), m_SpecificInt(Index)))))) 677 return false; 678 679 auto *VecTy = cast<FixedVectorType>(I.getType()); 680 auto *ScalarTy = VecTy->getScalarType(); 681 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType()); 682 if (!SrcVecTy || ScalarTy != SrcVecTy->getScalarType()) 683 return false; 684 685 // Ignore bogus insert/extract index. 686 unsigned NumElts = VecTy->getNumElements(); 687 if (Index >= NumElts) 688 return false; 689 690 // We are inserting the negated element into the same lane that we extracted 691 // from. This is equivalent to a select-shuffle that chooses all but the 692 // negated element from the destination vector. 693 SmallVector<int> Mask(NumElts); 694 std::iota(Mask.begin(), Mask.end(), 0); 695 Mask[Index] = Index + NumElts; 696 InstructionCost OldCost = 697 TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy, CostKind) + 698 TTI.getVectorInstrCost(I, VecTy, CostKind, Index); 699 700 // If the extract has one use, it will be eliminated, so count it in the 701 // original cost. If it has more than one use, ignore the cost because it will 702 // be the same before/after. 703 if (Extract->hasOneUse()) 704 OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index); 705 706 InstructionCost NewCost = 707 TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy, CostKind) + 708 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, VecTy, Mask, 709 CostKind); 710 711 bool NeedLenChg = SrcVecTy->getNumElements() != NumElts; 712 // If the lengths of the two vectors are not equal, 713 // we need to add a length-change vector. Add this cost. 714 SmallVector<int> SrcMask; 715 if (NeedLenChg) { 716 SrcMask.assign(NumElts, PoisonMaskElem); 717 SrcMask[Index] = Index; 718 NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 719 SrcVecTy, SrcMask, CostKind); 720 } 721 722 if (NewCost > OldCost) 723 return false; 724 725 Value *NewShuf; 726 // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index 727 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg); 728 if (NeedLenChg) { 729 // shuffle DestVec, (shuffle (fneg SrcVec), poison, SrcMask), Mask 730 Value *LenChgShuf = Builder.CreateShuffleVector(VecFNeg, SrcMask); 731 NewShuf = Builder.CreateShuffleVector(DestVec, LenChgShuf, Mask); 732 } else { 733 // shuffle DestVec, (fneg SrcVec), Mask 734 NewShuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask); 735 } 736 737 replaceValue(I, *NewShuf); 738 return true; 739 } 740 741 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the 742 /// destination type followed by shuffle. This can enable further transforms by 743 /// moving bitcasts or shuffles together. 744 bool VectorCombine::foldBitcastShuffle(Instruction &I) { 745 Value *V0, *V1; 746 ArrayRef<int> Mask; 747 if (!match(&I, m_BitCast(m_OneUse( 748 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask)))))) 749 return false; 750 751 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for 752 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle 753 // mask for scalable type is a splat or not. 754 // 2) Disallow non-vector casts. 755 // TODO: We could allow any shuffle. 756 auto *DestTy = dyn_cast<FixedVectorType>(I.getType()); 757 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType()); 758 if (!DestTy || !SrcTy) 759 return false; 760 761 unsigned DestEltSize = DestTy->getScalarSizeInBits(); 762 unsigned SrcEltSize = SrcTy->getScalarSizeInBits(); 763 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0) 764 return false; 765 766 bool IsUnary = isa<UndefValue>(V1); 767 768 // For binary shuffles, only fold bitcast(shuffle(X,Y)) 769 // if it won't increase the number of bitcasts. 770 if (!IsUnary) { 771 auto *BCTy0 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V0)->getType()); 772 auto *BCTy1 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V1)->getType()); 773 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) && 774 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType())) 775 return false; 776 } 777 778 SmallVector<int, 16> NewMask; 779 if (DestEltSize <= SrcEltSize) { 780 // The bitcast is from wide to narrow/equal elements. The shuffle mask can 781 // always be expanded to the equivalent form choosing narrower elements. 782 assert(SrcEltSize % DestEltSize == 0 && "Unexpected shuffle mask"); 783 unsigned ScaleFactor = SrcEltSize / DestEltSize; 784 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask); 785 } else { 786 // The bitcast is from narrow elements to wide elements. The shuffle mask 787 // must choose consecutive elements to allow casting first. 788 assert(DestEltSize % SrcEltSize == 0 && "Unexpected shuffle mask"); 789 unsigned ScaleFactor = DestEltSize / SrcEltSize; 790 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask)) 791 return false; 792 } 793 794 // Bitcast the shuffle src - keep its original width but using the destination 795 // scalar type. 796 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize; 797 auto *NewShuffleTy = 798 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts); 799 auto *OldShuffleTy = 800 FixedVectorType::get(SrcTy->getScalarType(), Mask.size()); 801 unsigned NumOps = IsUnary ? 1 : 2; 802 803 // The new shuffle must not cost more than the old shuffle. 804 TargetTransformInfo::ShuffleKind SK = 805 IsUnary ? TargetTransformInfo::SK_PermuteSingleSrc 806 : TargetTransformInfo::SK_PermuteTwoSrc; 807 808 InstructionCost NewCost = 809 TTI.getShuffleCost(SK, NewShuffleTy, NewMask, CostKind) + 810 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy, 811 TargetTransformInfo::CastContextHint::None, 812 CostKind)); 813 InstructionCost OldCost = 814 TTI.getShuffleCost(SK, SrcTy, Mask, CostKind) + 815 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy, 816 TargetTransformInfo::CastContextHint::None, 817 CostKind); 818 819 LLVM_DEBUG(dbgs() << "Found a bitcasted shuffle: " << I << "\n OldCost: " 820 << OldCost << " vs NewCost: " << NewCost << "\n"); 821 822 if (NewCost > OldCost || !NewCost.isValid()) 823 return false; 824 825 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC' 826 ++NumShufOfBitcast; 827 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy); 828 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy); 829 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask); 830 replaceValue(I, *Shuf); 831 return true; 832 } 833 834 /// VP Intrinsics whose vector operands are both splat values may be simplified 835 /// into the scalar version of the operation and the result splatted. This 836 /// can lead to scalarization down the line. 837 bool VectorCombine::scalarizeVPIntrinsic(Instruction &I) { 838 if (!isa<VPIntrinsic>(I)) 839 return false; 840 VPIntrinsic &VPI = cast<VPIntrinsic>(I); 841 Value *Op0 = VPI.getArgOperand(0); 842 Value *Op1 = VPI.getArgOperand(1); 843 844 if (!isSplatValue(Op0) || !isSplatValue(Op1)) 845 return false; 846 847 // Check getSplatValue early in this function, to avoid doing unnecessary 848 // work. 849 Value *ScalarOp0 = getSplatValue(Op0); 850 Value *ScalarOp1 = getSplatValue(Op1); 851 if (!ScalarOp0 || !ScalarOp1) 852 return false; 853 854 // For the binary VP intrinsics supported here, the result on disabled lanes 855 // is a poison value. For now, only do this simplification if all lanes 856 // are active. 857 // TODO: Relax the condition that all lanes are active by using insertelement 858 // on inactive lanes. 859 auto IsAllTrueMask = [](Value *MaskVal) { 860 if (Value *SplattedVal = getSplatValue(MaskVal)) 861 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal)) 862 return ConstValue->isAllOnesValue(); 863 return false; 864 }; 865 if (!IsAllTrueMask(VPI.getArgOperand(2))) 866 return false; 867 868 // Check to make sure we support scalarization of the intrinsic 869 Intrinsic::ID IntrID = VPI.getIntrinsicID(); 870 if (!VPBinOpIntrinsic::isVPBinOp(IntrID)) 871 return false; 872 873 // Calculate cost of splatting both operands into vectors and the vector 874 // intrinsic 875 VectorType *VecTy = cast<VectorType>(VPI.getType()); 876 SmallVector<int> Mask; 877 if (auto *FVTy = dyn_cast<FixedVectorType>(VecTy)) 878 Mask.resize(FVTy->getNumElements(), 0); 879 InstructionCost SplatCost = 880 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0) + 881 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, Mask, 882 CostKind); 883 884 // Calculate the cost of the VP Intrinsic 885 SmallVector<Type *, 4> Args; 886 for (Value *V : VPI.args()) 887 Args.push_back(V->getType()); 888 IntrinsicCostAttributes Attrs(IntrID, VecTy, Args); 889 InstructionCost VectorOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind); 890 InstructionCost OldCost = 2 * SplatCost + VectorOpCost; 891 892 // Determine scalar opcode 893 std::optional<unsigned> FunctionalOpcode = 894 VPI.getFunctionalOpcode(); 895 std::optional<Intrinsic::ID> ScalarIntrID = std::nullopt; 896 if (!FunctionalOpcode) { 897 ScalarIntrID = VPI.getFunctionalIntrinsicID(); 898 if (!ScalarIntrID) 899 return false; 900 } 901 902 // Calculate cost of scalarizing 903 InstructionCost ScalarOpCost = 0; 904 if (ScalarIntrID) { 905 IntrinsicCostAttributes Attrs(*ScalarIntrID, VecTy->getScalarType(), Args); 906 ScalarOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind); 907 } else { 908 ScalarOpCost = TTI.getArithmeticInstrCost(*FunctionalOpcode, 909 VecTy->getScalarType(), CostKind); 910 } 911 912 // The existing splats may be kept around if other instructions use them. 913 InstructionCost CostToKeepSplats = 914 (SplatCost * !Op0->hasOneUse()) + (SplatCost * !Op1->hasOneUse()); 915 InstructionCost NewCost = ScalarOpCost + SplatCost + CostToKeepSplats; 916 917 LLVM_DEBUG(dbgs() << "Found a VP Intrinsic to scalarize: " << VPI 918 << "\n"); 919 LLVM_DEBUG(dbgs() << "Cost of Intrinsic: " << OldCost 920 << ", Cost of scalarizing:" << NewCost << "\n"); 921 922 // We want to scalarize unless the vector variant actually has lower cost. 923 if (OldCost < NewCost || !NewCost.isValid()) 924 return false; 925 926 // Scalarize the intrinsic 927 ElementCount EC = cast<VectorType>(Op0->getType())->getElementCount(); 928 Value *EVL = VPI.getArgOperand(3); 929 930 // If the VP op might introduce UB or poison, we can scalarize it provided 931 // that we know the EVL > 0: If the EVL is zero, then the original VP op 932 // becomes a no-op and thus won't be UB, so make sure we don't introduce UB by 933 // scalarizing it. 934 bool SafeToSpeculate; 935 if (ScalarIntrID) 936 SafeToSpeculate = Intrinsic::getAttributes(I.getContext(), *ScalarIntrID) 937 .hasFnAttr(Attribute::AttrKind::Speculatable); 938 else 939 SafeToSpeculate = isSafeToSpeculativelyExecuteWithOpcode( 940 *FunctionalOpcode, &VPI, nullptr, &AC, &DT); 941 if (!SafeToSpeculate && 942 !isKnownNonZero(EVL, SimplifyQuery(*DL, &DT, &AC, &VPI))) 943 return false; 944 945 Value *ScalarVal = 946 ScalarIntrID 947 ? Builder.CreateIntrinsic(VecTy->getScalarType(), *ScalarIntrID, 948 {ScalarOp0, ScalarOp1}) 949 : Builder.CreateBinOp((Instruction::BinaryOps)(*FunctionalOpcode), 950 ScalarOp0, ScalarOp1); 951 952 replaceValue(VPI, *Builder.CreateVectorSplat(EC, ScalarVal)); 953 return true; 954 } 955 956 /// Match a vector binop or compare instruction with at least one inserted 957 /// scalar operand and convert to scalar binop/cmp followed by insertelement. 958 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) { 959 CmpPredicate Pred = CmpInst::BAD_ICMP_PREDICATE; 960 Value *Ins0, *Ins1; 961 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) && 962 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1)))) 963 return false; 964 965 // Do not convert the vector condition of a vector select into a scalar 966 // condition. That may cause problems for codegen because of differences in 967 // boolean formats and register-file transfers. 968 // TODO: Can we account for that in the cost model? 969 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE; 970 if (IsCmp) 971 for (User *U : I.users()) 972 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value()))) 973 return false; 974 975 // Match against one or both scalar values being inserted into constant 976 // vectors: 977 // vec_op VecC0, (inselt VecC1, V1, Index) 978 // vec_op (inselt VecC0, V0, Index), VecC1 979 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) 980 // TODO: Deal with mismatched index constants and variable indexes? 981 Constant *VecC0 = nullptr, *VecC1 = nullptr; 982 Value *V0 = nullptr, *V1 = nullptr; 983 uint64_t Index0 = 0, Index1 = 0; 984 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0), 985 m_ConstantInt(Index0))) && 986 !match(Ins0, m_Constant(VecC0))) 987 return false; 988 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1), 989 m_ConstantInt(Index1))) && 990 !match(Ins1, m_Constant(VecC1))) 991 return false; 992 993 bool IsConst0 = !V0; 994 bool IsConst1 = !V1; 995 if (IsConst0 && IsConst1) 996 return false; 997 if (!IsConst0 && !IsConst1 && Index0 != Index1) 998 return false; 999 1000 auto *VecTy0 = cast<VectorType>(Ins0->getType()); 1001 auto *VecTy1 = cast<VectorType>(Ins1->getType()); 1002 if (VecTy0->getElementCount().getKnownMinValue() <= Index0 || 1003 VecTy1->getElementCount().getKnownMinValue() <= Index1) 1004 return false; 1005 1006 // Bail for single insertion if it is a load. 1007 // TODO: Handle this once getVectorInstrCost can cost for load/stores. 1008 auto *I0 = dyn_cast_or_null<Instruction>(V0); 1009 auto *I1 = dyn_cast_or_null<Instruction>(V1); 1010 if ((IsConst0 && I1 && I1->mayReadFromMemory()) || 1011 (IsConst1 && I0 && I0->mayReadFromMemory())) 1012 return false; 1013 1014 uint64_t Index = IsConst0 ? Index1 : Index0; 1015 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType(); 1016 Type *VecTy = I.getType(); 1017 assert(VecTy->isVectorTy() && 1018 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) && 1019 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() || 1020 ScalarTy->isPointerTy()) && 1021 "Unexpected types for insert element into binop or cmp"); 1022 1023 unsigned Opcode = I.getOpcode(); 1024 InstructionCost ScalarOpCost, VectorOpCost; 1025 if (IsCmp) { 1026 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate(); 1027 ScalarOpCost = TTI.getCmpSelInstrCost( 1028 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind); 1029 VectorOpCost = TTI.getCmpSelInstrCost( 1030 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind); 1031 } else { 1032 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind); 1033 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind); 1034 } 1035 1036 // Get cost estimate for the insert element. This cost will factor into 1037 // both sequences. 1038 InstructionCost InsertCost = TTI.getVectorInstrCost( 1039 Instruction::InsertElement, VecTy, CostKind, Index); 1040 InstructionCost OldCost = 1041 (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost; 1042 InstructionCost NewCost = ScalarOpCost + InsertCost + 1043 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) + 1044 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost); 1045 1046 // We want to scalarize unless the vector variant actually has lower cost. 1047 if (OldCost < NewCost || !NewCost.isValid()) 1048 return false; 1049 1050 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) --> 1051 // inselt NewVecC, (scalar_op V0, V1), Index 1052 if (IsCmp) 1053 ++NumScalarCmp; 1054 else 1055 ++NumScalarBO; 1056 1057 // For constant cases, extract the scalar element, this should constant fold. 1058 if (IsConst0) 1059 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index)); 1060 if (IsConst1) 1061 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index)); 1062 1063 Value *Scalar = 1064 IsCmp ? Builder.CreateCmp(Pred, V0, V1) 1065 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1); 1066 1067 Scalar->setName(I.getName() + ".scalar"); 1068 1069 // All IR flags are safe to back-propagate. There is no potential for extra 1070 // poison to be created by the scalar instruction. 1071 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar)) 1072 ScalarInst->copyIRFlags(&I); 1073 1074 // Fold the vector constants in the original vectors into a new base vector. 1075 Value *NewVecC = 1076 IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1) 1077 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1); 1078 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index); 1079 replaceValue(I, *Insert); 1080 return true; 1081 } 1082 1083 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of 1084 /// a vector into vector operations followed by extract. Note: The SLP pass 1085 /// may miss this pattern because of implementation problems. 1086 bool VectorCombine::foldExtractedCmps(Instruction &I) { 1087 auto *BI = dyn_cast<BinaryOperator>(&I); 1088 1089 // We are looking for a scalar binop of booleans. 1090 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1) 1091 if (!BI || !I.getType()->isIntegerTy(1)) 1092 return false; 1093 1094 // The compare predicates should match, and each compare should have a 1095 // constant operand. 1096 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1); 1097 Instruction *I0, *I1; 1098 Constant *C0, *C1; 1099 CmpPredicate P0, P1; 1100 // FIXME: Use CmpPredicate::getMatching here. 1101 if (!match(B0, m_Cmp(P0, m_Instruction(I0), m_Constant(C0))) || 1102 !match(B1, m_Cmp(P1, m_Instruction(I1), m_Constant(C1))) || 1103 P0 != static_cast<CmpInst::Predicate>(P1)) 1104 return false; 1105 1106 // The compare operands must be extracts of the same vector with constant 1107 // extract indexes. 1108 Value *X; 1109 uint64_t Index0, Index1; 1110 if (!match(I0, m_ExtractElt(m_Value(X), m_ConstantInt(Index0))) || 1111 !match(I1, m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))) 1112 return false; 1113 1114 auto *Ext0 = cast<ExtractElementInst>(I0); 1115 auto *Ext1 = cast<ExtractElementInst>(I1); 1116 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1, CostKind); 1117 if (!ConvertToShuf) 1118 return false; 1119 assert((ConvertToShuf == Ext0 || ConvertToShuf == Ext1) && 1120 "Unknown ExtractElementInst"); 1121 1122 // The original scalar pattern is: 1123 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1) 1124 CmpInst::Predicate Pred = P0; 1125 unsigned CmpOpcode = 1126 CmpInst::isFPPredicate(Pred) ? Instruction::FCmp : Instruction::ICmp; 1127 auto *VecTy = dyn_cast<FixedVectorType>(X->getType()); 1128 if (!VecTy) 1129 return false; 1130 1131 InstructionCost Ext0Cost = 1132 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0); 1133 InstructionCost Ext1Cost = 1134 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1); 1135 InstructionCost CmpCost = TTI.getCmpSelInstrCost( 1136 CmpOpcode, I0->getType(), CmpInst::makeCmpResultType(I0->getType()), Pred, 1137 CostKind); 1138 1139 InstructionCost OldCost = 1140 Ext0Cost + Ext1Cost + CmpCost * 2 + 1141 TTI.getArithmeticInstrCost(I.getOpcode(), I.getType(), CostKind); 1142 1143 // The proposed vector pattern is: 1144 // vcmp = cmp Pred X, VecC 1145 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0 1146 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0; 1147 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1; 1148 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType())); 1149 InstructionCost NewCost = TTI.getCmpSelInstrCost( 1150 CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred, 1151 CostKind); 1152 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem); 1153 ShufMask[CheapIndex] = ExpensiveIndex; 1154 NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy, 1155 ShufMask, CostKind); 1156 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy, CostKind); 1157 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex); 1158 NewCost += Ext0->hasOneUse() ? 0 : Ext0Cost; 1159 NewCost += Ext1->hasOneUse() ? 0 : Ext1Cost; 1160 1161 // Aggressively form vector ops if the cost is equal because the transform 1162 // may enable further optimization. 1163 // Codegen can reverse this transform (scalarize) if it was not profitable. 1164 if (OldCost < NewCost || !NewCost.isValid()) 1165 return false; 1166 1167 // Create a vector constant from the 2 scalar constants. 1168 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(), 1169 PoisonValue::get(VecTy->getElementType())); 1170 CmpC[Index0] = C0; 1171 CmpC[Index1] = C1; 1172 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC)); 1173 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder); 1174 Value *LHS = ConvertToShuf == Ext0 ? Shuf : VCmp; 1175 Value *RHS = ConvertToShuf == Ext0 ? VCmp : Shuf; 1176 Value *VecLogic = Builder.CreateBinOp(BI->getOpcode(), LHS, RHS); 1177 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex); 1178 replaceValue(I, *NewExt); 1179 ++NumVecCmpBO; 1180 return true; 1181 } 1182 1183 // Check if memory loc modified between two instrs in the same BB 1184 static bool isMemModifiedBetween(BasicBlock::iterator Begin, 1185 BasicBlock::iterator End, 1186 const MemoryLocation &Loc, AAResults &AA) { 1187 unsigned NumScanned = 0; 1188 return std::any_of(Begin, End, [&](const Instruction &Instr) { 1189 return isModSet(AA.getModRefInfo(&Instr, Loc)) || 1190 ++NumScanned > MaxInstrsToScan; 1191 }); 1192 } 1193 1194 namespace { 1195 /// Helper class to indicate whether a vector index can be safely scalarized and 1196 /// if a freeze needs to be inserted. 1197 class ScalarizationResult { 1198 enum class StatusTy { Unsafe, Safe, SafeWithFreeze }; 1199 1200 StatusTy Status; 1201 Value *ToFreeze; 1202 1203 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr) 1204 : Status(Status), ToFreeze(ToFreeze) {} 1205 1206 public: 1207 ScalarizationResult(const ScalarizationResult &Other) = default; 1208 ~ScalarizationResult() { 1209 assert(!ToFreeze && "freeze() not called with ToFreeze being set"); 1210 } 1211 1212 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; } 1213 static ScalarizationResult safe() { return {StatusTy::Safe}; } 1214 static ScalarizationResult safeWithFreeze(Value *ToFreeze) { 1215 return {StatusTy::SafeWithFreeze, ToFreeze}; 1216 } 1217 1218 /// Returns true if the index can be scalarize without requiring a freeze. 1219 bool isSafe() const { return Status == StatusTy::Safe; } 1220 /// Returns true if the index cannot be scalarized. 1221 bool isUnsafe() const { return Status == StatusTy::Unsafe; } 1222 /// Returns true if the index can be scalarize, but requires inserting a 1223 /// freeze. 1224 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; } 1225 1226 /// Reset the state of Unsafe and clear ToFreze if set. 1227 void discard() { 1228 ToFreeze = nullptr; 1229 Status = StatusTy::Unsafe; 1230 } 1231 1232 /// Freeze the ToFreeze and update the use in \p User to use it. 1233 void freeze(IRBuilder<> &Builder, Instruction &UserI) { 1234 assert(isSafeWithFreeze() && 1235 "should only be used when freezing is required"); 1236 assert(is_contained(ToFreeze->users(), &UserI) && 1237 "UserI must be a user of ToFreeze"); 1238 IRBuilder<>::InsertPointGuard Guard(Builder); 1239 Builder.SetInsertPoint(cast<Instruction>(&UserI)); 1240 Value *Frozen = 1241 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen"); 1242 for (Use &U : make_early_inc_range((UserI.operands()))) 1243 if (U.get() == ToFreeze) 1244 U.set(Frozen); 1245 1246 ToFreeze = nullptr; 1247 } 1248 }; 1249 } // namespace 1250 1251 /// Check if it is legal to scalarize a memory access to \p VecTy at index \p 1252 /// Idx. \p Idx must access a valid vector element. 1253 static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, 1254 Instruction *CtxI, 1255 AssumptionCache &AC, 1256 const DominatorTree &DT) { 1257 // We do checks for both fixed vector types and scalable vector types. 1258 // This is the number of elements of fixed vector types, 1259 // or the minimum number of elements of scalable vector types. 1260 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue(); 1261 1262 if (auto *C = dyn_cast<ConstantInt>(Idx)) { 1263 if (C->getValue().ult(NumElements)) 1264 return ScalarizationResult::safe(); 1265 return ScalarizationResult::unsafe(); 1266 } 1267 1268 unsigned IntWidth = Idx->getType()->getScalarSizeInBits(); 1269 APInt Zero(IntWidth, 0); 1270 APInt MaxElts(IntWidth, NumElements); 1271 ConstantRange ValidIndices(Zero, MaxElts); 1272 ConstantRange IdxRange(IntWidth, true); 1273 1274 if (isGuaranteedNotToBePoison(Idx, &AC)) { 1275 if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false, 1276 true, &AC, CtxI, &DT))) 1277 return ScalarizationResult::safe(); 1278 return ScalarizationResult::unsafe(); 1279 } 1280 1281 // If the index may be poison, check if we can insert a freeze before the 1282 // range of the index is restricted. 1283 Value *IdxBase; 1284 ConstantInt *CI; 1285 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) { 1286 IdxRange = IdxRange.binaryAnd(CI->getValue()); 1287 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) { 1288 IdxRange = IdxRange.urem(CI->getValue()); 1289 } 1290 1291 if (ValidIndices.contains(IdxRange)) 1292 return ScalarizationResult::safeWithFreeze(IdxBase); 1293 return ScalarizationResult::unsafe(); 1294 } 1295 1296 /// The memory operation on a vector of \p ScalarType had alignment of 1297 /// \p VectorAlignment. Compute the maximal, but conservatively correct, 1298 /// alignment that will be valid for the memory operation on a single scalar 1299 /// element of the same type with index \p Idx. 1300 static Align computeAlignmentAfterScalarization(Align VectorAlignment, 1301 Type *ScalarType, Value *Idx, 1302 const DataLayout &DL) { 1303 if (auto *C = dyn_cast<ConstantInt>(Idx)) 1304 return commonAlignment(VectorAlignment, 1305 C->getZExtValue() * DL.getTypeStoreSize(ScalarType)); 1306 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType)); 1307 } 1308 1309 // Combine patterns like: 1310 // %0 = load <4 x i32>, <4 x i32>* %a 1311 // %1 = insertelement <4 x i32> %0, i32 %b, i32 1 1312 // store <4 x i32> %1, <4 x i32>* %a 1313 // to: 1314 // %0 = bitcast <4 x i32>* %a to i32* 1315 // %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1 1316 // store i32 %b, i32* %1 1317 bool VectorCombine::foldSingleElementStore(Instruction &I) { 1318 auto *SI = cast<StoreInst>(&I); 1319 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType())) 1320 return false; 1321 1322 // TODO: Combine more complicated patterns (multiple insert) by referencing 1323 // TargetTransformInfo. 1324 Instruction *Source; 1325 Value *NewElement; 1326 Value *Idx; 1327 if (!match(SI->getValueOperand(), 1328 m_InsertElt(m_Instruction(Source), m_Value(NewElement), 1329 m_Value(Idx)))) 1330 return false; 1331 1332 if (auto *Load = dyn_cast<LoadInst>(Source)) { 1333 auto VecTy = cast<VectorType>(SI->getValueOperand()->getType()); 1334 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts(); 1335 // Don't optimize for atomic/volatile load or store. Ensure memory is not 1336 // modified between, vector type matches store size, and index is inbounds. 1337 if (!Load->isSimple() || Load->getParent() != SI->getParent() || 1338 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) || 1339 SrcAddr != SI->getPointerOperand()->stripPointerCasts()) 1340 return false; 1341 1342 auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT); 1343 if (ScalarizableIdx.isUnsafe() || 1344 isMemModifiedBetween(Load->getIterator(), SI->getIterator(), 1345 MemoryLocation::get(SI), AA)) 1346 return false; 1347 1348 // Ensure we add the load back to the worklist BEFORE its users so they can 1349 // erased in the correct order. 1350 Worklist.push(Load); 1351 1352 if (ScalarizableIdx.isSafeWithFreeze()) 1353 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx)); 1354 Value *GEP = Builder.CreateInBoundsGEP( 1355 SI->getValueOperand()->getType(), SI->getPointerOperand(), 1356 {ConstantInt::get(Idx->getType(), 0), Idx}); 1357 StoreInst *NSI = Builder.CreateStore(NewElement, GEP); 1358 NSI->copyMetadata(*SI); 1359 Align ScalarOpAlignment = computeAlignmentAfterScalarization( 1360 std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx, 1361 *DL); 1362 NSI->setAlignment(ScalarOpAlignment); 1363 replaceValue(I, *NSI); 1364 eraseInstruction(I); 1365 return true; 1366 } 1367 1368 return false; 1369 } 1370 1371 /// Try to scalarize vector loads feeding extractelement instructions. 1372 bool VectorCombine::scalarizeLoadExtract(Instruction &I) { 1373 Value *Ptr; 1374 if (!match(&I, m_Load(m_Value(Ptr)))) 1375 return false; 1376 1377 auto *LI = cast<LoadInst>(&I); 1378 auto *VecTy = cast<VectorType>(LI->getType()); 1379 if (LI->isVolatile() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType())) 1380 return false; 1381 1382 InstructionCost OriginalCost = 1383 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(), 1384 LI->getPointerAddressSpace(), CostKind); 1385 InstructionCost ScalarizedCost = 0; 1386 1387 Instruction *LastCheckedInst = LI; 1388 unsigned NumInstChecked = 0; 1389 DenseMap<ExtractElementInst *, ScalarizationResult> NeedFreeze; 1390 auto FailureGuard = make_scope_exit([&]() { 1391 // If the transform is aborted, discard the ScalarizationResults. 1392 for (auto &Pair : NeedFreeze) 1393 Pair.second.discard(); 1394 }); 1395 1396 // Check if all users of the load are extracts with no memory modifications 1397 // between the load and the extract. Compute the cost of both the original 1398 // code and the scalarized version. 1399 for (User *U : LI->users()) { 1400 auto *UI = dyn_cast<ExtractElementInst>(U); 1401 if (!UI || UI->getParent() != LI->getParent()) 1402 return false; 1403 1404 // Check if any instruction between the load and the extract may modify 1405 // memory. 1406 if (LastCheckedInst->comesBefore(UI)) { 1407 for (Instruction &I : 1408 make_range(std::next(LI->getIterator()), UI->getIterator())) { 1409 // Bail out if we reached the check limit or the instruction may write 1410 // to memory. 1411 if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory()) 1412 return false; 1413 NumInstChecked++; 1414 } 1415 LastCheckedInst = UI; 1416 } 1417 1418 auto ScalarIdx = 1419 canScalarizeAccess(VecTy, UI->getIndexOperand(), LI, AC, DT); 1420 if (ScalarIdx.isUnsafe()) 1421 return false; 1422 if (ScalarIdx.isSafeWithFreeze()) { 1423 NeedFreeze.try_emplace(UI, ScalarIdx); 1424 ScalarIdx.discard(); 1425 } 1426 1427 auto *Index = dyn_cast<ConstantInt>(UI->getIndexOperand()); 1428 OriginalCost += 1429 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind, 1430 Index ? Index->getZExtValue() : -1); 1431 ScalarizedCost += 1432 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(), 1433 Align(1), LI->getPointerAddressSpace(), CostKind); 1434 ScalarizedCost += TTI.getAddressComputationCost(VecTy->getElementType()); 1435 } 1436 1437 if (ScalarizedCost >= OriginalCost) 1438 return false; 1439 1440 // Ensure we add the load back to the worklist BEFORE its users so they can 1441 // erased in the correct order. 1442 Worklist.push(LI); 1443 1444 // Replace extracts with narrow scalar loads. 1445 for (User *U : LI->users()) { 1446 auto *EI = cast<ExtractElementInst>(U); 1447 Value *Idx = EI->getIndexOperand(); 1448 1449 // Insert 'freeze' for poison indexes. 1450 auto It = NeedFreeze.find(EI); 1451 if (It != NeedFreeze.end()) 1452 It->second.freeze(Builder, *cast<Instruction>(Idx)); 1453 1454 Builder.SetInsertPoint(EI); 1455 Value *GEP = 1456 Builder.CreateInBoundsGEP(VecTy, Ptr, {Builder.getInt32(0), Idx}); 1457 auto *NewLoad = cast<LoadInst>(Builder.CreateLoad( 1458 VecTy->getElementType(), GEP, EI->getName() + ".scalar")); 1459 1460 Align ScalarOpAlignment = computeAlignmentAfterScalarization( 1461 LI->getAlign(), VecTy->getElementType(), Idx, *DL); 1462 NewLoad->setAlignment(ScalarOpAlignment); 1463 1464 replaceValue(*EI, *NewLoad); 1465 } 1466 1467 FailureGuard.release(); 1468 return true; 1469 } 1470 1471 /// Try to fold "(or (zext (bitcast X)), (shl (zext (bitcast Y)), C))" 1472 /// to "(bitcast (concat X, Y))" 1473 /// where X/Y are bitcasted from i1 mask vectors. 1474 bool VectorCombine::foldConcatOfBoolMasks(Instruction &I) { 1475 Type *Ty = I.getType(); 1476 if (!Ty->isIntegerTy()) 1477 return false; 1478 1479 // TODO: Add big endian test coverage 1480 if (DL->isBigEndian()) 1481 return false; 1482 1483 // Restrict to disjoint cases so the mask vectors aren't overlapping. 1484 Instruction *X, *Y; 1485 if (!match(&I, m_DisjointOr(m_Instruction(X), m_Instruction(Y)))) 1486 return false; 1487 1488 // Allow both sources to contain shl, to handle more generic pattern: 1489 // "(or (shl (zext (bitcast X)), C1), (shl (zext (bitcast Y)), C2))" 1490 Value *SrcX; 1491 uint64_t ShAmtX = 0; 1492 if (!match(X, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcX)))))) && 1493 !match(X, m_OneUse( 1494 m_Shl(m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcX))))), 1495 m_ConstantInt(ShAmtX))))) 1496 return false; 1497 1498 Value *SrcY; 1499 uint64_t ShAmtY = 0; 1500 if (!match(Y, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcY)))))) && 1501 !match(Y, m_OneUse( 1502 m_Shl(m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcY))))), 1503 m_ConstantInt(ShAmtY))))) 1504 return false; 1505 1506 // Canonicalize larger shift to the RHS. 1507 if (ShAmtX > ShAmtY) { 1508 std::swap(X, Y); 1509 std::swap(SrcX, SrcY); 1510 std::swap(ShAmtX, ShAmtY); 1511 } 1512 1513 // Ensure both sources are matching vXi1 bool mask types, and that the shift 1514 // difference is the mask width so they can be easily concatenated together. 1515 uint64_t ShAmtDiff = ShAmtY - ShAmtX; 1516 unsigned NumSHL = (ShAmtX > 0) + (ShAmtY > 0); 1517 unsigned BitWidth = Ty->getPrimitiveSizeInBits(); 1518 auto *MaskTy = dyn_cast<FixedVectorType>(SrcX->getType()); 1519 if (!MaskTy || SrcX->getType() != SrcY->getType() || 1520 !MaskTy->getElementType()->isIntegerTy(1) || 1521 MaskTy->getNumElements() != ShAmtDiff || 1522 MaskTy->getNumElements() > (BitWidth / 2)) 1523 return false; 1524 1525 auto *ConcatTy = FixedVectorType::getDoubleElementsVectorType(MaskTy); 1526 auto *ConcatIntTy = 1527 Type::getIntNTy(Ty->getContext(), ConcatTy->getNumElements()); 1528 auto *MaskIntTy = Type::getIntNTy(Ty->getContext(), ShAmtDiff); 1529 1530 SmallVector<int, 32> ConcatMask(ConcatTy->getNumElements()); 1531 std::iota(ConcatMask.begin(), ConcatMask.end(), 0); 1532 1533 // TODO: Is it worth supporting multi use cases? 1534 InstructionCost OldCost = 0; 1535 OldCost += TTI.getArithmeticInstrCost(Instruction::Or, Ty, CostKind); 1536 OldCost += 1537 NumSHL * TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind); 1538 OldCost += 2 * TTI.getCastInstrCost(Instruction::ZExt, Ty, MaskIntTy, 1539 TTI::CastContextHint::None, CostKind); 1540 OldCost += 2 * TTI.getCastInstrCost(Instruction::BitCast, MaskIntTy, MaskTy, 1541 TTI::CastContextHint::None, CostKind); 1542 1543 InstructionCost NewCost = 0; 1544 NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, MaskTy, 1545 ConcatMask, CostKind); 1546 NewCost += TTI.getCastInstrCost(Instruction::BitCast, ConcatIntTy, ConcatTy, 1547 TTI::CastContextHint::None, CostKind); 1548 if (Ty != ConcatIntTy) 1549 NewCost += TTI.getCastInstrCost(Instruction::ZExt, Ty, ConcatIntTy, 1550 TTI::CastContextHint::None, CostKind); 1551 if (ShAmtX > 0) 1552 NewCost += TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind); 1553 1554 LLVM_DEBUG(dbgs() << "Found a concatenation of bitcasted bool masks: " << I 1555 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 1556 << "\n"); 1557 1558 if (NewCost > OldCost) 1559 return false; 1560 1561 // Build bool mask concatenation, bitcast back to scalar integer, and perform 1562 // any residual zero-extension or shifting. 1563 Value *Concat = Builder.CreateShuffleVector(SrcX, SrcY, ConcatMask); 1564 Worklist.pushValue(Concat); 1565 1566 Value *Result = Builder.CreateBitCast(Concat, ConcatIntTy); 1567 1568 if (Ty != ConcatIntTy) { 1569 Worklist.pushValue(Result); 1570 Result = Builder.CreateZExt(Result, Ty); 1571 } 1572 1573 if (ShAmtX > 0) { 1574 Worklist.pushValue(Result); 1575 Result = Builder.CreateShl(Result, ShAmtX); 1576 } 1577 1578 replaceValue(I, *Result); 1579 return true; 1580 } 1581 1582 /// Try to convert "shuffle (binop (shuffle, shuffle)), undef" 1583 /// --> "binop (shuffle), (shuffle)". 1584 bool VectorCombine::foldPermuteOfBinops(Instruction &I) { 1585 BinaryOperator *BinOp; 1586 ArrayRef<int> OuterMask; 1587 if (!match(&I, 1588 m_Shuffle(m_OneUse(m_BinOp(BinOp)), m_Undef(), m_Mask(OuterMask)))) 1589 return false; 1590 1591 // Don't introduce poison into div/rem. 1592 if (BinOp->isIntDivRem() && llvm::is_contained(OuterMask, PoisonMaskElem)) 1593 return false; 1594 1595 Value *Op00, *Op01; 1596 ArrayRef<int> Mask0; 1597 if (!match(BinOp->getOperand(0), 1598 m_OneUse(m_Shuffle(m_Value(Op00), m_Value(Op01), m_Mask(Mask0))))) 1599 return false; 1600 1601 Value *Op10, *Op11; 1602 ArrayRef<int> Mask1; 1603 if (!match(BinOp->getOperand(1), 1604 m_OneUse(m_Shuffle(m_Value(Op10), m_Value(Op11), m_Mask(Mask1))))) 1605 return false; 1606 1607 Instruction::BinaryOps Opcode = BinOp->getOpcode(); 1608 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType()); 1609 auto *BinOpTy = dyn_cast<FixedVectorType>(BinOp->getType()); 1610 auto *Op0Ty = dyn_cast<FixedVectorType>(Op00->getType()); 1611 auto *Op1Ty = dyn_cast<FixedVectorType>(Op10->getType()); 1612 if (!ShuffleDstTy || !BinOpTy || !Op0Ty || !Op1Ty) 1613 return false; 1614 1615 unsigned NumSrcElts = BinOpTy->getNumElements(); 1616 1617 // Don't accept shuffles that reference the second operand in 1618 // div/rem or if its an undef arg. 1619 if ((BinOp->isIntDivRem() || !isa<PoisonValue>(I.getOperand(1))) && 1620 any_of(OuterMask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; })) 1621 return false; 1622 1623 // Merge outer / inner shuffles. 1624 SmallVector<int> NewMask0, NewMask1; 1625 for (int M : OuterMask) { 1626 if (M < 0 || M >= (int)NumSrcElts) { 1627 NewMask0.push_back(PoisonMaskElem); 1628 NewMask1.push_back(PoisonMaskElem); 1629 } else { 1630 NewMask0.push_back(Mask0[M]); 1631 NewMask1.push_back(Mask1[M]); 1632 } 1633 } 1634 1635 // Try to merge shuffles across the binop if the new shuffles are not costly. 1636 InstructionCost OldCost = 1637 TTI.getArithmeticInstrCost(Opcode, BinOpTy, CostKind) + 1638 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, BinOpTy, 1639 OuterMask, CostKind, 0, nullptr, {BinOp}, &I) + 1640 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, Op0Ty, Mask0, 1641 CostKind, 0, nullptr, {Op00, Op01}, 1642 cast<Instruction>(BinOp->getOperand(0))) + 1643 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, Op1Ty, Mask1, 1644 CostKind, 0, nullptr, {Op10, Op11}, 1645 cast<Instruction>(BinOp->getOperand(1))); 1646 1647 InstructionCost NewCost = 1648 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, Op0Ty, NewMask0, 1649 CostKind, 0, nullptr, {Op00, Op01}) + 1650 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, Op1Ty, NewMask1, 1651 CostKind, 0, nullptr, {Op10, Op11}) + 1652 TTI.getArithmeticInstrCost(Opcode, ShuffleDstTy, CostKind); 1653 1654 LLVM_DEBUG(dbgs() << "Found a shuffle feeding a shuffled binop: " << I 1655 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 1656 << "\n"); 1657 1658 // If costs are equal, still fold as we reduce instruction count. 1659 if (NewCost > OldCost) 1660 return false; 1661 1662 Value *Shuf0 = Builder.CreateShuffleVector(Op00, Op01, NewMask0); 1663 Value *Shuf1 = Builder.CreateShuffleVector(Op10, Op11, NewMask1); 1664 Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1); 1665 1666 // Intersect flags from the old binops. 1667 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) 1668 NewInst->copyIRFlags(BinOp); 1669 1670 Worklist.pushValue(Shuf0); 1671 Worklist.pushValue(Shuf1); 1672 replaceValue(I, *NewBO); 1673 return true; 1674 } 1675 1676 /// Try to convert "shuffle (binop), (binop)" into "binop (shuffle), (shuffle)". 1677 /// Try to convert "shuffle (cmpop), (cmpop)" into "cmpop (shuffle), (shuffle)". 1678 bool VectorCombine::foldShuffleOfBinops(Instruction &I) { 1679 ArrayRef<int> OldMask; 1680 Instruction *LHS, *RHS; 1681 if (!match(&I, m_Shuffle(m_OneUse(m_Instruction(LHS)), 1682 m_OneUse(m_Instruction(RHS)), m_Mask(OldMask)))) 1683 return false; 1684 1685 // TODO: Add support for addlike etc. 1686 if (LHS->getOpcode() != RHS->getOpcode()) 1687 return false; 1688 1689 Value *X, *Y, *Z, *W; 1690 bool IsCommutative = false; 1691 CmpPredicate PredLHS = CmpInst::BAD_ICMP_PREDICATE; 1692 CmpPredicate PredRHS = CmpInst::BAD_ICMP_PREDICATE; 1693 if (match(LHS, m_BinOp(m_Value(X), m_Value(Y))) && 1694 match(RHS, m_BinOp(m_Value(Z), m_Value(W)))) { 1695 auto *BO = cast<BinaryOperator>(LHS); 1696 // Don't introduce poison into div/rem. 1697 if (llvm::is_contained(OldMask, PoisonMaskElem) && BO->isIntDivRem()) 1698 return false; 1699 IsCommutative = BinaryOperator::isCommutative(BO->getOpcode()); 1700 } else if (match(LHS, m_Cmp(PredLHS, m_Value(X), m_Value(Y))) && 1701 match(RHS, m_Cmp(PredRHS, m_Value(Z), m_Value(W))) && 1702 (CmpInst::Predicate)PredLHS == (CmpInst::Predicate)PredRHS) { 1703 IsCommutative = cast<CmpInst>(LHS)->isCommutative(); 1704 } else 1705 return false; 1706 1707 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType()); 1708 auto *BinResTy = dyn_cast<FixedVectorType>(LHS->getType()); 1709 auto *BinOpTy = dyn_cast<FixedVectorType>(X->getType()); 1710 if (!ShuffleDstTy || !BinResTy || !BinOpTy || X->getType() != Z->getType()) 1711 return false; 1712 1713 unsigned NumSrcElts = BinOpTy->getNumElements(); 1714 1715 // If we have something like "add X, Y" and "add Z, X", swap ops to match. 1716 if (IsCommutative && X != Z && Y != W && (X == W || Y == Z)) 1717 std::swap(X, Y); 1718 1719 auto ConvertToUnary = [NumSrcElts](int &M) { 1720 if (M >= (int)NumSrcElts) 1721 M -= NumSrcElts; 1722 }; 1723 1724 SmallVector<int> NewMask0(OldMask); 1725 TargetTransformInfo::ShuffleKind SK0 = TargetTransformInfo::SK_PermuteTwoSrc; 1726 if (X == Z) { 1727 llvm::for_each(NewMask0, ConvertToUnary); 1728 SK0 = TargetTransformInfo::SK_PermuteSingleSrc; 1729 Z = PoisonValue::get(BinOpTy); 1730 } 1731 1732 SmallVector<int> NewMask1(OldMask); 1733 TargetTransformInfo::ShuffleKind SK1 = TargetTransformInfo::SK_PermuteTwoSrc; 1734 if (Y == W) { 1735 llvm::for_each(NewMask1, ConvertToUnary); 1736 SK1 = TargetTransformInfo::SK_PermuteSingleSrc; 1737 W = PoisonValue::get(BinOpTy); 1738 } 1739 1740 // Try to replace a binop with a shuffle if the shuffle is not costly. 1741 InstructionCost OldCost = 1742 TTI.getInstructionCost(LHS, CostKind) + 1743 TTI.getInstructionCost(RHS, CostKind) + 1744 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, BinResTy, 1745 OldMask, CostKind, 0, nullptr, {LHS, RHS}, &I); 1746 1747 // Handle shuffle(binop(shuffle(x),y),binop(z,shuffle(w))) style patterns 1748 // where one use shuffles have gotten split across the binop/cmp. These 1749 // often allow a major reduction in total cost that wouldn't happen as 1750 // individual folds. 1751 auto MergeInner = [&](Value *&Op, int Offset, MutableArrayRef<int> Mask, 1752 TTI::TargetCostKind CostKind) -> bool { 1753 Value *InnerOp; 1754 ArrayRef<int> InnerMask; 1755 if (match(Op, m_OneUse(m_Shuffle(m_Value(InnerOp), m_Undef(), 1756 m_Mask(InnerMask)))) && 1757 InnerOp->getType() == Op->getType() && 1758 all_of(InnerMask, 1759 [NumSrcElts](int M) { return M < (int)NumSrcElts; })) { 1760 for (int &M : Mask) 1761 if (Offset <= M && M < (int)(Offset + NumSrcElts)) { 1762 M = InnerMask[M - Offset]; 1763 M = 0 <= M ? M + Offset : M; 1764 } 1765 OldCost += TTI.getInstructionCost(cast<Instruction>(Op), CostKind); 1766 Op = InnerOp; 1767 return true; 1768 } 1769 return false; 1770 }; 1771 bool ReducedInstCount = false; 1772 ReducedInstCount |= MergeInner(X, 0, NewMask0, CostKind); 1773 ReducedInstCount |= MergeInner(Y, 0, NewMask1, CostKind); 1774 ReducedInstCount |= MergeInner(Z, NumSrcElts, NewMask0, CostKind); 1775 ReducedInstCount |= MergeInner(W, NumSrcElts, NewMask1, CostKind); 1776 1777 InstructionCost NewCost = 1778 TTI.getShuffleCost(SK0, BinOpTy, NewMask0, CostKind, 0, nullptr, {X, Z}) + 1779 TTI.getShuffleCost(SK1, BinOpTy, NewMask1, CostKind, 0, nullptr, {Y, W}); 1780 1781 if (PredLHS == CmpInst::BAD_ICMP_PREDICATE) { 1782 NewCost += 1783 TTI.getArithmeticInstrCost(LHS->getOpcode(), ShuffleDstTy, CostKind); 1784 } else { 1785 auto *ShuffleCmpTy = 1786 FixedVectorType::get(BinOpTy->getElementType(), ShuffleDstTy); 1787 NewCost += TTI.getCmpSelInstrCost(LHS->getOpcode(), ShuffleCmpTy, 1788 ShuffleDstTy, PredLHS, CostKind); 1789 } 1790 1791 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two binops: " << I 1792 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 1793 << "\n"); 1794 1795 // If either shuffle will constant fold away, then fold for the same cost as 1796 // we will reduce the instruction count. 1797 ReducedInstCount |= (isa<Constant>(X) && isa<Constant>(Z)) || 1798 (isa<Constant>(Y) && isa<Constant>(W)); 1799 if (ReducedInstCount ? (NewCost > OldCost) : (NewCost >= OldCost)) 1800 return false; 1801 1802 Value *Shuf0 = Builder.CreateShuffleVector(X, Z, NewMask0); 1803 Value *Shuf1 = Builder.CreateShuffleVector(Y, W, NewMask1); 1804 Value *NewBO = PredLHS == CmpInst::BAD_ICMP_PREDICATE 1805 ? Builder.CreateBinOp( 1806 cast<BinaryOperator>(LHS)->getOpcode(), Shuf0, Shuf1) 1807 : Builder.CreateCmp(PredLHS, Shuf0, Shuf1); 1808 1809 // Intersect flags from the old binops. 1810 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) { 1811 NewInst->copyIRFlags(LHS); 1812 NewInst->andIRFlags(RHS); 1813 } 1814 1815 Worklist.pushValue(Shuf0); 1816 Worklist.pushValue(Shuf1); 1817 replaceValue(I, *NewBO); 1818 return true; 1819 } 1820 1821 /// Try to convert "shuffle (castop), (castop)" with a shared castop operand 1822 /// into "castop (shuffle)". 1823 bool VectorCombine::foldShuffleOfCastops(Instruction &I) { 1824 Value *V0, *V1; 1825 ArrayRef<int> OldMask; 1826 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask)))) 1827 return false; 1828 1829 auto *C0 = dyn_cast<CastInst>(V0); 1830 auto *C1 = dyn_cast<CastInst>(V1); 1831 if (!C0 || !C1) 1832 return false; 1833 1834 Instruction::CastOps Opcode = C0->getOpcode(); 1835 if (C0->getSrcTy() != C1->getSrcTy()) 1836 return false; 1837 1838 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds. 1839 if (Opcode != C1->getOpcode()) { 1840 if (match(C0, m_SExtLike(m_Value())) && match(C1, m_SExtLike(m_Value()))) 1841 Opcode = Instruction::SExt; 1842 else 1843 return false; 1844 } 1845 1846 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType()); 1847 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy()); 1848 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy()); 1849 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy) 1850 return false; 1851 1852 unsigned NumSrcElts = CastSrcTy->getNumElements(); 1853 unsigned NumDstElts = CastDstTy->getNumElements(); 1854 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) && 1855 "Only bitcasts expected to alter src/dst element counts"); 1856 1857 // Check for bitcasting of unscalable vector types. 1858 // e.g. <32 x i40> -> <40 x i32> 1859 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 && 1860 (NumDstElts % NumSrcElts) != 0) 1861 return false; 1862 1863 SmallVector<int, 16> NewMask; 1864 if (NumSrcElts >= NumDstElts) { 1865 // The bitcast is from wide to narrow/equal elements. The shuffle mask can 1866 // always be expanded to the equivalent form choosing narrower elements. 1867 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask"); 1868 unsigned ScaleFactor = NumSrcElts / NumDstElts; 1869 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask); 1870 } else { 1871 // The bitcast is from narrow elements to wide elements. The shuffle mask 1872 // must choose consecutive elements to allow casting first. 1873 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask"); 1874 unsigned ScaleFactor = NumDstElts / NumSrcElts; 1875 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask)) 1876 return false; 1877 } 1878 1879 auto *NewShuffleDstTy = 1880 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size()); 1881 1882 // Try to replace a castop with a shuffle if the shuffle is not costly. 1883 InstructionCost CostC0 = 1884 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy, 1885 TTI::CastContextHint::None, CostKind); 1886 InstructionCost CostC1 = 1887 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy, 1888 TTI::CastContextHint::None, CostKind); 1889 InstructionCost OldCost = CostC0 + CostC1; 1890 OldCost += 1891 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, CastDstTy, 1892 OldMask, CostKind, 0, nullptr, {}, &I); 1893 1894 InstructionCost NewCost = TTI.getShuffleCost( 1895 TargetTransformInfo::SK_PermuteTwoSrc, CastSrcTy, NewMask, CostKind); 1896 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy, 1897 TTI::CastContextHint::None, CostKind); 1898 if (!C0->hasOneUse()) 1899 NewCost += CostC0; 1900 if (!C1->hasOneUse()) 1901 NewCost += CostC1; 1902 1903 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I 1904 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 1905 << "\n"); 1906 if (NewCost > OldCost) 1907 return false; 1908 1909 Value *Shuf = Builder.CreateShuffleVector(C0->getOperand(0), 1910 C1->getOperand(0), NewMask); 1911 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy); 1912 1913 // Intersect flags from the old casts. 1914 if (auto *NewInst = dyn_cast<Instruction>(Cast)) { 1915 NewInst->copyIRFlags(C0); 1916 NewInst->andIRFlags(C1); 1917 } 1918 1919 Worklist.pushValue(Shuf); 1920 replaceValue(I, *Cast); 1921 return true; 1922 } 1923 1924 /// Try to convert any of: 1925 /// "shuffle (shuffle x, y), (shuffle y, x)" 1926 /// "shuffle (shuffle x, undef), (shuffle y, undef)" 1927 /// "shuffle (shuffle x, undef), y" 1928 /// "shuffle x, (shuffle y, undef)" 1929 /// into "shuffle x, y". 1930 bool VectorCombine::foldShuffleOfShuffles(Instruction &I) { 1931 ArrayRef<int> OuterMask; 1932 Value *OuterV0, *OuterV1; 1933 if (!match(&I, 1934 m_Shuffle(m_Value(OuterV0), m_Value(OuterV1), m_Mask(OuterMask)))) 1935 return false; 1936 1937 ArrayRef<int> InnerMask0, InnerMask1; 1938 Value *X0, *X1, *Y0, *Y1; 1939 bool Match0 = 1940 match(OuterV0, m_Shuffle(m_Value(X0), m_Value(Y0), m_Mask(InnerMask0))); 1941 bool Match1 = 1942 match(OuterV1, m_Shuffle(m_Value(X1), m_Value(Y1), m_Mask(InnerMask1))); 1943 if (!Match0 && !Match1) 1944 return false; 1945 1946 X0 = Match0 ? X0 : OuterV0; 1947 Y0 = Match0 ? Y0 : OuterV0; 1948 X1 = Match1 ? X1 : OuterV1; 1949 Y1 = Match1 ? Y1 : OuterV1; 1950 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType()); 1951 auto *ShuffleSrcTy = dyn_cast<FixedVectorType>(X0->getType()); 1952 auto *ShuffleImmTy = dyn_cast<FixedVectorType>(OuterV0->getType()); 1953 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy || 1954 X0->getType() != X1->getType()) 1955 return false; 1956 1957 unsigned NumSrcElts = ShuffleSrcTy->getNumElements(); 1958 unsigned NumImmElts = ShuffleImmTy->getNumElements(); 1959 1960 // Attempt to merge shuffles, matching upto 2 source operands. 1961 // Replace index to a poison arg with PoisonMaskElem. 1962 // Bail if either inner masks reference an undef arg. 1963 SmallVector<int, 16> NewMask(OuterMask); 1964 Value *NewX = nullptr, *NewY = nullptr; 1965 for (int &M : NewMask) { 1966 Value *Src = nullptr; 1967 if (0 <= M && M < (int)NumImmElts) { 1968 Src = OuterV0; 1969 if (Match0) { 1970 M = InnerMask0[M]; 1971 Src = M >= (int)NumSrcElts ? Y0 : X0; 1972 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M; 1973 } 1974 } else if (M >= (int)NumImmElts) { 1975 Src = OuterV1; 1976 M -= NumImmElts; 1977 if (Match1) { 1978 M = InnerMask1[M]; 1979 Src = M >= (int)NumSrcElts ? Y1 : X1; 1980 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M; 1981 } 1982 } 1983 if (Src && M != PoisonMaskElem) { 1984 assert(0 <= M && M < (int)NumSrcElts && "Unexpected shuffle mask index"); 1985 if (isa<UndefValue>(Src)) { 1986 // We've referenced an undef element - if its poison, update the shuffle 1987 // mask, else bail. 1988 if (!isa<PoisonValue>(Src)) 1989 return false; 1990 M = PoisonMaskElem; 1991 continue; 1992 } 1993 if (!NewX || NewX == Src) { 1994 NewX = Src; 1995 continue; 1996 } 1997 if (!NewY || NewY == Src) { 1998 M += NumSrcElts; 1999 NewY = Src; 2000 continue; 2001 } 2002 return false; 2003 } 2004 } 2005 2006 if (!NewX) 2007 return PoisonValue::get(ShuffleDstTy); 2008 if (!NewY) 2009 NewY = PoisonValue::get(ShuffleSrcTy); 2010 2011 // Have we folded to an Identity shuffle? 2012 if (ShuffleVectorInst::isIdentityMask(NewMask, NumSrcElts)) { 2013 replaceValue(I, *NewX); 2014 return true; 2015 } 2016 2017 // Try to merge the shuffles if the new shuffle is not costly. 2018 InstructionCost InnerCost0 = 0; 2019 if (Match0) 2020 InnerCost0 = TTI.getInstructionCost(cast<Instruction>(OuterV0), CostKind); 2021 2022 InstructionCost InnerCost1 = 0; 2023 if (Match1) 2024 InnerCost1 = TTI.getInstructionCost(cast<Instruction>(OuterV1), CostKind); 2025 2026 InstructionCost OuterCost = TTI.getShuffleCost( 2027 TargetTransformInfo::SK_PermuteTwoSrc, ShuffleImmTy, OuterMask, CostKind, 2028 0, nullptr, {OuterV0, OuterV1}, &I); 2029 2030 InstructionCost OldCost = InnerCost0 + InnerCost1 + OuterCost; 2031 2032 bool IsUnary = all_of(NewMask, [&](int M) { return M < (int)NumSrcElts; }); 2033 TargetTransformInfo::ShuffleKind SK = 2034 IsUnary ? TargetTransformInfo::SK_PermuteSingleSrc 2035 : TargetTransformInfo::SK_PermuteTwoSrc; 2036 InstructionCost NewCost = TTI.getShuffleCost( 2037 SK, ShuffleSrcTy, NewMask, CostKind, 0, nullptr, {NewX, NewY}); 2038 if (!OuterV0->hasOneUse()) 2039 NewCost += InnerCost0; 2040 if (!OuterV1->hasOneUse()) 2041 NewCost += InnerCost1; 2042 2043 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two shuffles: " << I 2044 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 2045 << "\n"); 2046 if (NewCost > OldCost) 2047 return false; 2048 2049 Value *Shuf = Builder.CreateShuffleVector(NewX, NewY, NewMask); 2050 replaceValue(I, *Shuf); 2051 return true; 2052 } 2053 2054 /// Try to convert 2055 /// "shuffle (intrinsic), (intrinsic)" into "intrinsic (shuffle), (shuffle)". 2056 bool VectorCombine::foldShuffleOfIntrinsics(Instruction &I) { 2057 Value *V0, *V1; 2058 ArrayRef<int> OldMask; 2059 if (!match(&I, m_Shuffle(m_OneUse(m_Value(V0)), m_OneUse(m_Value(V1)), 2060 m_Mask(OldMask)))) 2061 return false; 2062 2063 auto *II0 = dyn_cast<IntrinsicInst>(V0); 2064 auto *II1 = dyn_cast<IntrinsicInst>(V1); 2065 if (!II0 || !II1) 2066 return false; 2067 2068 Intrinsic::ID IID = II0->getIntrinsicID(); 2069 if (IID != II1->getIntrinsicID()) 2070 return false; 2071 2072 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType()); 2073 auto *II0Ty = dyn_cast<FixedVectorType>(II0->getType()); 2074 if (!ShuffleDstTy || !II0Ty) 2075 return false; 2076 2077 if (!isTriviallyVectorizable(IID)) 2078 return false; 2079 2080 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) 2081 if (isVectorIntrinsicWithScalarOpAtArg(IID, I, &TTI) && 2082 II0->getArgOperand(I) != II1->getArgOperand(I)) 2083 return false; 2084 2085 InstructionCost OldCost = 2086 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II0), CostKind) + 2087 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II1), CostKind) + 2088 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, II0Ty, OldMask, 2089 CostKind, 0, nullptr, {II0, II1}, &I); 2090 2091 SmallVector<Type *> NewArgsTy; 2092 InstructionCost NewCost = 0; 2093 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) 2094 if (isVectorIntrinsicWithScalarOpAtArg(IID, I, &TTI)) { 2095 NewArgsTy.push_back(II0->getArgOperand(I)->getType()); 2096 } else { 2097 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(I)->getType()); 2098 NewArgsTy.push_back(FixedVectorType::get(VecTy->getElementType(), 2099 VecTy->getNumElements() * 2)); 2100 NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, 2101 VecTy, OldMask, CostKind); 2102 } 2103 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy); 2104 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind); 2105 2106 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two intrinsics: " << I 2107 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 2108 << "\n"); 2109 2110 if (NewCost > OldCost) 2111 return false; 2112 2113 SmallVector<Value *> NewArgs; 2114 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) 2115 if (isVectorIntrinsicWithScalarOpAtArg(IID, I, &TTI)) { 2116 NewArgs.push_back(II0->getArgOperand(I)); 2117 } else { 2118 Value *Shuf = Builder.CreateShuffleVector(II0->getArgOperand(I), 2119 II1->getArgOperand(I), OldMask); 2120 NewArgs.push_back(Shuf); 2121 Worklist.pushValue(Shuf); 2122 } 2123 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs); 2124 2125 // Intersect flags from the old intrinsics. 2126 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic)) { 2127 NewInst->copyIRFlags(II0); 2128 NewInst->andIRFlags(II1); 2129 } 2130 2131 replaceValue(I, *NewIntrinsic); 2132 return true; 2133 } 2134 2135 using InstLane = std::pair<Use *, int>; 2136 2137 static InstLane lookThroughShuffles(Use *U, int Lane) { 2138 while (auto *SV = dyn_cast<ShuffleVectorInst>(U->get())) { 2139 unsigned NumElts = 2140 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements(); 2141 int M = SV->getMaskValue(Lane); 2142 if (M < 0) 2143 return {nullptr, PoisonMaskElem}; 2144 if (static_cast<unsigned>(M) < NumElts) { 2145 U = &SV->getOperandUse(0); 2146 Lane = M; 2147 } else { 2148 U = &SV->getOperandUse(1); 2149 Lane = M - NumElts; 2150 } 2151 } 2152 return InstLane{U, Lane}; 2153 } 2154 2155 static SmallVector<InstLane> 2156 generateInstLaneVectorFromOperand(ArrayRef<InstLane> Item, int Op) { 2157 SmallVector<InstLane> NItem; 2158 for (InstLane IL : Item) { 2159 auto [U, Lane] = IL; 2160 InstLane OpLane = 2161 U ? lookThroughShuffles(&cast<Instruction>(U->get())->getOperandUse(Op), 2162 Lane) 2163 : InstLane{nullptr, PoisonMaskElem}; 2164 NItem.emplace_back(OpLane); 2165 } 2166 return NItem; 2167 } 2168 2169 /// Detect concat of multiple values into a vector 2170 static bool isFreeConcat(ArrayRef<InstLane> Item, TTI::TargetCostKind CostKind, 2171 const TargetTransformInfo &TTI) { 2172 auto *Ty = cast<FixedVectorType>(Item.front().first->get()->getType()); 2173 unsigned NumElts = Ty->getNumElements(); 2174 if (Item.size() == NumElts || NumElts == 1 || Item.size() % NumElts != 0) 2175 return false; 2176 2177 // Check that the concat is free, usually meaning that the type will be split 2178 // during legalization. 2179 SmallVector<int, 16> ConcatMask(NumElts * 2); 2180 std::iota(ConcatMask.begin(), ConcatMask.end(), 0); 2181 if (TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, ConcatMask, CostKind) != 0) 2182 return false; 2183 2184 unsigned NumSlices = Item.size() / NumElts; 2185 // Currently we generate a tree of shuffles for the concats, which limits us 2186 // to a power2. 2187 if (!isPowerOf2_32(NumSlices)) 2188 return false; 2189 for (unsigned Slice = 0; Slice < NumSlices; ++Slice) { 2190 Use *SliceV = Item[Slice * NumElts].first; 2191 if (!SliceV || SliceV->get()->getType() != Ty) 2192 return false; 2193 for (unsigned Elt = 0; Elt < NumElts; ++Elt) { 2194 auto [V, Lane] = Item[Slice * NumElts + Elt]; 2195 if (Lane != static_cast<int>(Elt) || SliceV->get() != V->get()) 2196 return false; 2197 } 2198 } 2199 return true; 2200 } 2201 2202 static Value *generateNewInstTree(ArrayRef<InstLane> Item, FixedVectorType *Ty, 2203 const SmallPtrSet<Use *, 4> &IdentityLeafs, 2204 const SmallPtrSet<Use *, 4> &SplatLeafs, 2205 const SmallPtrSet<Use *, 4> &ConcatLeafs, 2206 IRBuilder<> &Builder, 2207 const TargetTransformInfo *TTI) { 2208 auto [FrontU, FrontLane] = Item.front(); 2209 2210 if (IdentityLeafs.contains(FrontU)) { 2211 return FrontU->get(); 2212 } 2213 if (SplatLeafs.contains(FrontU)) { 2214 SmallVector<int, 16> Mask(Ty->getNumElements(), FrontLane); 2215 return Builder.CreateShuffleVector(FrontU->get(), Mask); 2216 } 2217 if (ConcatLeafs.contains(FrontU)) { 2218 unsigned NumElts = 2219 cast<FixedVectorType>(FrontU->get()->getType())->getNumElements(); 2220 SmallVector<Value *> Values(Item.size() / NumElts, nullptr); 2221 for (unsigned S = 0; S < Values.size(); ++S) 2222 Values[S] = Item[S * NumElts].first->get(); 2223 2224 while (Values.size() > 1) { 2225 NumElts *= 2; 2226 SmallVector<int, 16> Mask(NumElts, 0); 2227 std::iota(Mask.begin(), Mask.end(), 0); 2228 SmallVector<Value *> NewValues(Values.size() / 2, nullptr); 2229 for (unsigned S = 0; S < NewValues.size(); ++S) 2230 NewValues[S] = 2231 Builder.CreateShuffleVector(Values[S * 2], Values[S * 2 + 1], Mask); 2232 Values = NewValues; 2233 } 2234 return Values[0]; 2235 } 2236 2237 auto *I = cast<Instruction>(FrontU->get()); 2238 auto *II = dyn_cast<IntrinsicInst>(I); 2239 unsigned NumOps = I->getNumOperands() - (II ? 1 : 0); 2240 SmallVector<Value *> Ops(NumOps); 2241 for (unsigned Idx = 0; Idx < NumOps; Idx++) { 2242 if (II && 2243 isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, TTI)) { 2244 Ops[Idx] = II->getOperand(Idx); 2245 continue; 2246 } 2247 Ops[Idx] = generateNewInstTree(generateInstLaneVectorFromOperand(Item, Idx), 2248 Ty, IdentityLeafs, SplatLeafs, ConcatLeafs, 2249 Builder, TTI); 2250 } 2251 2252 SmallVector<Value *, 8> ValueList; 2253 for (const auto &Lane : Item) 2254 if (Lane.first) 2255 ValueList.push_back(Lane.first->get()); 2256 2257 Type *DstTy = 2258 FixedVectorType::get(I->getType()->getScalarType(), Ty->getNumElements()); 2259 if (auto *BI = dyn_cast<BinaryOperator>(I)) { 2260 auto *Value = Builder.CreateBinOp((Instruction::BinaryOps)BI->getOpcode(), 2261 Ops[0], Ops[1]); 2262 propagateIRFlags(Value, ValueList); 2263 return Value; 2264 } 2265 if (auto *CI = dyn_cast<CmpInst>(I)) { 2266 auto *Value = Builder.CreateCmp(CI->getPredicate(), Ops[0], Ops[1]); 2267 propagateIRFlags(Value, ValueList); 2268 return Value; 2269 } 2270 if (auto *SI = dyn_cast<SelectInst>(I)) { 2271 auto *Value = Builder.CreateSelect(Ops[0], Ops[1], Ops[2], "", SI); 2272 propagateIRFlags(Value, ValueList); 2273 return Value; 2274 } 2275 if (auto *CI = dyn_cast<CastInst>(I)) { 2276 auto *Value = Builder.CreateCast((Instruction::CastOps)CI->getOpcode(), 2277 Ops[0], DstTy); 2278 propagateIRFlags(Value, ValueList); 2279 return Value; 2280 } 2281 if (II) { 2282 auto *Value = Builder.CreateIntrinsic(DstTy, II->getIntrinsicID(), Ops); 2283 propagateIRFlags(Value, ValueList); 2284 return Value; 2285 } 2286 assert(isa<UnaryInstruction>(I) && "Unexpected instruction type in Generate"); 2287 auto *Value = 2288 Builder.CreateUnOp((Instruction::UnaryOps)I->getOpcode(), Ops[0]); 2289 propagateIRFlags(Value, ValueList); 2290 return Value; 2291 } 2292 2293 // Starting from a shuffle, look up through operands tracking the shuffled index 2294 // of each lane. If we can simplify away the shuffles to identities then 2295 // do so. 2296 bool VectorCombine::foldShuffleToIdentity(Instruction &I) { 2297 auto *Ty = dyn_cast<FixedVectorType>(I.getType()); 2298 if (!Ty || I.use_empty()) 2299 return false; 2300 2301 SmallVector<InstLane> Start(Ty->getNumElements()); 2302 for (unsigned M = 0, E = Ty->getNumElements(); M < E; ++M) 2303 Start[M] = lookThroughShuffles(&*I.use_begin(), M); 2304 2305 SmallVector<SmallVector<InstLane>> Worklist; 2306 Worklist.push_back(Start); 2307 SmallPtrSet<Use *, 4> IdentityLeafs, SplatLeafs, ConcatLeafs; 2308 unsigned NumVisited = 0; 2309 2310 while (!Worklist.empty()) { 2311 if (++NumVisited > MaxInstrsToScan) 2312 return false; 2313 2314 SmallVector<InstLane> Item = Worklist.pop_back_val(); 2315 auto [FrontU, FrontLane] = Item.front(); 2316 2317 // If we found an undef first lane then bail out to keep things simple. 2318 if (!FrontU) 2319 return false; 2320 2321 // Helper to peek through bitcasts to the same value. 2322 auto IsEquiv = [&](Value *X, Value *Y) { 2323 return X->getType() == Y->getType() && 2324 peekThroughBitcasts(X) == peekThroughBitcasts(Y); 2325 }; 2326 2327 // Look for an identity value. 2328 if (FrontLane == 0 && 2329 cast<FixedVectorType>(FrontU->get()->getType())->getNumElements() == 2330 Ty->getNumElements() && 2331 all_of(drop_begin(enumerate(Item)), [IsEquiv, Item](const auto &E) { 2332 Value *FrontV = Item.front().first->get(); 2333 return !E.value().first || (IsEquiv(E.value().first->get(), FrontV) && 2334 E.value().second == (int)E.index()); 2335 })) { 2336 IdentityLeafs.insert(FrontU); 2337 continue; 2338 } 2339 // Look for constants, for the moment only supporting constant splats. 2340 if (auto *C = dyn_cast<Constant>(FrontU); 2341 C && C->getSplatValue() && 2342 all_of(drop_begin(Item), [Item](InstLane &IL) { 2343 Value *FrontV = Item.front().first->get(); 2344 Use *U = IL.first; 2345 return !U || (isa<Constant>(U->get()) && 2346 cast<Constant>(U->get())->getSplatValue() == 2347 cast<Constant>(FrontV)->getSplatValue()); 2348 })) { 2349 SplatLeafs.insert(FrontU); 2350 continue; 2351 } 2352 // Look for a splat value. 2353 if (all_of(drop_begin(Item), [Item](InstLane &IL) { 2354 auto [FrontU, FrontLane] = Item.front(); 2355 auto [U, Lane] = IL; 2356 return !U || (U->get() == FrontU->get() && Lane == FrontLane); 2357 })) { 2358 SplatLeafs.insert(FrontU); 2359 continue; 2360 } 2361 2362 // We need each element to be the same type of value, and check that each 2363 // element has a single use. 2364 auto CheckLaneIsEquivalentToFirst = [Item](InstLane IL) { 2365 Value *FrontV = Item.front().first->get(); 2366 if (!IL.first) 2367 return true; 2368 Value *V = IL.first->get(); 2369 if (auto *I = dyn_cast<Instruction>(V); I && !I->hasOneUse()) 2370 return false; 2371 if (V->getValueID() != FrontV->getValueID()) 2372 return false; 2373 if (auto *CI = dyn_cast<CmpInst>(V)) 2374 if (CI->getPredicate() != cast<CmpInst>(FrontV)->getPredicate()) 2375 return false; 2376 if (auto *CI = dyn_cast<CastInst>(V)) 2377 if (CI->getSrcTy()->getScalarType() != 2378 cast<CastInst>(FrontV)->getSrcTy()->getScalarType()) 2379 return false; 2380 if (auto *SI = dyn_cast<SelectInst>(V)) 2381 if (!isa<VectorType>(SI->getOperand(0)->getType()) || 2382 SI->getOperand(0)->getType() != 2383 cast<SelectInst>(FrontV)->getOperand(0)->getType()) 2384 return false; 2385 if (isa<CallInst>(V) && !isa<IntrinsicInst>(V)) 2386 return false; 2387 auto *II = dyn_cast<IntrinsicInst>(V); 2388 return !II || (isa<IntrinsicInst>(FrontV) && 2389 II->getIntrinsicID() == 2390 cast<IntrinsicInst>(FrontV)->getIntrinsicID() && 2391 !II->hasOperandBundles()); 2392 }; 2393 if (all_of(drop_begin(Item), CheckLaneIsEquivalentToFirst)) { 2394 // Check the operator is one that we support. 2395 if (isa<BinaryOperator, CmpInst>(FrontU)) { 2396 // We exclude div/rem in case they hit UB from poison lanes. 2397 if (auto *BO = dyn_cast<BinaryOperator>(FrontU); 2398 BO && BO->isIntDivRem()) 2399 return false; 2400 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 0)); 2401 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 1)); 2402 continue; 2403 } else if (isa<UnaryOperator, TruncInst, ZExtInst, SExtInst, FPToSIInst, 2404 FPToUIInst, SIToFPInst, UIToFPInst>(FrontU)) { 2405 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 0)); 2406 continue; 2407 } else if (auto *BitCast = dyn_cast<BitCastInst>(FrontU)) { 2408 // TODO: Handle vector widening/narrowing bitcasts. 2409 auto *DstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy()); 2410 auto *SrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy()); 2411 if (DstTy && SrcTy && 2412 SrcTy->getNumElements() == DstTy->getNumElements()) { 2413 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 0)); 2414 continue; 2415 } 2416 } else if (isa<SelectInst>(FrontU)) { 2417 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 0)); 2418 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 1)); 2419 Worklist.push_back(generateInstLaneVectorFromOperand(Item, 2)); 2420 continue; 2421 } else if (auto *II = dyn_cast<IntrinsicInst>(FrontU); 2422 II && isTriviallyVectorizable(II->getIntrinsicID()) && 2423 !II->hasOperandBundles()) { 2424 for (unsigned Op = 0, E = II->getNumOperands() - 1; Op < E; Op++) { 2425 if (isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Op, 2426 &TTI)) { 2427 if (!all_of(drop_begin(Item), [Item, Op](InstLane &IL) { 2428 Value *FrontV = Item.front().first->get(); 2429 Use *U = IL.first; 2430 return !U || (cast<Instruction>(U->get())->getOperand(Op) == 2431 cast<Instruction>(FrontV)->getOperand(Op)); 2432 })) 2433 return false; 2434 continue; 2435 } 2436 Worklist.push_back(generateInstLaneVectorFromOperand(Item, Op)); 2437 } 2438 continue; 2439 } 2440 } 2441 2442 if (isFreeConcat(Item, CostKind, TTI)) { 2443 ConcatLeafs.insert(FrontU); 2444 continue; 2445 } 2446 2447 return false; 2448 } 2449 2450 if (NumVisited <= 1) 2451 return false; 2452 2453 LLVM_DEBUG(dbgs() << "Found a superfluous identity shuffle: " << I << "\n"); 2454 2455 // If we got this far, we know the shuffles are superfluous and can be 2456 // removed. Scan through again and generate the new tree of instructions. 2457 Builder.SetInsertPoint(&I); 2458 Value *V = generateNewInstTree(Start, Ty, IdentityLeafs, SplatLeafs, 2459 ConcatLeafs, Builder, &TTI); 2460 replaceValue(I, *V); 2461 return true; 2462 } 2463 2464 /// Given a commutative reduction, the order of the input lanes does not alter 2465 /// the results. We can use this to remove certain shuffles feeding the 2466 /// reduction, removing the need to shuffle at all. 2467 bool VectorCombine::foldShuffleFromReductions(Instruction &I) { 2468 auto *II = dyn_cast<IntrinsicInst>(&I); 2469 if (!II) 2470 return false; 2471 switch (II->getIntrinsicID()) { 2472 case Intrinsic::vector_reduce_add: 2473 case Intrinsic::vector_reduce_mul: 2474 case Intrinsic::vector_reduce_and: 2475 case Intrinsic::vector_reduce_or: 2476 case Intrinsic::vector_reduce_xor: 2477 case Intrinsic::vector_reduce_smin: 2478 case Intrinsic::vector_reduce_smax: 2479 case Intrinsic::vector_reduce_umin: 2480 case Intrinsic::vector_reduce_umax: 2481 break; 2482 default: 2483 return false; 2484 } 2485 2486 // Find all the inputs when looking through operations that do not alter the 2487 // lane order (binops, for example). Currently we look for a single shuffle, 2488 // and can ignore splat values. 2489 std::queue<Value *> Worklist; 2490 SmallPtrSet<Value *, 4> Visited; 2491 ShuffleVectorInst *Shuffle = nullptr; 2492 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0))) 2493 Worklist.push(Op); 2494 2495 while (!Worklist.empty()) { 2496 Value *CV = Worklist.front(); 2497 Worklist.pop(); 2498 if (Visited.contains(CV)) 2499 continue; 2500 2501 // Splats don't change the order, so can be safely ignored. 2502 if (isSplatValue(CV)) 2503 continue; 2504 2505 Visited.insert(CV); 2506 2507 if (auto *CI = dyn_cast<Instruction>(CV)) { 2508 if (CI->isBinaryOp()) { 2509 for (auto *Op : CI->operand_values()) 2510 Worklist.push(Op); 2511 continue; 2512 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) { 2513 if (Shuffle && Shuffle != SV) 2514 return false; 2515 Shuffle = SV; 2516 continue; 2517 } 2518 } 2519 2520 // Anything else is currently an unknown node. 2521 return false; 2522 } 2523 2524 if (!Shuffle) 2525 return false; 2526 2527 // Check all uses of the binary ops and shuffles are also included in the 2528 // lane-invariant operations (Visited should be the list of lanewise 2529 // instructions, including the shuffle that we found). 2530 for (auto *V : Visited) 2531 for (auto *U : V->users()) 2532 if (!Visited.contains(U) && U != &I) 2533 return false; 2534 2535 FixedVectorType *VecType = 2536 dyn_cast<FixedVectorType>(II->getOperand(0)->getType()); 2537 if (!VecType) 2538 return false; 2539 FixedVectorType *ShuffleInputType = 2540 dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType()); 2541 if (!ShuffleInputType) 2542 return false; 2543 unsigned NumInputElts = ShuffleInputType->getNumElements(); 2544 2545 // Find the mask from sorting the lanes into order. This is most likely to 2546 // become a identity or concat mask. Undef elements are pushed to the end. 2547 SmallVector<int> ConcatMask; 2548 Shuffle->getShuffleMask(ConcatMask); 2549 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; }); 2550 // In the case of a truncating shuffle it's possible for the mask 2551 // to have an index greater than the size of the resulting vector. 2552 // This requires special handling. 2553 bool IsTruncatingShuffle = VecType->getNumElements() < NumInputElts; 2554 bool UsesSecondVec = 2555 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; }); 2556 2557 FixedVectorType *VecTyForCost = 2558 (UsesSecondVec && !IsTruncatingShuffle) ? VecType : ShuffleInputType; 2559 InstructionCost OldCost = TTI.getShuffleCost( 2560 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, 2561 VecTyForCost, Shuffle->getShuffleMask(), CostKind); 2562 InstructionCost NewCost = TTI.getShuffleCost( 2563 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, 2564 VecTyForCost, ConcatMask, CostKind); 2565 2566 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle 2567 << "\n"); 2568 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost 2569 << "\n"); 2570 if (NewCost < OldCost) { 2571 Builder.SetInsertPoint(Shuffle); 2572 Value *NewShuffle = Builder.CreateShuffleVector( 2573 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask); 2574 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n"); 2575 replaceValue(*Shuffle, *NewShuffle); 2576 } 2577 2578 // See if we can re-use foldSelectShuffle, getting it to reduce the size of 2579 // the shuffle into a nicer order, as it can ignore the order of the shuffles. 2580 return foldSelectShuffle(*Shuffle, true); 2581 } 2582 2583 /// Determine if its more efficient to fold: 2584 /// reduce(trunc(x)) -> trunc(reduce(x)). 2585 /// reduce(sext(x)) -> sext(reduce(x)). 2586 /// reduce(zext(x)) -> zext(reduce(x)). 2587 bool VectorCombine::foldCastFromReductions(Instruction &I) { 2588 auto *II = dyn_cast<IntrinsicInst>(&I); 2589 if (!II) 2590 return false; 2591 2592 bool TruncOnly = false; 2593 Intrinsic::ID IID = II->getIntrinsicID(); 2594 switch (IID) { 2595 case Intrinsic::vector_reduce_add: 2596 case Intrinsic::vector_reduce_mul: 2597 TruncOnly = true; 2598 break; 2599 case Intrinsic::vector_reduce_and: 2600 case Intrinsic::vector_reduce_or: 2601 case Intrinsic::vector_reduce_xor: 2602 break; 2603 default: 2604 return false; 2605 } 2606 2607 unsigned ReductionOpc = getArithmeticReductionInstruction(IID); 2608 Value *ReductionSrc = I.getOperand(0); 2609 2610 Value *Src; 2611 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(Src)))) && 2612 (TruncOnly || !match(ReductionSrc, m_OneUse(m_ZExtOrSExt(m_Value(Src)))))) 2613 return false; 2614 2615 auto CastOpc = 2616 (Instruction::CastOps)cast<Instruction>(ReductionSrc)->getOpcode(); 2617 2618 auto *SrcTy = cast<VectorType>(Src->getType()); 2619 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType()); 2620 Type *ResultTy = I.getType(); 2621 2622 InstructionCost OldCost = TTI.getArithmeticReductionCost( 2623 ReductionOpc, ReductionSrcTy, std::nullopt, CostKind); 2624 OldCost += TTI.getCastInstrCost(CastOpc, ReductionSrcTy, SrcTy, 2625 TTI::CastContextHint::None, CostKind, 2626 cast<CastInst>(ReductionSrc)); 2627 InstructionCost NewCost = 2628 TTI.getArithmeticReductionCost(ReductionOpc, SrcTy, std::nullopt, 2629 CostKind) + 2630 TTI.getCastInstrCost(CastOpc, ResultTy, ReductionSrcTy->getScalarType(), 2631 TTI::CastContextHint::None, CostKind); 2632 2633 if (OldCost <= NewCost || !NewCost.isValid()) 2634 return false; 2635 2636 Value *NewReduction = Builder.CreateIntrinsic(SrcTy->getScalarType(), 2637 II->getIntrinsicID(), {Src}); 2638 Value *NewCast = Builder.CreateCast(CastOpc, NewReduction, ResultTy); 2639 replaceValue(I, *NewCast); 2640 return true; 2641 } 2642 2643 /// This method looks for groups of shuffles acting on binops, of the form: 2644 /// %x = shuffle ... 2645 /// %y = shuffle ... 2646 /// %a = binop %x, %y 2647 /// %b = binop %x, %y 2648 /// shuffle %a, %b, selectmask 2649 /// We may, especially if the shuffle is wider than legal, be able to convert 2650 /// the shuffle to a form where only parts of a and b need to be computed. On 2651 /// architectures with no obvious "select" shuffle, this can reduce the total 2652 /// number of operations if the target reports them as cheaper. 2653 bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) { 2654 auto *SVI = cast<ShuffleVectorInst>(&I); 2655 auto *VT = cast<FixedVectorType>(I.getType()); 2656 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0)); 2657 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1)); 2658 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() || 2659 VT != Op0->getType()) 2660 return false; 2661 2662 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0)); 2663 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1)); 2664 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0)); 2665 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1)); 2666 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B}); 2667 auto checkSVNonOpUses = [&](Instruction *I) { 2668 if (!I || I->getOperand(0)->getType() != VT) 2669 return true; 2670 return any_of(I->users(), [&](User *U) { 2671 return U != Op0 && U != Op1 && 2672 !(isa<ShuffleVectorInst>(U) && 2673 (InputShuffles.contains(cast<Instruction>(U)) || 2674 isInstructionTriviallyDead(cast<Instruction>(U)))); 2675 }); 2676 }; 2677 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) || 2678 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B)) 2679 return false; 2680 2681 // Collect all the uses that are shuffles that we can transform together. We 2682 // may not have a single shuffle, but a group that can all be transformed 2683 // together profitably. 2684 SmallVector<ShuffleVectorInst *> Shuffles; 2685 auto collectShuffles = [&](Instruction *I) { 2686 for (auto *U : I->users()) { 2687 auto *SV = dyn_cast<ShuffleVectorInst>(U); 2688 if (!SV || SV->getType() != VT) 2689 return false; 2690 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) || 2691 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1)) 2692 return false; 2693 if (!llvm::is_contained(Shuffles, SV)) 2694 Shuffles.push_back(SV); 2695 } 2696 return true; 2697 }; 2698 if (!collectShuffles(Op0) || !collectShuffles(Op1)) 2699 return false; 2700 // From a reduction, we need to be processing a single shuffle, otherwise the 2701 // other uses will not be lane-invariant. 2702 if (FromReduction && Shuffles.size() > 1) 2703 return false; 2704 2705 // Add any shuffle uses for the shuffles we have found, to include them in our 2706 // cost calculations. 2707 if (!FromReduction) { 2708 for (ShuffleVectorInst *SV : Shuffles) { 2709 for (auto *U : SV->users()) { 2710 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U); 2711 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT) 2712 Shuffles.push_back(SSV); 2713 } 2714 } 2715 } 2716 2717 // For each of the output shuffles, we try to sort all the first vector 2718 // elements to the beginning, followed by the second array elements at the 2719 // end. If the binops are legalized to smaller vectors, this may reduce total 2720 // number of binops. We compute the ReconstructMask mask needed to convert 2721 // back to the original lane order. 2722 SmallVector<std::pair<int, int>> V1, V2; 2723 SmallVector<SmallVector<int>> OrigReconstructMasks; 2724 int MaxV1Elt = 0, MaxV2Elt = 0; 2725 unsigned NumElts = VT->getNumElements(); 2726 for (ShuffleVectorInst *SVN : Shuffles) { 2727 SmallVector<int> Mask; 2728 SVN->getShuffleMask(Mask); 2729 2730 // Check the operands are the same as the original, or reversed (in which 2731 // case we need to commute the mask). 2732 Value *SVOp0 = SVN->getOperand(0); 2733 Value *SVOp1 = SVN->getOperand(1); 2734 if (isa<UndefValue>(SVOp1)) { 2735 auto *SSV = cast<ShuffleVectorInst>(SVOp0); 2736 SVOp0 = SSV->getOperand(0); 2737 SVOp1 = SSV->getOperand(1); 2738 for (unsigned I = 0, E = Mask.size(); I != E; I++) { 2739 if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size())) 2740 return false; 2741 Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]); 2742 } 2743 } 2744 if (SVOp0 == Op1 && SVOp1 == Op0) { 2745 std::swap(SVOp0, SVOp1); 2746 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts); 2747 } 2748 if (SVOp0 != Op0 || SVOp1 != Op1) 2749 return false; 2750 2751 // Calculate the reconstruction mask for this shuffle, as the mask needed to 2752 // take the packed values from Op0/Op1 and reconstructing to the original 2753 // order. 2754 SmallVector<int> ReconstructMask; 2755 for (unsigned I = 0; I < Mask.size(); I++) { 2756 if (Mask[I] < 0) { 2757 ReconstructMask.push_back(-1); 2758 } else if (Mask[I] < static_cast<int>(NumElts)) { 2759 MaxV1Elt = std::max(MaxV1Elt, Mask[I]); 2760 auto It = find_if(V1, [&](const std::pair<int, int> &A) { 2761 return Mask[I] == A.first; 2762 }); 2763 if (It != V1.end()) 2764 ReconstructMask.push_back(It - V1.begin()); 2765 else { 2766 ReconstructMask.push_back(V1.size()); 2767 V1.emplace_back(Mask[I], V1.size()); 2768 } 2769 } else { 2770 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts); 2771 auto It = find_if(V2, [&](const std::pair<int, int> &A) { 2772 return Mask[I] - static_cast<int>(NumElts) == A.first; 2773 }); 2774 if (It != V2.end()) 2775 ReconstructMask.push_back(NumElts + It - V2.begin()); 2776 else { 2777 ReconstructMask.push_back(NumElts + V2.size()); 2778 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size()); 2779 } 2780 } 2781 } 2782 2783 // For reductions, we know that the lane ordering out doesn't alter the 2784 // result. In-order can help simplify the shuffle away. 2785 if (FromReduction) 2786 sort(ReconstructMask); 2787 OrigReconstructMasks.push_back(std::move(ReconstructMask)); 2788 } 2789 2790 // If the Maximum element used from V1 and V2 are not larger than the new 2791 // vectors, the vectors are already packes and performing the optimization 2792 // again will likely not help any further. This also prevents us from getting 2793 // stuck in a cycle in case the costs do not also rule it out. 2794 if (V1.empty() || V2.empty() || 2795 (MaxV1Elt == static_cast<int>(V1.size()) - 1 && 2796 MaxV2Elt == static_cast<int>(V2.size()) - 1)) 2797 return false; 2798 2799 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a 2800 // shuffle of another shuffle, or not a shuffle (that is treated like a 2801 // identity shuffle). 2802 auto GetBaseMaskValue = [&](Instruction *I, int M) { 2803 auto *SV = dyn_cast<ShuffleVectorInst>(I); 2804 if (!SV) 2805 return M; 2806 if (isa<UndefValue>(SV->getOperand(1))) 2807 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0))) 2808 if (InputShuffles.contains(SSV)) 2809 return SSV->getMaskValue(SV->getMaskValue(M)); 2810 return SV->getMaskValue(M); 2811 }; 2812 2813 // Attempt to sort the inputs my ascending mask values to make simpler input 2814 // shuffles and push complex shuffles down to the uses. We sort on the first 2815 // of the two input shuffle orders, to try and get at least one input into a 2816 // nice order. 2817 auto SortBase = [&](Instruction *A, std::pair<int, int> X, 2818 std::pair<int, int> Y) { 2819 int MXA = GetBaseMaskValue(A, X.first); 2820 int MYA = GetBaseMaskValue(A, Y.first); 2821 return MXA < MYA; 2822 }; 2823 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) { 2824 return SortBase(SVI0A, A, B); 2825 }); 2826 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) { 2827 return SortBase(SVI1A, A, B); 2828 }); 2829 // Calculate our ReconstructMasks from the OrigReconstructMasks and the 2830 // modified order of the input shuffles. 2831 SmallVector<SmallVector<int>> ReconstructMasks; 2832 for (const auto &Mask : OrigReconstructMasks) { 2833 SmallVector<int> ReconstructMask; 2834 for (int M : Mask) { 2835 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) { 2836 auto It = find_if(V, [M](auto A) { return A.second == M; }); 2837 assert(It != V.end() && "Expected all entries in Mask"); 2838 return std::distance(V.begin(), It); 2839 }; 2840 if (M < 0) 2841 ReconstructMask.push_back(-1); 2842 else if (M < static_cast<int>(NumElts)) { 2843 ReconstructMask.push_back(FindIndex(V1, M)); 2844 } else { 2845 ReconstructMask.push_back(NumElts + FindIndex(V2, M)); 2846 } 2847 } 2848 ReconstructMasks.push_back(std::move(ReconstructMask)); 2849 } 2850 2851 // Calculate the masks needed for the new input shuffles, which get padded 2852 // with undef 2853 SmallVector<int> V1A, V1B, V2A, V2B; 2854 for (unsigned I = 0; I < V1.size(); I++) { 2855 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first)); 2856 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first)); 2857 } 2858 for (unsigned I = 0; I < V2.size(); I++) { 2859 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first)); 2860 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first)); 2861 } 2862 while (V1A.size() < NumElts) { 2863 V1A.push_back(PoisonMaskElem); 2864 V1B.push_back(PoisonMaskElem); 2865 } 2866 while (V2A.size() < NumElts) { 2867 V2A.push_back(PoisonMaskElem); 2868 V2B.push_back(PoisonMaskElem); 2869 } 2870 2871 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) { 2872 auto *SV = dyn_cast<ShuffleVectorInst>(I); 2873 if (!SV) 2874 return C; 2875 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1)) 2876 ? TTI::SK_PermuteSingleSrc 2877 : TTI::SK_PermuteTwoSrc, 2878 VT, SV->getShuffleMask(), CostKind); 2879 }; 2880 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) { 2881 return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask, CostKind); 2882 }; 2883 2884 // Get the costs of the shuffles + binops before and after with the new 2885 // shuffle masks. 2886 InstructionCost CostBefore = 2887 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT, CostKind) + 2888 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT, CostKind); 2889 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(), 2890 InstructionCost(0), AddShuffleCost); 2891 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(), 2892 InstructionCost(0), AddShuffleCost); 2893 2894 // The new binops will be unused for lanes past the used shuffle lengths. 2895 // These types attempt to get the correct cost for that from the target. 2896 FixedVectorType *Op0SmallVT = 2897 FixedVectorType::get(VT->getScalarType(), V1.size()); 2898 FixedVectorType *Op1SmallVT = 2899 FixedVectorType::get(VT->getScalarType(), V2.size()); 2900 InstructionCost CostAfter = 2901 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT, CostKind) + 2902 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT, CostKind); 2903 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(), 2904 InstructionCost(0), AddShuffleMaskCost); 2905 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B}); 2906 CostAfter += 2907 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(), 2908 InstructionCost(0), AddShuffleMaskCost); 2909 2910 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n"); 2911 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore 2912 << " vs CostAfter: " << CostAfter << "\n"); 2913 if (CostBefore <= CostAfter) 2914 return false; 2915 2916 // The cost model has passed, create the new instructions. 2917 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * { 2918 auto *SV = dyn_cast<ShuffleVectorInst>(I); 2919 if (!SV) 2920 return I; 2921 if (isa<UndefValue>(SV->getOperand(1))) 2922 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0))) 2923 if (InputShuffles.contains(SSV)) 2924 return SSV->getOperand(Op); 2925 return SV->getOperand(Op); 2926 }; 2927 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef()); 2928 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0), 2929 GetShuffleOperand(SVI0A, 1), V1A); 2930 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef()); 2931 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0), 2932 GetShuffleOperand(SVI0B, 1), V1B); 2933 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef()); 2934 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0), 2935 GetShuffleOperand(SVI1A, 1), V2A); 2936 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef()); 2937 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0), 2938 GetShuffleOperand(SVI1B, 1), V2B); 2939 Builder.SetInsertPoint(Op0); 2940 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(), 2941 NSV0A, NSV0B); 2942 if (auto *I = dyn_cast<Instruction>(NOp0)) 2943 I->copyIRFlags(Op0, true); 2944 Builder.SetInsertPoint(Op1); 2945 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(), 2946 NSV1A, NSV1B); 2947 if (auto *I = dyn_cast<Instruction>(NOp1)) 2948 I->copyIRFlags(Op1, true); 2949 2950 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) { 2951 Builder.SetInsertPoint(Shuffles[S]); 2952 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]); 2953 replaceValue(*Shuffles[S], *NSV); 2954 } 2955 2956 Worklist.pushValue(NSV0A); 2957 Worklist.pushValue(NSV0B); 2958 Worklist.pushValue(NSV1A); 2959 Worklist.pushValue(NSV1B); 2960 for (auto *S : Shuffles) 2961 Worklist.add(S); 2962 return true; 2963 } 2964 2965 /// Check if instruction depends on ZExt and this ZExt can be moved after the 2966 /// instruction. Move ZExt if it is profitable. For example: 2967 /// logic(zext(x),y) -> zext(logic(x,trunc(y))) 2968 /// lshr((zext(x),y) -> zext(lshr(x,trunc(y))) 2969 /// Cost model calculations takes into account if zext(x) has other users and 2970 /// whether it can be propagated through them too. 2971 bool VectorCombine::shrinkType(Instruction &I) { 2972 Value *ZExted, *OtherOperand; 2973 if (!match(&I, m_c_BitwiseLogic(m_ZExt(m_Value(ZExted)), 2974 m_Value(OtherOperand))) && 2975 !match(&I, m_LShr(m_ZExt(m_Value(ZExted)), m_Value(OtherOperand)))) 2976 return false; 2977 2978 Value *ZExtOperand = I.getOperand(I.getOperand(0) == OtherOperand ? 1 : 0); 2979 2980 auto *BigTy = cast<FixedVectorType>(I.getType()); 2981 auto *SmallTy = cast<FixedVectorType>(ZExted->getType()); 2982 unsigned BW = SmallTy->getElementType()->getPrimitiveSizeInBits(); 2983 2984 if (I.getOpcode() == Instruction::LShr) { 2985 // Check that the shift amount is less than the number of bits in the 2986 // smaller type. Otherwise, the smaller lshr will return a poison value. 2987 KnownBits ShAmtKB = computeKnownBits(I.getOperand(1), *DL); 2988 if (ShAmtKB.getMaxValue().uge(BW)) 2989 return false; 2990 } else { 2991 // Check that the expression overall uses at most the same number of bits as 2992 // ZExted 2993 KnownBits KB = computeKnownBits(&I, *DL); 2994 if (KB.countMaxActiveBits() > BW) 2995 return false; 2996 } 2997 2998 // Calculate costs of leaving current IR as it is and moving ZExt operation 2999 // later, along with adding truncates if needed 3000 InstructionCost ZExtCost = TTI.getCastInstrCost( 3001 Instruction::ZExt, BigTy, SmallTy, 3002 TargetTransformInfo::CastContextHint::None, CostKind); 3003 InstructionCost CurrentCost = ZExtCost; 3004 InstructionCost ShrinkCost = 0; 3005 3006 // Calculate total cost and check that we can propagate through all ZExt users 3007 for (User *U : ZExtOperand->users()) { 3008 auto *UI = cast<Instruction>(U); 3009 if (UI == &I) { 3010 CurrentCost += 3011 TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind); 3012 ShrinkCost += 3013 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind); 3014 ShrinkCost += ZExtCost; 3015 continue; 3016 } 3017 3018 if (!Instruction::isBinaryOp(UI->getOpcode())) 3019 return false; 3020 3021 // Check if we can propagate ZExt through its other users 3022 KnownBits KB = computeKnownBits(UI, *DL); 3023 if (KB.countMaxActiveBits() > BW) 3024 return false; 3025 3026 CurrentCost += TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind); 3027 ShrinkCost += 3028 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind); 3029 ShrinkCost += ZExtCost; 3030 } 3031 3032 // If the other instruction operand is not a constant, we'll need to 3033 // generate a truncate instruction. So we have to adjust cost 3034 if (!isa<Constant>(OtherOperand)) 3035 ShrinkCost += TTI.getCastInstrCost( 3036 Instruction::Trunc, SmallTy, BigTy, 3037 TargetTransformInfo::CastContextHint::None, CostKind); 3038 3039 // If the cost of shrinking types and leaving the IR is the same, we'll lean 3040 // towards modifying the IR because shrinking opens opportunities for other 3041 // shrinking optimisations. 3042 if (ShrinkCost > CurrentCost) 3043 return false; 3044 3045 Builder.SetInsertPoint(&I); 3046 Value *Op0 = ZExted; 3047 Value *Op1 = Builder.CreateTrunc(OtherOperand, SmallTy); 3048 // Keep the order of operands the same 3049 if (I.getOperand(0) == OtherOperand) 3050 std::swap(Op0, Op1); 3051 Value *NewBinOp = 3052 Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(), Op0, Op1); 3053 cast<Instruction>(NewBinOp)->copyIRFlags(&I); 3054 cast<Instruction>(NewBinOp)->copyMetadata(I); 3055 Value *NewZExtr = Builder.CreateZExt(NewBinOp, BigTy); 3056 replaceValue(I, *NewZExtr); 3057 return true; 3058 } 3059 3060 /// insert (DstVec, (extract SrcVec, ExtIdx), InsIdx) --> 3061 /// shuffle (DstVec, SrcVec, Mask) 3062 bool VectorCombine::foldInsExtVectorToShuffle(Instruction &I) { 3063 Value *DstVec, *SrcVec; 3064 uint64_t ExtIdx, InsIdx; 3065 if (!match(&I, 3066 m_InsertElt(m_Value(DstVec), 3067 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx)), 3068 m_ConstantInt(InsIdx)))) 3069 return false; 3070 3071 auto *VecTy = dyn_cast<FixedVectorType>(I.getType()); 3072 if (!VecTy || SrcVec->getType() != VecTy) 3073 return false; 3074 3075 unsigned NumElts = VecTy->getNumElements(); 3076 if (ExtIdx >= NumElts || InsIdx >= NumElts) 3077 return false; 3078 3079 // Insertion into poison is a cheaper single operand shuffle. 3080 TargetTransformInfo::ShuffleKind SK; 3081 SmallVector<int> Mask(NumElts, PoisonMaskElem); 3082 if (isa<PoisonValue>(DstVec) && !isa<UndefValue>(SrcVec)) { 3083 SK = TargetTransformInfo::SK_PermuteSingleSrc; 3084 Mask[InsIdx] = ExtIdx; 3085 std::swap(DstVec, SrcVec); 3086 } else { 3087 SK = TargetTransformInfo::SK_PermuteTwoSrc; 3088 std::iota(Mask.begin(), Mask.end(), 0); 3089 Mask[InsIdx] = ExtIdx + NumElts; 3090 } 3091 3092 // Cost 3093 auto *Ins = cast<InsertElementInst>(&I); 3094 auto *Ext = cast<ExtractElementInst>(I.getOperand(1)); 3095 InstructionCost InsCost = 3096 TTI.getVectorInstrCost(*Ins, VecTy, CostKind, InsIdx); 3097 InstructionCost ExtCost = 3098 TTI.getVectorInstrCost(*Ext, VecTy, CostKind, ExtIdx); 3099 InstructionCost OldCost = ExtCost + InsCost; 3100 3101 // Ignore 'free' identity insertion shuffle. 3102 // TODO: getShuffleCost should return TCC_Free for Identity shuffles. 3103 InstructionCost NewCost = 0; 3104 if (!ShuffleVectorInst::isIdentityMask(Mask, NumElts)) 3105 NewCost += TTI.getShuffleCost(SK, VecTy, Mask, CostKind, 0, nullptr, 3106 {DstVec, SrcVec}); 3107 if (!Ext->hasOneUse()) 3108 NewCost += ExtCost; 3109 3110 LLVM_DEBUG(dbgs() << "Found a insert/extract shuffle-like pair: " << I 3111 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost 3112 << "\n"); 3113 3114 if (OldCost < NewCost) 3115 return false; 3116 3117 // Canonicalize undef param to RHS to help further folds. 3118 if (isa<UndefValue>(DstVec) && !isa<UndefValue>(SrcVec)) { 3119 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts); 3120 std::swap(DstVec, SrcVec); 3121 } 3122 3123 Value *Shuf = Builder.CreateShuffleVector(DstVec, SrcVec, Mask); 3124 replaceValue(I, *Shuf); 3125 3126 return true; 3127 } 3128 3129 /// This is the entry point for all transforms. Pass manager differences are 3130 /// handled in the callers of this function. 3131 bool VectorCombine::run() { 3132 if (DisableVectorCombine) 3133 return false; 3134 3135 // Don't attempt vectorization if the target does not support vectors. 3136 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true))) 3137 return false; 3138 3139 LLVM_DEBUG(dbgs() << "\n\nVECTORCOMBINE on " << F.getName() << "\n"); 3140 3141 bool MadeChange = false; 3142 auto FoldInst = [this, &MadeChange](Instruction &I) { 3143 Builder.SetInsertPoint(&I); 3144 bool IsVectorType = isa<VectorType>(I.getType()); 3145 bool IsFixedVectorType = isa<FixedVectorType>(I.getType()); 3146 auto Opcode = I.getOpcode(); 3147 3148 LLVM_DEBUG(dbgs() << "VC: Visiting: " << I << '\n'); 3149 3150 // These folds should be beneficial regardless of when this pass is run 3151 // in the optimization pipeline. 3152 // The type checking is for run-time efficiency. We can avoid wasting time 3153 // dispatching to folding functions if there's no chance of matching. 3154 if (IsFixedVectorType) { 3155 switch (Opcode) { 3156 case Instruction::InsertElement: 3157 MadeChange |= vectorizeLoadInsert(I); 3158 break; 3159 case Instruction::ShuffleVector: 3160 MadeChange |= widenSubvectorLoad(I); 3161 break; 3162 default: 3163 break; 3164 } 3165 } 3166 3167 // This transform works with scalable and fixed vectors 3168 // TODO: Identify and allow other scalable transforms 3169 if (IsVectorType) { 3170 MadeChange |= scalarizeBinopOrCmp(I); 3171 MadeChange |= scalarizeLoadExtract(I); 3172 MadeChange |= scalarizeVPIntrinsic(I); 3173 } 3174 3175 if (Opcode == Instruction::Store) 3176 MadeChange |= foldSingleElementStore(I); 3177 3178 // If this is an early pipeline invocation of this pass, we are done. 3179 if (TryEarlyFoldsOnly) 3180 return; 3181 3182 // Otherwise, try folds that improve codegen but may interfere with 3183 // early IR canonicalizations. 3184 // The type checking is for run-time efficiency. We can avoid wasting time 3185 // dispatching to folding functions if there's no chance of matching. 3186 if (IsFixedVectorType) { 3187 switch (Opcode) { 3188 case Instruction::InsertElement: 3189 MadeChange |= foldInsExtFNeg(I); 3190 MadeChange |= foldInsExtVectorToShuffle(I); 3191 break; 3192 case Instruction::ShuffleVector: 3193 MadeChange |= foldPermuteOfBinops(I); 3194 MadeChange |= foldShuffleOfBinops(I); 3195 MadeChange |= foldShuffleOfCastops(I); 3196 MadeChange |= foldShuffleOfShuffles(I); 3197 MadeChange |= foldShuffleOfIntrinsics(I); 3198 MadeChange |= foldSelectShuffle(I); 3199 MadeChange |= foldShuffleToIdentity(I); 3200 break; 3201 case Instruction::BitCast: 3202 MadeChange |= foldBitcastShuffle(I); 3203 break; 3204 default: 3205 MadeChange |= shrinkType(I); 3206 break; 3207 } 3208 } else { 3209 switch (Opcode) { 3210 case Instruction::Call: 3211 MadeChange |= foldShuffleFromReductions(I); 3212 MadeChange |= foldCastFromReductions(I); 3213 break; 3214 case Instruction::ICmp: 3215 case Instruction::FCmp: 3216 MadeChange |= foldExtractExtract(I); 3217 break; 3218 case Instruction::Or: 3219 MadeChange |= foldConcatOfBoolMasks(I); 3220 [[fallthrough]]; 3221 default: 3222 if (Instruction::isBinaryOp(Opcode)) { 3223 MadeChange |= foldExtractExtract(I); 3224 MadeChange |= foldExtractedCmps(I); 3225 } 3226 break; 3227 } 3228 } 3229 }; 3230 3231 for (BasicBlock &BB : F) { 3232 // Ignore unreachable basic blocks. 3233 if (!DT.isReachableFromEntry(&BB)) 3234 continue; 3235 // Use early increment range so that we can erase instructions in loop. 3236 for (Instruction &I : make_early_inc_range(BB)) { 3237 if (I.isDebugOrPseudoInst()) 3238 continue; 3239 FoldInst(I); 3240 } 3241 } 3242 3243 while (!Worklist.isEmpty()) { 3244 Instruction *I = Worklist.removeOne(); 3245 if (!I) 3246 continue; 3247 3248 if (isInstructionTriviallyDead(I)) { 3249 eraseInstruction(*I); 3250 continue; 3251 } 3252 3253 FoldInst(*I); 3254 } 3255 3256 return MadeChange; 3257 } 3258 3259 PreservedAnalyses VectorCombinePass::run(Function &F, 3260 FunctionAnalysisManager &FAM) { 3261 auto &AC = FAM.getResult<AssumptionAnalysis>(F); 3262 TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 3263 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 3264 AAResults &AA = FAM.getResult<AAManager>(F); 3265 const DataLayout *DL = &F.getDataLayout(); 3266 VectorCombine Combiner(F, TTI, DT, AA, AC, DL, TTI::TCK_RecipThroughput, 3267 TryEarlyFoldsOnly); 3268 if (!Combiner.run()) 3269 return PreservedAnalyses::all(); 3270 PreservedAnalyses PA; 3271 PA.preserveSet<CFGAnalyses>(); 3272 return PA; 3273 } 3274