1 //===--------------------- InterleavedAccessPass.cpp ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Interleaved Access pass, which identifies
11 // interleaved memory accesses and transforms them into target specific
12 // intrinsics.
13 //
14 // An interleaved load reads data from memory into several vectors, with
15 // DE-interleaving the data on a factor. An interleaved store writes several
16 // vectors to memory with RE-interleaving the data on a factor.
17 //
18 // As interleaved accesses are difficult to identified in CodeGen (mainly
19 // because the VECTOR_SHUFFLE DAG node is quite different from the shufflevector
20 // IR), we identify and transform them to intrinsics in this pass so the
21 // intrinsics can be easily matched into target specific instructions later in
22 // CodeGen.
23 //
24 // E.g. An interleaved load (Factor = 2):
25 //        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
26 //        %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <0, 2, 4, 6>
27 //        %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <1, 3, 5, 7>
28 //
29 // It could be transformed into a ld2 intrinsic in AArch64 backend or a vld2
30 // intrinsic in ARM backend.
31 //
32 // In X86, this can be further optimized into a set of target
33 // specific loads followed by an optimized sequence of shuffles.
34 //
35 // E.g. An interleaved store (Factor = 3):
36 //        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
37 //                                    <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
38 //        store <12 x i32> %i.vec, <12 x i32>* %ptr
39 //
40 // It could be transformed into a st3 intrinsic in AArch64 backend or a vst3
41 // intrinsic in ARM backend.
42 //
43 // Similarly, a set of interleaved stores can be transformed into an optimized
44 // sequence of shuffles followed by a set of target specific stores for X86.
45 //===----------------------------------------------------------------------===//
46 
47 #include "llvm/CodeGen/Passes.h"
48 #include "llvm/IR/Dominators.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "interleaved-access"
59 
60 static cl::opt<bool> LowerInterleavedAccesses(
61     "lower-interleaved-accesses",
62     cl::desc("Enable lowering interleaved accesses to intrinsics"),
63     cl::init(true), cl::Hidden);
64 
65 static unsigned MaxFactor; // The maximum supported interleave factor.
66 
67 namespace {
68 
69 class InterleavedAccess : public FunctionPass {
70 
71 public:
72   static char ID;
73   InterleavedAccess(const TargetMachine *TM = nullptr)
74       : FunctionPass(ID), DT(nullptr), TM(TM), TLI(nullptr) {
75     initializeInterleavedAccessPass(*PassRegistry::getPassRegistry());
76   }
77 
78   StringRef getPassName() const override { return "Interleaved Access Pass"; }
79 
80   bool runOnFunction(Function &F) override;
81 
82   void getAnalysisUsage(AnalysisUsage &AU) const override {
83     AU.addRequired<DominatorTreeWrapperPass>();
84     AU.addPreserved<DominatorTreeWrapperPass>();
85   }
86 
87 private:
88   DominatorTree *DT;
89   const TargetMachine *TM;
90   const TargetLowering *TLI;
91 
92   /// \brief Transform an interleaved load into target specific intrinsics.
93   bool lowerInterleavedLoad(LoadInst *LI,
94                             SmallVector<Instruction *, 32> &DeadInsts);
95 
96   /// \brief Transform an interleaved store into target specific intrinsics.
97   bool lowerInterleavedStore(StoreInst *SI,
98                              SmallVector<Instruction *, 32> &DeadInsts);
99 
100   /// \brief Returns true if the uses of an interleaved load by the
101   /// extractelement instructions in \p Extracts can be replaced by uses of the
102   /// shufflevector instructions in \p Shuffles instead. If so, the necessary
103   /// replacements are also performed.
104   bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts,
105                           ArrayRef<ShuffleVectorInst *> Shuffles);
106 };
107 } // end anonymous namespace.
108 
109 char InterleavedAccess::ID = 0;
110 INITIALIZE_TM_PASS_BEGIN(
111     InterleavedAccess, "interleaved-access",
112     "Lower interleaved memory accesses to target specific intrinsics", false,
113     false)
114 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
115 INITIALIZE_TM_PASS_END(
116     InterleavedAccess, "interleaved-access",
117     "Lower interleaved memory accesses to target specific intrinsics", false,
118     false)
119 
120 FunctionPass *llvm::createInterleavedAccessPass(const TargetMachine *TM) {
121   return new InterleavedAccess(TM);
122 }
123 
124 /// \brief Check if the mask is a DE-interleave mask of the given factor
125 /// \p Factor like:
126 ///     <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
127 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
128                                        unsigned &Index) {
129   // Check all potential start indices from 0 to (Factor - 1).
130   for (Index = 0; Index < Factor; Index++) {
131     unsigned i = 0;
132 
133     // Check that elements are in ascending order by Factor. Ignore undef
134     // elements.
135     for (; i < Mask.size(); i++)
136       if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor)
137         break;
138 
139     if (i == Mask.size())
140       return true;
141   }
142 
143   return false;
144 }
145 
146 /// \brief Check if the mask is a DE-interleave mask for an interleaved load.
147 ///
148 /// E.g. DE-interleave masks (Factor = 2) could be:
149 ///     <0, 2, 4, 6>    (mask of index 0 to extract even elements)
150 ///     <1, 3, 5, 7>    (mask of index 1 to extract odd elements)
151 static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
152                                unsigned &Index) {
153   if (Mask.size() < 2)
154     return false;
155 
156   // Check potential Factors.
157   for (Factor = 2; Factor <= MaxFactor; Factor++)
158     if (isDeInterleaveMaskOfFactor(Mask, Factor, Index))
159       return true;
160 
161   return false;
162 }
163 
164 /// \brief Check if the mask is RE-interleave mask for an interleaved store.
165 ///
166 /// I.e. <0, NumSubElts, ... , NumSubElts*(Factor - 1), 1, NumSubElts + 1, ...>
167 ///
168 /// E.g. The RE-interleave mask (Factor = 2) could be:
169 ///     <0, 4, 1, 5, 2, 6, 3, 7>
170 static bool isReInterleaveMask(ArrayRef<int> Mask, unsigned &Factor) {
171   unsigned NumElts = Mask.size();
172   if (NumElts < 4)
173     return false;
174 
175   // Check potential Factors.
176   for (Factor = 2; Factor <= MaxFactor; Factor++) {
177     if (NumElts % Factor)
178       continue;
179 
180     unsigned NumSubElts = NumElts / Factor;
181     if (!isPowerOf2_32(NumSubElts))
182       continue;
183 
184     // Check whether each element matchs the RE-interleaved rule. Ignore undef
185     // elements.
186     unsigned i = 0;
187     for (; i < NumElts; i++)
188       if (Mask[i] >= 0 &&
189           static_cast<unsigned>(Mask[i]) !=
190               (i % Factor) * NumSubElts + i / Factor)
191         break;
192 
193     // Find a RE-interleaved mask of current factor.
194     if (i == NumElts)
195       return true;
196   }
197 
198   return false;
199 }
200 
201 bool InterleavedAccess::lowerInterleavedLoad(
202     LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) {
203   if (!LI->isSimple())
204     return false;
205 
206   SmallVector<ShuffleVectorInst *, 4> Shuffles;
207   SmallVector<ExtractElementInst *, 4> Extracts;
208 
209   // Check if all users of this load are shufflevectors. If we encounter any
210   // users that are extractelement instructions, we save them to later check if
211   // they can be modifed to extract from one of the shufflevectors instead of
212   // the load.
213   for (auto UI = LI->user_begin(), E = LI->user_end(); UI != E; UI++) {
214     auto *Extract = dyn_cast<ExtractElementInst>(*UI);
215     if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) {
216       Extracts.push_back(Extract);
217       continue;
218     }
219     ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(*UI);
220     if (!SVI || !isa<UndefValue>(SVI->getOperand(1)))
221       return false;
222 
223     Shuffles.push_back(SVI);
224   }
225 
226   if (Shuffles.empty())
227     return false;
228 
229   unsigned Factor, Index;
230 
231   // Check if the first shufflevector is DE-interleave shuffle.
232   if (!isDeInterleaveMask(Shuffles[0]->getShuffleMask(), Factor, Index))
233     return false;
234 
235   // Holds the corresponding index for each DE-interleave shuffle.
236   SmallVector<unsigned, 4> Indices;
237   Indices.push_back(Index);
238 
239   Type *VecTy = Shuffles[0]->getType();
240 
241   // Check if other shufflevectors are also DE-interleaved of the same type
242   // and factor as the first shufflevector.
243   for (unsigned i = 1; i < Shuffles.size(); i++) {
244     if (Shuffles[i]->getType() != VecTy)
245       return false;
246 
247     if (!isDeInterleaveMaskOfFactor(Shuffles[i]->getShuffleMask(), Factor,
248                                     Index))
249       return false;
250 
251     Indices.push_back(Index);
252   }
253 
254   // Try and modify users of the load that are extractelement instructions to
255   // use the shufflevector instructions instead of the load.
256   if (!tryReplaceExtracts(Extracts, Shuffles))
257     return false;
258 
259   DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n");
260 
261   // Try to create target specific intrinsics to replace the load and shuffles.
262   if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor))
263     return false;
264 
265   for (auto SVI : Shuffles)
266     DeadInsts.push_back(SVI);
267 
268   DeadInsts.push_back(LI);
269   return true;
270 }
271 
272 bool InterleavedAccess::tryReplaceExtracts(
273     ArrayRef<ExtractElementInst *> Extracts,
274     ArrayRef<ShuffleVectorInst *> Shuffles) {
275 
276   // If there aren't any extractelement instructions to modify, there's nothing
277   // to do.
278   if (Extracts.empty())
279     return true;
280 
281   // Maps extractelement instructions to vector-index pairs. The extractlement
282   // instructions will be modified to use the new vector and index operands.
283   DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap;
284 
285   for (auto *Extract : Extracts) {
286 
287     // The vector index that is extracted.
288     auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand());
289     auto Index = IndexOperand->getSExtValue();
290 
291     // Look for a suitable shufflevector instruction. The goal is to modify the
292     // extractelement instruction (which uses an interleaved load) to use one
293     // of the shufflevector instructions instead of the load.
294     for (auto *Shuffle : Shuffles) {
295 
296       // If the shufflevector instruction doesn't dominate the extract, we
297       // can't create a use of it.
298       if (!DT->dominates(Shuffle, Extract))
299         continue;
300 
301       // Inspect the indices of the shufflevector instruction. If the shuffle
302       // selects the same index that is extracted, we can modify the
303       // extractelement instruction.
304       SmallVector<int, 4> Indices;
305       Shuffle->getShuffleMask(Indices);
306       for (unsigned I = 0; I < Indices.size(); ++I)
307         if (Indices[I] == Index) {
308           assert(Extract->getOperand(0) == Shuffle->getOperand(0) &&
309                  "Vector operations do not match");
310           ReplacementMap[Extract] = std::make_pair(Shuffle, I);
311           break;
312         }
313 
314       // If we found a suitable shufflevector instruction, stop looking.
315       if (ReplacementMap.count(Extract))
316         break;
317     }
318 
319     // If we did not find a suitable shufflevector instruction, the
320     // extractelement instruction cannot be modified, so we must give up.
321     if (!ReplacementMap.count(Extract))
322       return false;
323   }
324 
325   // Finally, perform the replacements.
326   IRBuilder<> Builder(Extracts[0]->getContext());
327   for (auto &Replacement : ReplacementMap) {
328     auto *Extract = Replacement.first;
329     auto *Vector = Replacement.second.first;
330     auto Index = Replacement.second.second;
331     Builder.SetInsertPoint(Extract);
332     Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index));
333     Extract->eraseFromParent();
334   }
335 
336   return true;
337 }
338 
339 bool InterleavedAccess::lowerInterleavedStore(
340     StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) {
341   if (!SI->isSimple())
342     return false;
343 
344   ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand());
345   if (!SVI || !SVI->hasOneUse())
346     return false;
347 
348   // Check if the shufflevector is RE-interleave shuffle.
349   unsigned Factor;
350   if (!isReInterleaveMask(SVI->getShuffleMask(), Factor))
351     return false;
352 
353   DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n");
354 
355   // Try to create target specific intrinsics to replace the store and shuffle.
356   if (!TLI->lowerInterleavedStore(SI, SVI, Factor))
357     return false;
358 
359   // Already have a new target specific interleaved store. Erase the old store.
360   DeadInsts.push_back(SI);
361   DeadInsts.push_back(SVI);
362   return true;
363 }
364 
365 bool InterleavedAccess::runOnFunction(Function &F) {
366   if (!TM || !LowerInterleavedAccesses)
367     return false;
368 
369   DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n");
370 
371   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
372   TLI = TM->getSubtargetImpl(F)->getTargetLowering();
373   MaxFactor = TLI->getMaxSupportedInterleaveFactor();
374 
375   // Holds dead instructions that will be erased later.
376   SmallVector<Instruction *, 32> DeadInsts;
377   bool Changed = false;
378 
379   for (auto &I : instructions(F)) {
380     if (LoadInst *LI = dyn_cast<LoadInst>(&I))
381       Changed |= lowerInterleavedLoad(LI, DeadInsts);
382 
383     if (StoreInst *SI = dyn_cast<StoreInst>(&I))
384       Changed |= lowerInterleavedStore(SI, DeadInsts);
385   }
386 
387   for (auto I : DeadInsts)
388     I->eraseFromParent();
389 
390   return Changed;
391 }
392