1 //===- InterleavedAccessPass.cpp ------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Interleaved Access pass, which identifies 10 // interleaved memory accesses and transforms them into target specific 11 // intrinsics. 12 // 13 // An interleaved load reads data from memory into several vectors, with 14 // DE-interleaving the data on a factor. An interleaved store writes several 15 // vectors to memory with RE-interleaving the data on a factor. 16 // 17 // As interleaved accesses are difficult to identified in CodeGen (mainly 18 // because the VECTOR_SHUFFLE DAG node is quite different from the shufflevector 19 // IR), we identify and transform them to intrinsics in this pass so the 20 // intrinsics can be easily matched into target specific instructions later in 21 // CodeGen. 22 // 23 // E.g. An interleaved load (Factor = 2): 24 // %wide.vec = load <8 x i32>, <8 x i32>* %ptr 25 // %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> poison, <0, 2, 4, 6> 26 // %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> poison, <1, 3, 5, 7> 27 // 28 // It could be transformed into a ld2 intrinsic in AArch64 backend or a vld2 29 // intrinsic in ARM backend. 30 // 31 // In X86, this can be further optimized into a set of target 32 // specific loads followed by an optimized sequence of shuffles. 33 // 34 // E.g. An interleaved store (Factor = 3): 35 // %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 36 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 37 // store <12 x i32> %i.vec, <12 x i32>* %ptr 38 // 39 // It could be transformed into a st3 intrinsic in AArch64 backend or a vst3 40 // intrinsic in ARM backend. 41 // 42 // Similarly, a set of interleaved stores can be transformed into an optimized 43 // sequence of shuffles followed by a set of target specific stores for X86. 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/DenseMap.h" 49 #include "llvm/ADT/SetVector.h" 50 #include "llvm/ADT/SmallVector.h" 51 #include "llvm/CodeGen/InterleavedAccess.h" 52 #include "llvm/CodeGen/TargetLowering.h" 53 #include "llvm/CodeGen/TargetPassConfig.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/Function.h" 58 #include "llvm/IR/IRBuilder.h" 59 #include "llvm/IR/InstIterator.h" 60 #include "llvm/IR/Instruction.h" 61 #include "llvm/IR/Instructions.h" 62 #include "llvm/IR/IntrinsicInst.h" 63 #include "llvm/InitializePasses.h" 64 #include "llvm/Pass.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 #include <cassert> 72 #include <utility> 73 74 using namespace llvm; 75 76 #define DEBUG_TYPE "interleaved-access" 77 78 static cl::opt<bool> LowerInterleavedAccesses( 79 "lower-interleaved-accesses", 80 cl::desc("Enable lowering interleaved accesses to intrinsics"), 81 cl::init(true), cl::Hidden); 82 83 namespace { 84 85 class InterleavedAccessImpl { 86 friend class InterleavedAccess; 87 88 public: 89 InterleavedAccessImpl() = default; 90 InterleavedAccessImpl(DominatorTree *DT, const TargetLowering *TLI) 91 : DT(DT), TLI(TLI), MaxFactor(TLI->getMaxSupportedInterleaveFactor()) {} 92 bool runOnFunction(Function &F); 93 94 private: 95 DominatorTree *DT = nullptr; 96 const TargetLowering *TLI = nullptr; 97 98 /// The maximum supported interleave factor. 99 unsigned MaxFactor = 0u; 100 101 /// Transform an interleaved load into target specific intrinsics. 102 bool lowerInterleavedLoad(LoadInst *LI, 103 SmallSetVector<Instruction *, 32> &DeadInsts); 104 105 /// Transform an interleaved store into target specific intrinsics. 106 bool lowerInterleavedStore(StoreInst *SI, 107 SmallSetVector<Instruction *, 32> &DeadInsts); 108 109 /// Transform a load and a deinterleave intrinsic into target specific 110 /// instructions. 111 bool lowerDeinterleaveIntrinsic(IntrinsicInst *II, 112 SmallSetVector<Instruction *, 32> &DeadInsts); 113 114 /// Transform an interleave intrinsic and a store into target specific 115 /// instructions. 116 bool lowerInterleaveIntrinsic(IntrinsicInst *II, 117 SmallSetVector<Instruction *, 32> &DeadInsts); 118 119 /// Returns true if the uses of an interleaved load by the 120 /// extractelement instructions in \p Extracts can be replaced by uses of the 121 /// shufflevector instructions in \p Shuffles instead. If so, the necessary 122 /// replacements are also performed. 123 bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts, 124 ArrayRef<ShuffleVectorInst *> Shuffles); 125 126 /// Given a number of shuffles of the form shuffle(binop(x,y)), convert them 127 /// to binop(shuffle(x), shuffle(y)) to allow the formation of an 128 /// interleaving load. Any newly created shuffles that operate on \p LI will 129 /// be added to \p Shuffles. Returns true, if any changes to the IR have been 130 /// made. 131 bool replaceBinOpShuffles(ArrayRef<ShuffleVectorInst *> BinOpShuffles, 132 SmallVectorImpl<ShuffleVectorInst *> &Shuffles, 133 LoadInst *LI); 134 }; 135 136 class InterleavedAccess : public FunctionPass { 137 InterleavedAccessImpl Impl; 138 139 public: 140 static char ID; 141 142 InterleavedAccess() : FunctionPass(ID) { 143 initializeInterleavedAccessPass(*PassRegistry::getPassRegistry()); 144 } 145 146 StringRef getPassName() const override { return "Interleaved Access Pass"; } 147 148 bool runOnFunction(Function &F) override; 149 150 void getAnalysisUsage(AnalysisUsage &AU) const override { 151 AU.addRequired<DominatorTreeWrapperPass>(); 152 AU.setPreservesCFG(); 153 } 154 }; 155 156 } // end anonymous namespace. 157 158 PreservedAnalyses InterleavedAccessPass::run(Function &F, 159 FunctionAnalysisManager &FAM) { 160 auto *DT = &FAM.getResult<DominatorTreeAnalysis>(F); 161 auto *TLI = TM->getSubtargetImpl(F)->getTargetLowering(); 162 InterleavedAccessImpl Impl(DT, TLI); 163 bool Changed = Impl.runOnFunction(F); 164 165 if (!Changed) 166 return PreservedAnalyses::all(); 167 168 PreservedAnalyses PA; 169 PA.preserveSet<CFGAnalyses>(); 170 return PA; 171 } 172 173 char InterleavedAccess::ID = 0; 174 175 bool InterleavedAccess::runOnFunction(Function &F) { 176 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 177 if (!TPC || !LowerInterleavedAccesses) 178 return false; 179 180 LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n"); 181 182 Impl.DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 183 auto &TM = TPC->getTM<TargetMachine>(); 184 Impl.TLI = TM.getSubtargetImpl(F)->getTargetLowering(); 185 Impl.MaxFactor = Impl.TLI->getMaxSupportedInterleaveFactor(); 186 187 return Impl.runOnFunction(F); 188 } 189 190 INITIALIZE_PASS_BEGIN(InterleavedAccess, DEBUG_TYPE, 191 "Lower interleaved memory accesses to target specific intrinsics", false, 192 false) 193 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 194 INITIALIZE_PASS_END(InterleavedAccess, DEBUG_TYPE, 195 "Lower interleaved memory accesses to target specific intrinsics", false, 196 false) 197 198 FunctionPass *llvm::createInterleavedAccessPass() { 199 return new InterleavedAccess(); 200 } 201 202 /// Check if the mask is a DE-interleave mask for an interleaved load. 203 /// 204 /// E.g. DE-interleave masks (Factor = 2) could be: 205 /// <0, 2, 4, 6> (mask of index 0 to extract even elements) 206 /// <1, 3, 5, 7> (mask of index 1 to extract odd elements) 207 static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor, 208 unsigned &Index, unsigned MaxFactor, 209 unsigned NumLoadElements) { 210 if (Mask.size() < 2) 211 return false; 212 213 // Check potential Factors. 214 for (Factor = 2; Factor <= MaxFactor; Factor++) { 215 // Make sure we don't produce a load wider than the input load. 216 if (Mask.size() * Factor > NumLoadElements) 217 return false; 218 if (ShuffleVectorInst::isDeInterleaveMaskOfFactor(Mask, Factor, Index)) 219 return true; 220 } 221 222 return false; 223 } 224 225 /// Check if the mask can be used in an interleaved store. 226 // 227 /// It checks for a more general pattern than the RE-interleave mask. 228 /// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...> 229 /// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35> 230 /// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 231 /// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5> 232 /// 233 /// The particular case of an RE-interleave mask is: 234 /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...> 235 /// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7> 236 static bool isReInterleaveMask(ShuffleVectorInst *SVI, unsigned &Factor, 237 unsigned MaxFactor) { 238 unsigned NumElts = SVI->getShuffleMask().size(); 239 if (NumElts < 4) 240 return false; 241 242 // Check potential Factors. 243 for (Factor = 2; Factor <= MaxFactor; Factor++) { 244 if (SVI->isInterleave(Factor)) 245 return true; 246 } 247 248 return false; 249 } 250 251 bool InterleavedAccessImpl::lowerInterleavedLoad( 252 LoadInst *LI, SmallSetVector<Instruction *, 32> &DeadInsts) { 253 if (!LI->isSimple() || isa<ScalableVectorType>(LI->getType())) 254 return false; 255 256 // Check if all users of this load are shufflevectors. If we encounter any 257 // users that are extractelement instructions or binary operators, we save 258 // them to later check if they can be modified to extract from one of the 259 // shufflevectors instead of the load. 260 261 SmallVector<ShuffleVectorInst *, 4> Shuffles; 262 SmallVector<ExtractElementInst *, 4> Extracts; 263 // BinOpShuffles need to be handled a single time in case both operands of the 264 // binop are the same load. 265 SmallSetVector<ShuffleVectorInst *, 4> BinOpShuffles; 266 267 for (auto *User : LI->users()) { 268 auto *Extract = dyn_cast<ExtractElementInst>(User); 269 if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) { 270 Extracts.push_back(Extract); 271 continue; 272 } 273 if (auto *BI = dyn_cast<BinaryOperator>(User)) { 274 if (!BI->user_empty() && all_of(BI->users(), [](auto *U) { 275 auto *SVI = dyn_cast<ShuffleVectorInst>(U); 276 return SVI && isa<UndefValue>(SVI->getOperand(1)); 277 })) { 278 for (auto *SVI : BI->users()) 279 BinOpShuffles.insert(cast<ShuffleVectorInst>(SVI)); 280 continue; 281 } 282 } 283 auto *SVI = dyn_cast<ShuffleVectorInst>(User); 284 if (!SVI || !isa<UndefValue>(SVI->getOperand(1))) 285 return false; 286 287 Shuffles.push_back(SVI); 288 } 289 290 if (Shuffles.empty() && BinOpShuffles.empty()) 291 return false; 292 293 unsigned Factor, Index; 294 295 unsigned NumLoadElements = 296 cast<FixedVectorType>(LI->getType())->getNumElements(); 297 auto *FirstSVI = Shuffles.size() > 0 ? Shuffles[0] : BinOpShuffles[0]; 298 // Check if the first shufflevector is DE-interleave shuffle. 299 if (!isDeInterleaveMask(FirstSVI->getShuffleMask(), Factor, Index, MaxFactor, 300 NumLoadElements)) 301 return false; 302 303 // Holds the corresponding index for each DE-interleave shuffle. 304 SmallVector<unsigned, 4> Indices; 305 306 Type *VecTy = FirstSVI->getType(); 307 308 // Check if other shufflevectors are also DE-interleaved of the same type 309 // and factor as the first shufflevector. 310 for (auto *Shuffle : Shuffles) { 311 if (Shuffle->getType() != VecTy) 312 return false; 313 if (!ShuffleVectorInst::isDeInterleaveMaskOfFactor( 314 Shuffle->getShuffleMask(), Factor, Index)) 315 return false; 316 317 assert(Shuffle->getShuffleMask().size() <= NumLoadElements); 318 Indices.push_back(Index); 319 } 320 for (auto *Shuffle : BinOpShuffles) { 321 if (Shuffle->getType() != VecTy) 322 return false; 323 if (!ShuffleVectorInst::isDeInterleaveMaskOfFactor( 324 Shuffle->getShuffleMask(), Factor, Index)) 325 return false; 326 327 assert(Shuffle->getShuffleMask().size() <= NumLoadElements); 328 329 if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(0) == LI) 330 Indices.push_back(Index); 331 if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(1) == LI) 332 Indices.push_back(Index); 333 } 334 335 // Try and modify users of the load that are extractelement instructions to 336 // use the shufflevector instructions instead of the load. 337 if (!tryReplaceExtracts(Extracts, Shuffles)) 338 return false; 339 340 bool BinOpShuffleChanged = 341 replaceBinOpShuffles(BinOpShuffles.getArrayRef(), Shuffles, LI); 342 343 LLVM_DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n"); 344 345 // Try to create target specific intrinsics to replace the load and shuffles. 346 if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor)) { 347 // If Extracts is not empty, tryReplaceExtracts made changes earlier. 348 return !Extracts.empty() || BinOpShuffleChanged; 349 } 350 351 DeadInsts.insert(Shuffles.begin(), Shuffles.end()); 352 353 DeadInsts.insert(LI); 354 return true; 355 } 356 357 bool InterleavedAccessImpl::replaceBinOpShuffles( 358 ArrayRef<ShuffleVectorInst *> BinOpShuffles, 359 SmallVectorImpl<ShuffleVectorInst *> &Shuffles, LoadInst *LI) { 360 for (auto *SVI : BinOpShuffles) { 361 BinaryOperator *BI = cast<BinaryOperator>(SVI->getOperand(0)); 362 Type *BIOp0Ty = BI->getOperand(0)->getType(); 363 ArrayRef<int> Mask = SVI->getShuffleMask(); 364 assert(all_of(Mask, [&](int Idx) { 365 return Idx < (int)cast<FixedVectorType>(BIOp0Ty)->getNumElements(); 366 })); 367 368 BasicBlock::iterator insertPos = SVI->getIterator(); 369 auto *NewSVI1 = 370 new ShuffleVectorInst(BI->getOperand(0), PoisonValue::get(BIOp0Ty), 371 Mask, SVI->getName(), insertPos); 372 auto *NewSVI2 = new ShuffleVectorInst( 373 BI->getOperand(1), PoisonValue::get(BI->getOperand(1)->getType()), Mask, 374 SVI->getName(), insertPos); 375 BinaryOperator *NewBI = BinaryOperator::CreateWithCopiedFlags( 376 BI->getOpcode(), NewSVI1, NewSVI2, BI, BI->getName(), insertPos); 377 SVI->replaceAllUsesWith(NewBI); 378 LLVM_DEBUG(dbgs() << " Replaced: " << *BI << "\n And : " << *SVI 379 << "\n With : " << *NewSVI1 << "\n And : " 380 << *NewSVI2 << "\n And : " << *NewBI << "\n"); 381 RecursivelyDeleteTriviallyDeadInstructions(SVI); 382 if (NewSVI1->getOperand(0) == LI) 383 Shuffles.push_back(NewSVI1); 384 if (NewSVI2->getOperand(0) == LI) 385 Shuffles.push_back(NewSVI2); 386 } 387 388 return !BinOpShuffles.empty(); 389 } 390 391 bool InterleavedAccessImpl::tryReplaceExtracts( 392 ArrayRef<ExtractElementInst *> Extracts, 393 ArrayRef<ShuffleVectorInst *> Shuffles) { 394 // If there aren't any extractelement instructions to modify, there's nothing 395 // to do. 396 if (Extracts.empty()) 397 return true; 398 399 // Maps extractelement instructions to vector-index pairs. The extractlement 400 // instructions will be modified to use the new vector and index operands. 401 DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap; 402 403 for (auto *Extract : Extracts) { 404 // The vector index that is extracted. 405 auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand()); 406 auto Index = IndexOperand->getSExtValue(); 407 408 // Look for a suitable shufflevector instruction. The goal is to modify the 409 // extractelement instruction (which uses an interleaved load) to use one 410 // of the shufflevector instructions instead of the load. 411 for (auto *Shuffle : Shuffles) { 412 // If the shufflevector instruction doesn't dominate the extract, we 413 // can't create a use of it. 414 if (!DT->dominates(Shuffle, Extract)) 415 continue; 416 417 // Inspect the indices of the shufflevector instruction. If the shuffle 418 // selects the same index that is extracted, we can modify the 419 // extractelement instruction. 420 SmallVector<int, 4> Indices; 421 Shuffle->getShuffleMask(Indices); 422 for (unsigned I = 0; I < Indices.size(); ++I) 423 if (Indices[I] == Index) { 424 assert(Extract->getOperand(0) == Shuffle->getOperand(0) && 425 "Vector operations do not match"); 426 ReplacementMap[Extract] = std::make_pair(Shuffle, I); 427 break; 428 } 429 430 // If we found a suitable shufflevector instruction, stop looking. 431 if (ReplacementMap.count(Extract)) 432 break; 433 } 434 435 // If we did not find a suitable shufflevector instruction, the 436 // extractelement instruction cannot be modified, so we must give up. 437 if (!ReplacementMap.count(Extract)) 438 return false; 439 } 440 441 // Finally, perform the replacements. 442 IRBuilder<> Builder(Extracts[0]->getContext()); 443 for (auto &Replacement : ReplacementMap) { 444 auto *Extract = Replacement.first; 445 auto *Vector = Replacement.second.first; 446 auto Index = Replacement.second.second; 447 Builder.SetInsertPoint(Extract); 448 Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index)); 449 Extract->eraseFromParent(); 450 } 451 452 return true; 453 } 454 455 bool InterleavedAccessImpl::lowerInterleavedStore( 456 StoreInst *SI, SmallSetVector<Instruction *, 32> &DeadInsts) { 457 if (!SI->isSimple()) 458 return false; 459 460 auto *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand()); 461 if (!SVI || !SVI->hasOneUse() || isa<ScalableVectorType>(SVI->getType())) 462 return false; 463 464 // Check if the shufflevector is RE-interleave shuffle. 465 unsigned Factor; 466 if (!isReInterleaveMask(SVI, Factor, MaxFactor)) 467 return false; 468 469 LLVM_DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n"); 470 471 // Try to create target specific intrinsics to replace the store and shuffle. 472 if (!TLI->lowerInterleavedStore(SI, SVI, Factor)) 473 return false; 474 475 // Already have a new target specific interleaved store. Erase the old store. 476 DeadInsts.insert(SI); 477 DeadInsts.insert(SVI); 478 return true; 479 } 480 481 bool InterleavedAccessImpl::lowerDeinterleaveIntrinsic( 482 IntrinsicInst *DI, SmallSetVector<Instruction *, 32> &DeadInsts) { 483 LoadInst *LI = dyn_cast<LoadInst>(DI->getOperand(0)); 484 485 if (!LI || !LI->hasOneUse() || !LI->isSimple()) 486 return false; 487 488 LLVM_DEBUG(dbgs() << "IA: Found a deinterleave intrinsic: " << *DI << "\n"); 489 490 // Try and match this with target specific intrinsics. 491 SmallVector<Instruction *, 4> DeinterleaveDeadInsts; 492 if (!TLI->lowerDeinterleaveIntrinsicToLoad(DI, LI, DeinterleaveDeadInsts)) 493 return false; 494 495 DeadInsts.insert(DeinterleaveDeadInsts.begin(), DeinterleaveDeadInsts.end()); 496 // We now have a target-specific load, so delete the old one. 497 DeadInsts.insert(DI); 498 DeadInsts.insert(LI); 499 return true; 500 } 501 502 bool InterleavedAccessImpl::lowerInterleaveIntrinsic( 503 IntrinsicInst *II, SmallSetVector<Instruction *, 32> &DeadInsts) { 504 if (!II->hasOneUse()) 505 return false; 506 507 StoreInst *SI = dyn_cast<StoreInst>(*(II->users().begin())); 508 509 if (!SI || !SI->isSimple()) 510 return false; 511 512 LLVM_DEBUG(dbgs() << "IA: Found an interleave intrinsic: " << *II << "\n"); 513 514 SmallVector<Instruction *, 4> InterleaveDeadInsts; 515 // Try and match this with target specific intrinsics. 516 if (!TLI->lowerInterleaveIntrinsicToStore(II, SI, InterleaveDeadInsts)) 517 return false; 518 519 // We now have a target-specific store, so delete the old one. 520 DeadInsts.insert(SI); 521 DeadInsts.insert(II); 522 DeadInsts.insert(InterleaveDeadInsts.begin(), InterleaveDeadInsts.end()); 523 return true; 524 } 525 526 bool InterleavedAccessImpl::runOnFunction(Function &F) { 527 // Holds dead instructions that will be erased later. 528 SmallSetVector<Instruction *, 32> DeadInsts; 529 bool Changed = false; 530 531 for (auto &I : instructions(F)) { 532 if (auto *LI = dyn_cast<LoadInst>(&I)) 533 Changed |= lowerInterleavedLoad(LI, DeadInsts); 534 535 if (auto *SI = dyn_cast<StoreInst>(&I)) 536 Changed |= lowerInterleavedStore(SI, DeadInsts); 537 538 if (auto *II = dyn_cast<IntrinsicInst>(&I)) { 539 // At present, we only have intrinsics to represent (de)interleaving 540 // with a factor of 2. 541 if (II->getIntrinsicID() == Intrinsic::vector_deinterleave2) 542 Changed |= lowerDeinterleaveIntrinsic(II, DeadInsts); 543 else if (II->getIntrinsicID() == Intrinsic::vector_interleave2) 544 Changed |= lowerInterleaveIntrinsic(II, DeadInsts); 545 } 546 } 547 548 for (auto *I : DeadInsts) 549 I->eraseFromParent(); 550 551 return Changed; 552 } 553