blob: ec35b3f6449e168f319922b99b4d19ac428a17b1 [file] [log] [blame]
Chad Rosiera306eeb2016-05-02 14:32:17 +00001//===--------------------- InterleavedAccessPass.cpp ----------------------===//
Hao Liu1c1e0c92015-06-26 02:10:27 +00002//
Chad Rosiera306eeb2016-05-02 14:32:17 +00003// The LLVM Compiler Infrastructure
Hao Liu1c1e0c92015-06-26 02:10:27 +00004//
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
Chad Rosiera306eeb2016-05-02 14:32:17 +000011// interleaved memory accesses and transforms them into target specific
12// intrinsics.
Hao Liu1c1e0c92015-06-26 02:10:27 +000013//
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//
Chad Rosiera306eeb2016-05-02 14:32:17 +000018// 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.
Hao Liu1c1e0c92015-06-26 02:10:27 +000023//
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//
David L Kreitzer01a057a2016-10-14 18:20:41 +000032// In X86, this can be further optimized into a set of target
33// specific loads followed by an optimized sequence of shuffles.
34//
Hao Liu1c1e0c92015-06-26 02:10:27 +000035// 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//
David L Kreitzer01a057a2016-10-14 18:20:41 +000043// 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.
Hao Liu1c1e0c92015-06-26 02:10:27 +000045//===----------------------------------------------------------------------===//
46
47#include "llvm/CodeGen/Passes.h"
Matthew Simpson476c0af2016-05-19 21:39:00 +000048#include "llvm/IR/Dominators.h"
Hao Liu1c1e0c92015-06-26 02:10:27 +000049#include "llvm/IR/InstIterator.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/MathExtras.h"
Hao Liub41c0b42015-06-26 04:38:21 +000052#include "llvm/Support/raw_ostream.h"
Hao Liu1c1e0c92015-06-26 02:10:27 +000053#include "llvm/Target/TargetLowering.h"
54#include "llvm/Target/TargetSubtargetInfo.h"
55
56using namespace llvm;
57
58#define DEBUG_TYPE "interleaved-access"
59
60static cl::opt<bool> LowerInterleavedAccesses(
61 "lower-interleaved-accesses",
62 cl::desc("Enable lowering interleaved accesses to intrinsics"),
Silviu Baranga6d3f05c2015-09-01 11:12:35 +000063 cl::init(true), cl::Hidden);
Hao Liu1c1e0c92015-06-26 02:10:27 +000064
Hao Liu1c1e0c92015-06-26 02:10:27 +000065namespace {
66
67class InterleavedAccess : public FunctionPass {
68
69public:
70 static char ID;
71 InterleavedAccess(const TargetMachine *TM = nullptr)
Matthew Simpson476c0af2016-05-19 21:39:00 +000072 : FunctionPass(ID), DT(nullptr), TM(TM), TLI(nullptr) {
Hao Liu1c1e0c92015-06-26 02:10:27 +000073 initializeInterleavedAccessPass(*PassRegistry::getPassRegistry());
74 }
75
Mehdi Amini117296c2016-10-01 02:56:57 +000076 StringRef getPassName() const override { return "Interleaved Access Pass"; }
Hao Liu1c1e0c92015-06-26 02:10:27 +000077
78 bool runOnFunction(Function &F) override;
79
Matthew Simpson476c0af2016-05-19 21:39:00 +000080 void getAnalysisUsage(AnalysisUsage &AU) const override {
81 AU.addRequired<DominatorTreeWrapperPass>();
82 AU.addPreserved<DominatorTreeWrapperPass>();
83 }
84
Hao Liu1c1e0c92015-06-26 02:10:27 +000085private:
Matthew Simpson476c0af2016-05-19 21:39:00 +000086 DominatorTree *DT;
Hao Liu1c1e0c92015-06-26 02:10:27 +000087 const TargetMachine *TM;
88 const TargetLowering *TLI;
89
Benjamin Kramer1e425c92016-10-18 18:59:58 +000090 /// The maximum supported interleave factor.
91 unsigned MaxFactor;
92
Hao Liu1c1e0c92015-06-26 02:10:27 +000093 /// \brief Transform an interleaved load into target specific intrinsics.
94 bool lowerInterleavedLoad(LoadInst *LI,
95 SmallVector<Instruction *, 32> &DeadInsts);
96
97 /// \brief Transform an interleaved store into target specific intrinsics.
98 bool lowerInterleavedStore(StoreInst *SI,
99 SmallVector<Instruction *, 32> &DeadInsts);
Matthew Simpson476c0af2016-05-19 21:39:00 +0000100
101 /// \brief Returns true if the uses of an interleaved load by the
102 /// extractelement instructions in \p Extracts can be replaced by uses of the
103 /// shufflevector instructions in \p Shuffles instead. If so, the necessary
104 /// replacements are also performed.
105 bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts,
106 ArrayRef<ShuffleVectorInst *> Shuffles);
Hao Liu1c1e0c92015-06-26 02:10:27 +0000107};
108} // end anonymous namespace.
109
110char InterleavedAccess::ID = 0;
Matthew Simpson476c0af2016-05-19 21:39:00 +0000111INITIALIZE_TM_PASS_BEGIN(
112 InterleavedAccess, "interleaved-access",
113 "Lower interleaved memory accesses to target specific intrinsics", false,
114 false)
115INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
116INITIALIZE_TM_PASS_END(
117 InterleavedAccess, "interleaved-access",
118 "Lower interleaved memory accesses to target specific intrinsics", false,
119 false)
Hao Liu1c1e0c92015-06-26 02:10:27 +0000120
121FunctionPass *llvm::createInterleavedAccessPass(const TargetMachine *TM) {
122 return new InterleavedAccess(TM);
123}
124
125/// \brief Check if the mask is a DE-interleave mask of the given factor
126/// \p Factor like:
127/// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
128static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
129 unsigned &Index) {
130 // Check all potential start indices from 0 to (Factor - 1).
131 for (Index = 0; Index < Factor; Index++) {
132 unsigned i = 0;
133
134 // Check that elements are in ascending order by Factor. Ignore undef
135 // elements.
136 for (; i < Mask.size(); i++)
137 if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor)
138 break;
139
140 if (i == Mask.size())
141 return true;
142 }
143
144 return false;
145}
146
147/// \brief Check if the mask is a DE-interleave mask for an interleaved load.
148///
149/// E.g. DE-interleave masks (Factor = 2) could be:
150/// <0, 2, 4, 6> (mask of index 0 to extract even elements)
151/// <1, 3, 5, 7> (mask of index 1 to extract odd elements)
152static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
Benjamin Kramer1e425c92016-10-18 18:59:58 +0000153 unsigned &Index, unsigned MaxFactor) {
Hao Liu1c1e0c92015-06-26 02:10:27 +0000154 if (Mask.size() < 2)
155 return false;
156
157 // Check potential Factors.
158 for (Factor = 2; Factor <= MaxFactor; Factor++)
159 if (isDeInterleaveMaskOfFactor(Mask, Factor, Index))
160 return true;
161
162 return false;
163}
164
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000165/// \brief Check if the mask can be used in an interleaved store.
166//
167/// It checks for a more general pattern than the RE-interleave mask.
168/// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...>
169/// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35>
170/// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
171/// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5>
Hao Liu1c1e0c92015-06-26 02:10:27 +0000172///
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000173/// The particular case of an RE-interleave mask is:
174/// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...>
175/// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7>
Benjamin Kramer1e425c92016-10-18 18:59:58 +0000176static bool isReInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
Matthias Braun01fa9622017-01-31 18:37:53 +0000177 unsigned MaxFactor, unsigned OpNumElts) {
Hao Liu1c1e0c92015-06-26 02:10:27 +0000178 unsigned NumElts = Mask.size();
179 if (NumElts < 4)
180 return false;
181
182 // Check potential Factors.
183 for (Factor = 2; Factor <= MaxFactor; Factor++) {
184 if (NumElts % Factor)
185 continue;
186
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000187 unsigned LaneLen = NumElts / Factor;
188 if (!isPowerOf2_32(LaneLen))
Hao Liu1c1e0c92015-06-26 02:10:27 +0000189 continue;
190
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000191 // Check whether each element matches the general interleaved rule.
192 // Ignore undef elements, as long as the defined elements match the rule.
193 // Outer loop processes all factors (x, y, z in the above example)
194 unsigned I = 0, J;
195 for (; I < Factor; I++) {
196 unsigned SavedLaneValue;
197 unsigned SavedNoUndefs = 0;
198
199 // Inner loop processes consecutive accesses (x, x+1... in the example)
200 for (J = 0; J < LaneLen - 1; J++) {
201 // Lane computes x's position in the Mask
202 unsigned Lane = J * Factor + I;
203 unsigned NextLane = Lane + Factor;
204 int LaneValue = Mask[Lane];
205 int NextLaneValue = Mask[NextLane];
206
207 // If both are defined, values must be sequential
208 if (LaneValue >= 0 && NextLaneValue >= 0 &&
209 LaneValue + 1 != NextLaneValue)
210 break;
211
212 // If the next value is undef, save the current one as reference
213 if (LaneValue >= 0 && NextLaneValue < 0) {
214 SavedLaneValue = LaneValue;
215 SavedNoUndefs = 1;
216 }
217
218 // Undefs are allowed, but defined elements must still be consecutive:
219 // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
220 // Verify this by storing the last non-undef followed by an undef
221 // Check that following non-undef masks are incremented with the
222 // corresponding distance.
223 if (SavedNoUndefs > 0 && LaneValue < 0) {
224 SavedNoUndefs++;
225 if (NextLaneValue >= 0 &&
226 SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
227 break;
228 }
229 }
230
231 if (J < LaneLen - 1)
Hao Liu1c1e0c92015-06-26 02:10:27 +0000232 break;
233
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000234 int StartMask = 0;
235 if (Mask[I] >= 0) {
236 // Check that the start of the I range (J=0) is greater than 0
237 StartMask = Mask[I];
238 } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
239 // StartMask defined by the last value in lane
240 StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
241 } else if (SavedNoUndefs > 0) {
242 // StartMask defined by some non-zero value in the j loop
243 StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
244 }
245 // else StartMask remains set to 0, i.e. all elements are undefs
246
247 if (StartMask < 0)
248 break;
Matthias Braun01fa9622017-01-31 18:37:53 +0000249 // We must stay within the vectors; This case can happen with undefs.
250 if (StartMask + LaneLen > OpNumElts*2)
251 break;
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +0000252 }
253
254 // Found an interleaved mask of current factor.
255 if (I == Factor)
Hao Liu1c1e0c92015-06-26 02:10:27 +0000256 return true;
257 }
258
259 return false;
260}
261
262bool InterleavedAccess::lowerInterleavedLoad(
263 LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) {
264 if (!LI->isSimple())
265 return false;
266
267 SmallVector<ShuffleVectorInst *, 4> Shuffles;
Matthew Simpson476c0af2016-05-19 21:39:00 +0000268 SmallVector<ExtractElementInst *, 4> Extracts;
Hao Liu1c1e0c92015-06-26 02:10:27 +0000269
Matthew Simpson476c0af2016-05-19 21:39:00 +0000270 // Check if all users of this load are shufflevectors. If we encounter any
271 // users that are extractelement instructions, we save them to later check if
272 // they can be modifed to extract from one of the shufflevectors instead of
273 // the load.
Hao Liu1c1e0c92015-06-26 02:10:27 +0000274 for (auto UI = LI->user_begin(), E = LI->user_end(); UI != E; UI++) {
Matthew Simpson476c0af2016-05-19 21:39:00 +0000275 auto *Extract = dyn_cast<ExtractElementInst>(*UI);
276 if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) {
277 Extracts.push_back(Extract);
278 continue;
279 }
Hao Liu1c1e0c92015-06-26 02:10:27 +0000280 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(*UI);
281 if (!SVI || !isa<UndefValue>(SVI->getOperand(1)))
282 return false;
283
284 Shuffles.push_back(SVI);
285 }
286
287 if (Shuffles.empty())
288 return false;
289
290 unsigned Factor, Index;
291
292 // Check if the first shufflevector is DE-interleave shuffle.
Benjamin Kramer1e425c92016-10-18 18:59:58 +0000293 if (!isDeInterleaveMask(Shuffles[0]->getShuffleMask(), Factor, Index,
294 MaxFactor))
Hao Liu1c1e0c92015-06-26 02:10:27 +0000295 return false;
296
297 // Holds the corresponding index for each DE-interleave shuffle.
298 SmallVector<unsigned, 4> Indices;
299 Indices.push_back(Index);
300
301 Type *VecTy = Shuffles[0]->getType();
302
303 // Check if other shufflevectors are also DE-interleaved of the same type
304 // and factor as the first shufflevector.
305 for (unsigned i = 1; i < Shuffles.size(); i++) {
306 if (Shuffles[i]->getType() != VecTy)
307 return false;
308
309 if (!isDeInterleaveMaskOfFactor(Shuffles[i]->getShuffleMask(), Factor,
310 Index))
311 return false;
312
313 Indices.push_back(Index);
314 }
315
Matthew Simpson476c0af2016-05-19 21:39:00 +0000316 // Try and modify users of the load that are extractelement instructions to
317 // use the shufflevector instructions instead of the load.
318 if (!tryReplaceExtracts(Extracts, Shuffles))
319 return false;
320
Hao Liu1c1e0c92015-06-26 02:10:27 +0000321 DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n");
322
323 // Try to create target specific intrinsics to replace the load and shuffles.
324 if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor))
325 return false;
326
327 for (auto SVI : Shuffles)
328 DeadInsts.push_back(SVI);
329
330 DeadInsts.push_back(LI);
331 return true;
332}
333
Matthew Simpson476c0af2016-05-19 21:39:00 +0000334bool InterleavedAccess::tryReplaceExtracts(
335 ArrayRef<ExtractElementInst *> Extracts,
336 ArrayRef<ShuffleVectorInst *> Shuffles) {
337
338 // If there aren't any extractelement instructions to modify, there's nothing
339 // to do.
340 if (Extracts.empty())
341 return true;
342
343 // Maps extractelement instructions to vector-index pairs. The extractlement
344 // instructions will be modified to use the new vector and index operands.
345 DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap;
346
347 for (auto *Extract : Extracts) {
348
349 // The vector index that is extracted.
350 auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand());
351 auto Index = IndexOperand->getSExtValue();
352
353 // Look for a suitable shufflevector instruction. The goal is to modify the
354 // extractelement instruction (which uses an interleaved load) to use one
355 // of the shufflevector instructions instead of the load.
356 for (auto *Shuffle : Shuffles) {
357
358 // If the shufflevector instruction doesn't dominate the extract, we
359 // can't create a use of it.
360 if (!DT->dominates(Shuffle, Extract))
361 continue;
362
363 // Inspect the indices of the shufflevector instruction. If the shuffle
364 // selects the same index that is extracted, we can modify the
365 // extractelement instruction.
366 SmallVector<int, 4> Indices;
367 Shuffle->getShuffleMask(Indices);
368 for (unsigned I = 0; I < Indices.size(); ++I)
369 if (Indices[I] == Index) {
370 assert(Extract->getOperand(0) == Shuffle->getOperand(0) &&
371 "Vector operations do not match");
372 ReplacementMap[Extract] = std::make_pair(Shuffle, I);
373 break;
374 }
375
376 // If we found a suitable shufflevector instruction, stop looking.
377 if (ReplacementMap.count(Extract))
378 break;
379 }
380
381 // If we did not find a suitable shufflevector instruction, the
382 // extractelement instruction cannot be modified, so we must give up.
383 if (!ReplacementMap.count(Extract))
384 return false;
385 }
386
387 // Finally, perform the replacements.
388 IRBuilder<> Builder(Extracts[0]->getContext());
389 for (auto &Replacement : ReplacementMap) {
390 auto *Extract = Replacement.first;
391 auto *Vector = Replacement.second.first;
392 auto Index = Replacement.second.second;
393 Builder.SetInsertPoint(Extract);
394 Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index));
395 Extract->eraseFromParent();
396 }
397
398 return true;
399}
400
Hao Liu1c1e0c92015-06-26 02:10:27 +0000401bool InterleavedAccess::lowerInterleavedStore(
402 StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) {
403 if (!SI->isSimple())
404 return false;
405
406 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand());
407 if (!SVI || !SVI->hasOneUse())
408 return false;
409
410 // Check if the shufflevector is RE-interleave shuffle.
411 unsigned Factor;
Matthias Braun01fa9622017-01-31 18:37:53 +0000412 unsigned OpNumElts = SVI->getOperand(0)->getType()->getVectorNumElements();
413 if (!isReInterleaveMask(SVI->getShuffleMask(), Factor, MaxFactor, OpNumElts))
Hao Liu1c1e0c92015-06-26 02:10:27 +0000414 return false;
415
416 DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n");
417
418 // Try to create target specific intrinsics to replace the store and shuffle.
419 if (!TLI->lowerInterleavedStore(SI, SVI, Factor))
420 return false;
421
422 // Already have a new target specific interleaved store. Erase the old store.
423 DeadInsts.push_back(SI);
424 DeadInsts.push_back(SVI);
425 return true;
426}
427
428bool InterleavedAccess::runOnFunction(Function &F) {
429 if (!TM || !LowerInterleavedAccesses)
430 return false;
431
432 DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n");
433
Matthew Simpson476c0af2016-05-19 21:39:00 +0000434 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Hao Liu1c1e0c92015-06-26 02:10:27 +0000435 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
436 MaxFactor = TLI->getMaxSupportedInterleaveFactor();
437
438 // Holds dead instructions that will be erased later.
439 SmallVector<Instruction *, 32> DeadInsts;
440 bool Changed = false;
441
Nico Rieck78199512015-08-06 19:10:45 +0000442 for (auto &I : instructions(F)) {
Hao Liu1c1e0c92015-06-26 02:10:27 +0000443 if (LoadInst *LI = dyn_cast<LoadInst>(&I))
444 Changed |= lowerInterleavedLoad(LI, DeadInsts);
445
446 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
447 Changed |= lowerInterleavedStore(SI, DeadInsts);
448 }
449
450 for (auto I : DeadInsts)
451 I->eraseFromParent();
452
453 return Changed;
454}