xref: /llvm-project/llvm/lib/CodeGen/InterleavedAccessPass.cpp (revision a9d9616c0de3f07654ee139bead48b8d78f44e1f)
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/TargetLowering.h"
52 #include "llvm/CodeGen/TargetPassConfig.h"
53 #include "llvm/CodeGen/TargetSubtargetInfo.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/InstIterator.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/InitializePasses.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Transforms/Utils/Local.h"
70 #include <cassert>
71 #include <utility>
72 
73 using namespace llvm;
74 
75 #define DEBUG_TYPE "interleaved-access"
76 
77 static cl::opt<bool> LowerInterleavedAccesses(
78     "lower-interleaved-accesses",
79     cl::desc("Enable lowering interleaved accesses to intrinsics"),
80     cl::init(true), cl::Hidden);
81 
82 namespace {
83 
84 class InterleavedAccess : public FunctionPass {
85 public:
86   static char ID;
87 
88   InterleavedAccess() : FunctionPass(ID) {
89     initializeInterleavedAccessPass(*PassRegistry::getPassRegistry());
90   }
91 
92   StringRef getPassName() const override { return "Interleaved Access Pass"; }
93 
94   bool runOnFunction(Function &F) override;
95 
96   void getAnalysisUsage(AnalysisUsage &AU) const override {
97     AU.addRequired<DominatorTreeWrapperPass>();
98     AU.setPreservesCFG();
99   }
100 
101 private:
102   DominatorTree *DT = nullptr;
103   const TargetLowering *TLI = nullptr;
104 
105   /// The maximum supported interleave factor.
106   unsigned MaxFactor;
107 
108   /// Transform an interleaved load into target specific intrinsics.
109   bool lowerInterleavedLoad(LoadInst *LI,
110                             SmallVector<Instruction *, 32> &DeadInsts);
111 
112   /// Transform an interleaved store into target specific intrinsics.
113   bool lowerInterleavedStore(StoreInst *SI,
114                              SmallVector<Instruction *, 32> &DeadInsts);
115 
116   /// Returns true if the uses of an interleaved load by the
117   /// extractelement instructions in \p Extracts can be replaced by uses of the
118   /// shufflevector instructions in \p Shuffles instead. If so, the necessary
119   /// replacements are also performed.
120   bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts,
121                           ArrayRef<ShuffleVectorInst *> Shuffles);
122 
123   /// Given a number of shuffles of the form shuffle(binop(x,y)), convert them
124   /// to binop(shuffle(x), shuffle(y)) to allow the formation of an
125   /// interleaving load. Any newly created shuffles that operate on \p LI will
126   /// be added to \p Shuffles. Returns true, if any changes to the IR have been
127   /// made.
128   bool replaceBinOpShuffles(ArrayRef<ShuffleVectorInst *> BinOpShuffles,
129                             SmallVectorImpl<ShuffleVectorInst *> &Shuffles,
130                             LoadInst *LI);
131 };
132 
133 } // end anonymous namespace.
134 
135 char InterleavedAccess::ID = 0;
136 
137 INITIALIZE_PASS_BEGIN(InterleavedAccess, DEBUG_TYPE,
138     "Lower interleaved memory accesses to target specific intrinsics", false,
139     false)
140 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
141 INITIALIZE_PASS_END(InterleavedAccess, DEBUG_TYPE,
142     "Lower interleaved memory accesses to target specific intrinsics", false,
143     false)
144 
145 FunctionPass *llvm::createInterleavedAccessPass() {
146   return new InterleavedAccess();
147 }
148 
149 /// Check if the mask is a DE-interleave mask of the given factor
150 /// \p Factor like:
151 ///     <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
152 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
153                                        unsigned &Index) {
154   // Check all potential start indices from 0 to (Factor - 1).
155   for (Index = 0; Index < Factor; Index++) {
156     unsigned i = 0;
157 
158     // Check that elements are in ascending order by Factor. Ignore undef
159     // elements.
160     for (; i < Mask.size(); i++)
161       if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor)
162         break;
163 
164     if (i == Mask.size())
165       return true;
166   }
167 
168   return false;
169 }
170 
171 /// Check if the mask is a DE-interleave mask for an interleaved load.
172 ///
173 /// E.g. DE-interleave masks (Factor = 2) could be:
174 ///     <0, 2, 4, 6>    (mask of index 0 to extract even elements)
175 ///     <1, 3, 5, 7>    (mask of index 1 to extract odd elements)
176 static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
177                                unsigned &Index, unsigned MaxFactor,
178                                unsigned NumLoadElements) {
179   if (Mask.size() < 2)
180     return false;
181 
182   // Check potential Factors.
183   for (Factor = 2; Factor <= MaxFactor; Factor++) {
184     // Make sure we don't produce a load wider than the input load.
185     if (Mask.size() * Factor > NumLoadElements)
186       return false;
187     if (isDeInterleaveMaskOfFactor(Mask, Factor, Index))
188       return true;
189   }
190 
191   return false;
192 }
193 
194 /// Check if the mask can be used in an interleaved store.
195 //
196 /// It checks for a more general pattern than the RE-interleave mask.
197 /// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...>
198 /// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35>
199 /// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
200 /// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5>
201 ///
202 /// The particular case of an RE-interleave mask is:
203 /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...>
204 /// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7>
205 static bool isReInterleaveMask(ShuffleVectorInst *SVI, unsigned &Factor,
206                                unsigned MaxFactor) {
207   unsigned NumElts = SVI->getShuffleMask().size();
208   if (NumElts < 4)
209     return false;
210 
211   // Check potential Factors.
212   for (Factor = 2; Factor <= MaxFactor; Factor++) {
213     if (SVI->isInterleave(Factor))
214       return true;
215   }
216 
217   return false;
218 }
219 
220 bool InterleavedAccess::lowerInterleavedLoad(
221     LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) {
222   if (!LI->isSimple() || isa<ScalableVectorType>(LI->getType()))
223     return false;
224 
225   // Check if all users of this load are shufflevectors. If we encounter any
226   // users that are extractelement instructions or binary operators, we save
227   // them to later check if they can be modified to extract from one of the
228   // shufflevectors instead of the load.
229 
230   SmallVector<ShuffleVectorInst *, 4> Shuffles;
231   SmallVector<ExtractElementInst *, 4> Extracts;
232   // BinOpShuffles need to be handled a single time in case both operands of the
233   // binop are the same load.
234   SmallSetVector<ShuffleVectorInst *, 4> BinOpShuffles;
235 
236   for (auto *User : LI->users()) {
237     auto *Extract = dyn_cast<ExtractElementInst>(User);
238     if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) {
239       Extracts.push_back(Extract);
240       continue;
241     }
242     if (auto *BI = dyn_cast<BinaryOperator>(User)) {
243       if (all_of(BI->users(),
244                  [](auto *U) { return isa<ShuffleVectorInst>(U); })) {
245         for (auto *SVI : BI->users())
246           BinOpShuffles.insert(cast<ShuffleVectorInst>(SVI));
247         continue;
248       }
249     }
250     auto *SVI = dyn_cast<ShuffleVectorInst>(User);
251     if (!SVI || !isa<UndefValue>(SVI->getOperand(1)))
252       return false;
253 
254     Shuffles.push_back(SVI);
255   }
256 
257   if (Shuffles.empty() && BinOpShuffles.empty())
258     return false;
259 
260   unsigned Factor, Index;
261 
262   unsigned NumLoadElements =
263       cast<FixedVectorType>(LI->getType())->getNumElements();
264   auto *FirstSVI = Shuffles.size() > 0 ? Shuffles[0] : BinOpShuffles[0];
265   // Check if the first shufflevector is DE-interleave shuffle.
266   if (!isDeInterleaveMask(FirstSVI->getShuffleMask(), Factor, Index, MaxFactor,
267                           NumLoadElements))
268     return false;
269 
270   // Holds the corresponding index for each DE-interleave shuffle.
271   SmallVector<unsigned, 4> Indices;
272 
273   Type *VecTy = FirstSVI->getType();
274 
275   // Check if other shufflevectors are also DE-interleaved of the same type
276   // and factor as the first shufflevector.
277   for (auto *Shuffle : Shuffles) {
278     if (Shuffle->getType() != VecTy)
279       return false;
280     if (!isDeInterleaveMaskOfFactor(Shuffle->getShuffleMask(), Factor,
281                                     Index))
282       return false;
283 
284     assert(Shuffle->getShuffleMask().size() <= NumLoadElements);
285     Indices.push_back(Index);
286   }
287   for (auto *Shuffle : BinOpShuffles) {
288     if (Shuffle->getType() != VecTy)
289       return false;
290     if (!isDeInterleaveMaskOfFactor(Shuffle->getShuffleMask(), Factor,
291                                     Index))
292       return false;
293 
294     assert(Shuffle->getShuffleMask().size() <= NumLoadElements);
295 
296     if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(0) == LI)
297       Indices.push_back(Index);
298     if (cast<Instruction>(Shuffle->getOperand(0))->getOperand(1) == LI)
299       Indices.push_back(Index);
300   }
301 
302   // Try and modify users of the load that are extractelement instructions to
303   // use the shufflevector instructions instead of the load.
304   if (!tryReplaceExtracts(Extracts, Shuffles))
305     return false;
306 
307   bool BinOpShuffleChanged =
308       replaceBinOpShuffles(BinOpShuffles.getArrayRef(), Shuffles, LI);
309 
310   LLVM_DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n");
311 
312   // Try to create target specific intrinsics to replace the load and shuffles.
313   if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor)) {
314     // If Extracts is not empty, tryReplaceExtracts made changes earlier.
315     return !Extracts.empty() || BinOpShuffleChanged;
316   }
317 
318   append_range(DeadInsts, Shuffles);
319 
320   DeadInsts.push_back(LI);
321   return true;
322 }
323 
324 bool InterleavedAccess::replaceBinOpShuffles(
325     ArrayRef<ShuffleVectorInst *> BinOpShuffles,
326     SmallVectorImpl<ShuffleVectorInst *> &Shuffles, LoadInst *LI) {
327   for (auto *SVI : BinOpShuffles) {
328     BinaryOperator *BI = cast<BinaryOperator>(SVI->getOperand(0));
329     Type *BIOp0Ty = BI->getOperand(0)->getType();
330     ArrayRef<int> Mask = SVI->getShuffleMask();
331     assert(all_of(Mask, [&](int Idx) {
332       return Idx < (int)cast<FixedVectorType>(BIOp0Ty)->getNumElements();
333     }));
334 
335     auto *NewSVI1 =
336         new ShuffleVectorInst(BI->getOperand(0), PoisonValue::get(BIOp0Ty),
337                               Mask, SVI->getName(), SVI);
338     auto *NewSVI2 = new ShuffleVectorInst(
339         BI->getOperand(1), PoisonValue::get(BI->getOperand(1)->getType()), Mask,
340         SVI->getName(), SVI);
341     BinaryOperator *NewBI = BinaryOperator::CreateWithCopiedFlags(
342         BI->getOpcode(), NewSVI1, NewSVI2, BI, BI->getName(), SVI);
343     SVI->replaceAllUsesWith(NewBI);
344     LLVM_DEBUG(dbgs() << "  Replaced: " << *BI << "\n    And   : " << *SVI
345                       << "\n  With    : " << *NewSVI1 << "\n    And   : "
346                       << *NewSVI2 << "\n    And   : " << *NewBI << "\n");
347     RecursivelyDeleteTriviallyDeadInstructions(SVI);
348     if (NewSVI1->getOperand(0) == LI)
349       Shuffles.push_back(NewSVI1);
350     if (NewSVI2->getOperand(0) == LI)
351       Shuffles.push_back(NewSVI2);
352   }
353 
354   return !BinOpShuffles.empty();
355 }
356 
357 bool InterleavedAccess::tryReplaceExtracts(
358     ArrayRef<ExtractElementInst *> Extracts,
359     ArrayRef<ShuffleVectorInst *> Shuffles) {
360   // If there aren't any extractelement instructions to modify, there's nothing
361   // to do.
362   if (Extracts.empty())
363     return true;
364 
365   // Maps extractelement instructions to vector-index pairs. The extractlement
366   // instructions will be modified to use the new vector and index operands.
367   DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap;
368 
369   for (auto *Extract : Extracts) {
370     // The vector index that is extracted.
371     auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand());
372     auto Index = IndexOperand->getSExtValue();
373 
374     // Look for a suitable shufflevector instruction. The goal is to modify the
375     // extractelement instruction (which uses an interleaved load) to use one
376     // of the shufflevector instructions instead of the load.
377     for (auto *Shuffle : Shuffles) {
378       // If the shufflevector instruction doesn't dominate the extract, we
379       // can't create a use of it.
380       if (!DT->dominates(Shuffle, Extract))
381         continue;
382 
383       // Inspect the indices of the shufflevector instruction. If the shuffle
384       // selects the same index that is extracted, we can modify the
385       // extractelement instruction.
386       SmallVector<int, 4> Indices;
387       Shuffle->getShuffleMask(Indices);
388       for (unsigned I = 0; I < Indices.size(); ++I)
389         if (Indices[I] == Index) {
390           assert(Extract->getOperand(0) == Shuffle->getOperand(0) &&
391                  "Vector operations do not match");
392           ReplacementMap[Extract] = std::make_pair(Shuffle, I);
393           break;
394         }
395 
396       // If we found a suitable shufflevector instruction, stop looking.
397       if (ReplacementMap.count(Extract))
398         break;
399     }
400 
401     // If we did not find a suitable shufflevector instruction, the
402     // extractelement instruction cannot be modified, so we must give up.
403     if (!ReplacementMap.count(Extract))
404       return false;
405   }
406 
407   // Finally, perform the replacements.
408   IRBuilder<> Builder(Extracts[0]->getContext());
409   for (auto &Replacement : ReplacementMap) {
410     auto *Extract = Replacement.first;
411     auto *Vector = Replacement.second.first;
412     auto Index = Replacement.second.second;
413     Builder.SetInsertPoint(Extract);
414     Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index));
415     Extract->eraseFromParent();
416   }
417 
418   return true;
419 }
420 
421 bool InterleavedAccess::lowerInterleavedStore(
422     StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) {
423   if (!SI->isSimple())
424     return false;
425 
426   auto *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand());
427   if (!SVI || !SVI->hasOneUse() || isa<ScalableVectorType>(SVI->getType()))
428     return false;
429 
430   // Check if the shufflevector is RE-interleave shuffle.
431   unsigned Factor;
432   if (!isReInterleaveMask(SVI, Factor, MaxFactor))
433     return false;
434 
435   LLVM_DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n");
436 
437   // Try to create target specific intrinsics to replace the store and shuffle.
438   if (!TLI->lowerInterleavedStore(SI, SVI, Factor))
439     return false;
440 
441   // Already have a new target specific interleaved store. Erase the old store.
442   DeadInsts.push_back(SI);
443   DeadInsts.push_back(SVI);
444   return true;
445 }
446 
447 bool InterleavedAccess::runOnFunction(Function &F) {
448   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
449   if (!TPC || !LowerInterleavedAccesses)
450     return false;
451 
452   LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n");
453 
454   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
455   auto &TM = TPC->getTM<TargetMachine>();
456   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
457   MaxFactor = TLI->getMaxSupportedInterleaveFactor();
458 
459   // Holds dead instructions that will be erased later.
460   SmallVector<Instruction *, 32> DeadInsts;
461   bool Changed = false;
462 
463   for (auto &I : instructions(F)) {
464     if (auto *LI = dyn_cast<LoadInst>(&I))
465       Changed |= lowerInterleavedLoad(LI, DeadInsts);
466 
467     if (auto *SI = dyn_cast<StoreInst>(&I))
468       Changed |= lowerInterleavedStore(SI, DeadInsts);
469   }
470 
471   for (auto *I : DeadInsts)
472     I->eraseFromParent();
473 
474   return Changed;
475 }
476