12cab237bSDimitry Andric //===- InterleavedAccessPass.cpp ------------------------------------------===//
23dac3a9bSDimitry Andric //
33dac3a9bSDimitry Andric //                     The LLVM Compiler Infrastructure
43dac3a9bSDimitry Andric //
53dac3a9bSDimitry Andric // This file is distributed under the University of Illinois Open Source
63dac3a9bSDimitry Andric // License. See LICENSE.TXT for details.
73dac3a9bSDimitry Andric //
83dac3a9bSDimitry Andric //===----------------------------------------------------------------------===//
93dac3a9bSDimitry Andric //
103dac3a9bSDimitry Andric // This file implements the Interleaved Access pass, which identifies
113ca95b02SDimitry Andric // interleaved memory accesses and transforms them into target specific
123ca95b02SDimitry Andric // intrinsics.
133dac3a9bSDimitry Andric //
143dac3a9bSDimitry Andric // An interleaved load reads data from memory into several vectors, with
153dac3a9bSDimitry Andric // DE-interleaving the data on a factor. An interleaved store writes several
163dac3a9bSDimitry Andric // vectors to memory with RE-interleaving the data on a factor.
173dac3a9bSDimitry Andric //
183ca95b02SDimitry Andric // As interleaved accesses are difficult to identified in CodeGen (mainly
193ca95b02SDimitry Andric // because the VECTOR_SHUFFLE DAG node is quite different from the shufflevector
203ca95b02SDimitry Andric // IR), we identify and transform them to intrinsics in this pass so the
213ca95b02SDimitry Andric // intrinsics can be easily matched into target specific instructions later in
223ca95b02SDimitry Andric // CodeGen.
233dac3a9bSDimitry Andric //
243dac3a9bSDimitry Andric // E.g. An interleaved load (Factor = 2):
253dac3a9bSDimitry Andric //        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
263dac3a9bSDimitry Andric //        %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <0, 2, 4, 6>
273dac3a9bSDimitry Andric //        %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <1, 3, 5, 7>
283dac3a9bSDimitry Andric //
293dac3a9bSDimitry Andric // It could be transformed into a ld2 intrinsic in AArch64 backend or a vld2
303dac3a9bSDimitry Andric // intrinsic in ARM backend.
313dac3a9bSDimitry Andric //
32d88c1a5aSDimitry Andric // In X86, this can be further optimized into a set of target
33d88c1a5aSDimitry Andric // specific loads followed by an optimized sequence of shuffles.
34d88c1a5aSDimitry Andric //
353dac3a9bSDimitry Andric // E.g. An interleaved store (Factor = 3):
363dac3a9bSDimitry Andric //        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
373dac3a9bSDimitry Andric //                                    <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
383dac3a9bSDimitry Andric //        store <12 x i32> %i.vec, <12 x i32>* %ptr
393dac3a9bSDimitry Andric //
403dac3a9bSDimitry Andric // It could be transformed into a st3 intrinsic in AArch64 backend or a vst3
413dac3a9bSDimitry Andric // intrinsic in ARM backend.
423dac3a9bSDimitry Andric //
43d88c1a5aSDimitry Andric // Similarly, a set of interleaved stores can be transformed into an optimized
44d88c1a5aSDimitry Andric // sequence of shuffles followed by a set of target specific stores for X86.
452cab237bSDimitry Andric //
463dac3a9bSDimitry Andric //===----------------------------------------------------------------------===//
473dac3a9bSDimitry Andric 
482cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
492cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
502cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
512cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
52d8866befSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
532cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
542cab237bSDimitry Andric #include "llvm/IR/Constants.h"
553ca95b02SDimitry Andric #include "llvm/IR/Dominators.h"
562cab237bSDimitry Andric #include "llvm/IR/Function.h"
572cab237bSDimitry Andric #include "llvm/IR/IRBuilder.h"
583dac3a9bSDimitry Andric #include "llvm/IR/InstIterator.h"
592cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
602cab237bSDimitry Andric #include "llvm/IR/Instructions.h"
612cab237bSDimitry Andric #include "llvm/IR/Type.h"
622cab237bSDimitry Andric #include "llvm/Pass.h"
632cab237bSDimitry Andric #include "llvm/Support/Casting.h"
642cab237bSDimitry Andric #include "llvm/Support/CommandLine.h"
653dac3a9bSDimitry Andric #include "llvm/Support/Debug.h"
663dac3a9bSDimitry Andric #include "llvm/Support/MathExtras.h"
673dac3a9bSDimitry Andric #include "llvm/Support/raw_ostream.h"
682cab237bSDimitry Andric #include "llvm/Target/TargetMachine.h"
692cab237bSDimitry Andric #include <cassert>
702cab237bSDimitry Andric #include <utility>
713dac3a9bSDimitry Andric 
723dac3a9bSDimitry Andric using namespace llvm;
733dac3a9bSDimitry Andric 
743dac3a9bSDimitry Andric #define DEBUG_TYPE "interleaved-access"
753dac3a9bSDimitry Andric 
763dac3a9bSDimitry Andric static cl::opt<bool> LowerInterleavedAccesses(
773dac3a9bSDimitry Andric     "lower-interleaved-accesses",
783dac3a9bSDimitry Andric     cl::desc("Enable lowering interleaved accesses to intrinsics"),
797d523365SDimitry Andric     cl::init(true), cl::Hidden);
803dac3a9bSDimitry Andric 
813dac3a9bSDimitry Andric namespace {
823dac3a9bSDimitry Andric 
833dac3a9bSDimitry Andric class InterleavedAccess : public FunctionPass {
843dac3a9bSDimitry Andric public:
853dac3a9bSDimitry Andric   static char ID;
862cab237bSDimitry Andric 
872cab237bSDimitry Andric   InterleavedAccess() : FunctionPass(ID) {
883dac3a9bSDimitry Andric     initializeInterleavedAccessPass(*PassRegistry::getPassRegistry());
893dac3a9bSDimitry Andric   }
903dac3a9bSDimitry Andric 
91d88c1a5aSDimitry Andric   StringRef getPassName() const override { return "Interleaved Access Pass"; }
923dac3a9bSDimitry Andric 
933dac3a9bSDimitry Andric   bool runOnFunction(Function &F) override;
943dac3a9bSDimitry Andric 
953ca95b02SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
963ca95b02SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
973ca95b02SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
983ca95b02SDimitry Andric   }
993ca95b02SDimitry Andric 
1003dac3a9bSDimitry Andric private:
1012cab237bSDimitry Andric   DominatorTree *DT = nullptr;
1022cab237bSDimitry Andric   const TargetLowering *TLI = nullptr;
1033dac3a9bSDimitry Andric 
104d88c1a5aSDimitry Andric   /// The maximum supported interleave factor.
105d88c1a5aSDimitry Andric   unsigned MaxFactor;
106d88c1a5aSDimitry Andric 
1073dac3a9bSDimitry Andric   /// \brief Transform an interleaved load into target specific intrinsics.
1083dac3a9bSDimitry Andric   bool lowerInterleavedLoad(LoadInst *LI,
1093dac3a9bSDimitry Andric                             SmallVector<Instruction *, 32> &DeadInsts);
1103dac3a9bSDimitry Andric 
1113dac3a9bSDimitry Andric   /// \brief Transform an interleaved store into target specific intrinsics.
1123dac3a9bSDimitry Andric   bool lowerInterleavedStore(StoreInst *SI,
1133dac3a9bSDimitry Andric                              SmallVector<Instruction *, 32> &DeadInsts);
1143ca95b02SDimitry Andric 
1153ca95b02SDimitry Andric   /// \brief Returns true if the uses of an interleaved load by the
1163ca95b02SDimitry Andric   /// extractelement instructions in \p Extracts can be replaced by uses of the
1173ca95b02SDimitry Andric   /// shufflevector instructions in \p Shuffles instead. If so, the necessary
1183ca95b02SDimitry Andric   /// replacements are also performed.
1193ca95b02SDimitry Andric   bool tryReplaceExtracts(ArrayRef<ExtractElementInst *> Extracts,
1203ca95b02SDimitry Andric                           ArrayRef<ShuffleVectorInst *> Shuffles);
1213dac3a9bSDimitry Andric };
1222cab237bSDimitry Andric 
1233dac3a9bSDimitry Andric } // end anonymous namespace.
1243dac3a9bSDimitry Andric 
1253dac3a9bSDimitry Andric char InterleavedAccess::ID = 0;
1262cab237bSDimitry Andric 
127302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(InterleavedAccess, DEBUG_TYPE,
1283ca95b02SDimitry Andric     "Lower interleaved memory accesses to target specific intrinsics", false,
1293ca95b02SDimitry Andric     false)
1303ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
131302affcbSDimitry Andric INITIALIZE_PASS_END(InterleavedAccess, DEBUG_TYPE,
1323ca95b02SDimitry Andric     "Lower interleaved memory accesses to target specific intrinsics", false,
1333ca95b02SDimitry Andric     false)
1343dac3a9bSDimitry Andric 
135d8866befSDimitry Andric FunctionPass *llvm::createInterleavedAccessPass() {
136d8866befSDimitry Andric   return new InterleavedAccess();
1373dac3a9bSDimitry Andric }
1383dac3a9bSDimitry Andric 
1393dac3a9bSDimitry Andric /// \brief Check if the mask is a DE-interleave mask of the given factor
1403dac3a9bSDimitry Andric /// \p Factor like:
1413dac3a9bSDimitry Andric ///     <Index, Index+Factor, ..., Index+(NumElts-1)*Factor>
1423dac3a9bSDimitry Andric static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor,
1433dac3a9bSDimitry Andric                                        unsigned &Index) {
1443dac3a9bSDimitry Andric   // Check all potential start indices from 0 to (Factor - 1).
1453dac3a9bSDimitry Andric   for (Index = 0; Index < Factor; Index++) {
1463dac3a9bSDimitry Andric     unsigned i = 0;
1473dac3a9bSDimitry Andric 
1483dac3a9bSDimitry Andric     // Check that elements are in ascending order by Factor. Ignore undef
1493dac3a9bSDimitry Andric     // elements.
1503dac3a9bSDimitry Andric     for (; i < Mask.size(); i++)
1513dac3a9bSDimitry Andric       if (Mask[i] >= 0 && static_cast<unsigned>(Mask[i]) != Index + i * Factor)
1523dac3a9bSDimitry Andric         break;
1533dac3a9bSDimitry Andric 
1543dac3a9bSDimitry Andric     if (i == Mask.size())
1553dac3a9bSDimitry Andric       return true;
1563dac3a9bSDimitry Andric   }
1573dac3a9bSDimitry Andric 
1583dac3a9bSDimitry Andric   return false;
1593dac3a9bSDimitry Andric }
1603dac3a9bSDimitry Andric 
1613dac3a9bSDimitry Andric /// \brief Check if the mask is a DE-interleave mask for an interleaved load.
1623dac3a9bSDimitry Andric ///
1633dac3a9bSDimitry Andric /// E.g. DE-interleave masks (Factor = 2) could be:
1643dac3a9bSDimitry Andric ///     <0, 2, 4, 6>    (mask of index 0 to extract even elements)
1653dac3a9bSDimitry Andric ///     <1, 3, 5, 7>    (mask of index 1 to extract odd elements)
1663dac3a9bSDimitry Andric static bool isDeInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
167d88c1a5aSDimitry Andric                                unsigned &Index, unsigned MaxFactor) {
1683dac3a9bSDimitry Andric   if (Mask.size() < 2)
1693dac3a9bSDimitry Andric     return false;
1703dac3a9bSDimitry Andric 
1713dac3a9bSDimitry Andric   // Check potential Factors.
1723dac3a9bSDimitry Andric   for (Factor = 2; Factor <= MaxFactor; Factor++)
1733dac3a9bSDimitry Andric     if (isDeInterleaveMaskOfFactor(Mask, Factor, Index))
1743dac3a9bSDimitry Andric       return true;
1753dac3a9bSDimitry Andric 
1763dac3a9bSDimitry Andric   return false;
1773dac3a9bSDimitry Andric }
1783dac3a9bSDimitry Andric 
179d88c1a5aSDimitry Andric /// \brief Check if the mask can be used in an interleaved store.
180d88c1a5aSDimitry Andric //
181d88c1a5aSDimitry Andric /// It checks for a more general pattern than the RE-interleave mask.
182d88c1a5aSDimitry Andric /// I.e. <x, y, ... z, x+1, y+1, ...z+1, x+2, y+2, ...z+2, ...>
183d88c1a5aSDimitry Andric /// E.g. For a Factor of 2 (LaneLen=4): <4, 32, 5, 33, 6, 34, 7, 35>
184d88c1a5aSDimitry Andric /// E.g. For a Factor of 3 (LaneLen=4): <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
185d88c1a5aSDimitry Andric /// E.g. For a Factor of 4 (LaneLen=2): <8, 2, 12, 4, 9, 3, 13, 5>
1863dac3a9bSDimitry Andric ///
187d88c1a5aSDimitry Andric /// The particular case of an RE-interleave mask is:
188d88c1a5aSDimitry Andric /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...>
189d88c1a5aSDimitry Andric /// E.g. For a Factor of 2 (LaneLen=4): <0, 4, 1, 5, 2, 6, 3, 7>
190d88c1a5aSDimitry Andric static bool isReInterleaveMask(ArrayRef<int> Mask, unsigned &Factor,
191077e1117SDimitry Andric                                unsigned MaxFactor, unsigned OpNumElts) {
1923dac3a9bSDimitry Andric   unsigned NumElts = Mask.size();
1933dac3a9bSDimitry Andric   if (NumElts < 4)
1943dac3a9bSDimitry Andric     return false;
1953dac3a9bSDimitry Andric 
1963dac3a9bSDimitry Andric   // Check potential Factors.
1973dac3a9bSDimitry Andric   for (Factor = 2; Factor <= MaxFactor; Factor++) {
1983dac3a9bSDimitry Andric     if (NumElts % Factor)
1993dac3a9bSDimitry Andric       continue;
2003dac3a9bSDimitry Andric 
201d88c1a5aSDimitry Andric     unsigned LaneLen = NumElts / Factor;
202d88c1a5aSDimitry Andric     if (!isPowerOf2_32(LaneLen))
2033dac3a9bSDimitry Andric       continue;
2043dac3a9bSDimitry Andric 
205d88c1a5aSDimitry Andric     // Check whether each element matches the general interleaved rule.
206d88c1a5aSDimitry Andric     // Ignore undef elements, as long as the defined elements match the rule.
207d88c1a5aSDimitry Andric     // Outer loop processes all factors (x, y, z in the above example)
208d88c1a5aSDimitry Andric     unsigned I = 0, J;
209d88c1a5aSDimitry Andric     for (; I < Factor; I++) {
210d88c1a5aSDimitry Andric       unsigned SavedLaneValue;
211d88c1a5aSDimitry Andric       unsigned SavedNoUndefs = 0;
212d88c1a5aSDimitry Andric 
213d88c1a5aSDimitry Andric       // Inner loop processes consecutive accesses (x, x+1... in the example)
214d88c1a5aSDimitry Andric       for (J = 0; J < LaneLen - 1; J++) {
215d88c1a5aSDimitry Andric         // Lane computes x's position in the Mask
216d88c1a5aSDimitry Andric         unsigned Lane = J * Factor + I;
217d88c1a5aSDimitry Andric         unsigned NextLane = Lane + Factor;
218d88c1a5aSDimitry Andric         int LaneValue = Mask[Lane];
219d88c1a5aSDimitry Andric         int NextLaneValue = Mask[NextLane];
220d88c1a5aSDimitry Andric 
221d88c1a5aSDimitry Andric         // If both are defined, values must be sequential
222d88c1a5aSDimitry Andric         if (LaneValue >= 0 && NextLaneValue >= 0 &&
223d88c1a5aSDimitry Andric             LaneValue + 1 != NextLaneValue)
2243dac3a9bSDimitry Andric           break;
2253dac3a9bSDimitry Andric 
226d88c1a5aSDimitry Andric         // If the next value is undef, save the current one as reference
227d88c1a5aSDimitry Andric         if (LaneValue >= 0 && NextLaneValue < 0) {
228d88c1a5aSDimitry Andric           SavedLaneValue = LaneValue;
229d88c1a5aSDimitry Andric           SavedNoUndefs = 1;
230d88c1a5aSDimitry Andric         }
231d88c1a5aSDimitry Andric 
232d88c1a5aSDimitry Andric         // Undefs are allowed, but defined elements must still be consecutive:
233d88c1a5aSDimitry Andric         // i.e.: x,..., undef,..., x + 2,..., undef,..., undef,..., x + 5, ....
234d88c1a5aSDimitry Andric         // Verify this by storing the last non-undef followed by an undef
235d88c1a5aSDimitry Andric         // Check that following non-undef masks are incremented with the
236d88c1a5aSDimitry Andric         // corresponding distance.
237d88c1a5aSDimitry Andric         if (SavedNoUndefs > 0 && LaneValue < 0) {
238d88c1a5aSDimitry Andric           SavedNoUndefs++;
239d88c1a5aSDimitry Andric           if (NextLaneValue >= 0 &&
240d88c1a5aSDimitry Andric               SavedLaneValue + SavedNoUndefs != (unsigned)NextLaneValue)
241d88c1a5aSDimitry Andric             break;
242d88c1a5aSDimitry Andric         }
243d88c1a5aSDimitry Andric       }
244d88c1a5aSDimitry Andric 
245d88c1a5aSDimitry Andric       if (J < LaneLen - 1)
246d88c1a5aSDimitry Andric         break;
247d88c1a5aSDimitry Andric 
248d88c1a5aSDimitry Andric       int StartMask = 0;
249d88c1a5aSDimitry Andric       if (Mask[I] >= 0) {
250d88c1a5aSDimitry Andric         // Check that the start of the I range (J=0) is greater than 0
251d88c1a5aSDimitry Andric         StartMask = Mask[I];
252d88c1a5aSDimitry Andric       } else if (Mask[(LaneLen - 1) * Factor + I] >= 0) {
253d88c1a5aSDimitry Andric         // StartMask defined by the last value in lane
254d88c1a5aSDimitry Andric         StartMask = Mask[(LaneLen - 1) * Factor + I] - J;
255d88c1a5aSDimitry Andric       } else if (SavedNoUndefs > 0) {
256d88c1a5aSDimitry Andric         // StartMask defined by some non-zero value in the j loop
257d88c1a5aSDimitry Andric         StartMask = SavedLaneValue - (LaneLen - 1 - SavedNoUndefs);
258d88c1a5aSDimitry Andric       }
259d88c1a5aSDimitry Andric       // else StartMask remains set to 0, i.e. all elements are undefs
260d88c1a5aSDimitry Andric 
261d88c1a5aSDimitry Andric       if (StartMask < 0)
262d88c1a5aSDimitry Andric         break;
263077e1117SDimitry Andric       // We must stay within the vectors; This case can happen with undefs.
264077e1117SDimitry Andric       if (StartMask + LaneLen > OpNumElts*2)
265077e1117SDimitry Andric         break;
266d88c1a5aSDimitry Andric     }
267d88c1a5aSDimitry Andric 
268d88c1a5aSDimitry Andric     // Found an interleaved mask of current factor.
269d88c1a5aSDimitry Andric     if (I == Factor)
2703dac3a9bSDimitry Andric       return true;
2713dac3a9bSDimitry Andric   }
2723dac3a9bSDimitry Andric 
2733dac3a9bSDimitry Andric   return false;
2743dac3a9bSDimitry Andric }
2753dac3a9bSDimitry Andric 
2763dac3a9bSDimitry Andric bool InterleavedAccess::lowerInterleavedLoad(
2773dac3a9bSDimitry Andric     LoadInst *LI, SmallVector<Instruction *, 32> &DeadInsts) {
2783dac3a9bSDimitry Andric   if (!LI->isSimple())
2793dac3a9bSDimitry Andric     return false;
2803dac3a9bSDimitry Andric 
2813dac3a9bSDimitry Andric   SmallVector<ShuffleVectorInst *, 4> Shuffles;
2823ca95b02SDimitry Andric   SmallVector<ExtractElementInst *, 4> Extracts;
2833dac3a9bSDimitry Andric 
2843ca95b02SDimitry Andric   // Check if all users of this load are shufflevectors. If we encounter any
2853ca95b02SDimitry Andric   // users that are extractelement instructions, we save them to later check if
2863ca95b02SDimitry Andric   // they can be modifed to extract from one of the shufflevectors instead of
2873ca95b02SDimitry Andric   // the load.
2883dac3a9bSDimitry Andric   for (auto UI = LI->user_begin(), E = LI->user_end(); UI != E; UI++) {
2893ca95b02SDimitry Andric     auto *Extract = dyn_cast<ExtractElementInst>(*UI);
2903ca95b02SDimitry Andric     if (Extract && isa<ConstantInt>(Extract->getIndexOperand())) {
2913ca95b02SDimitry Andric       Extracts.push_back(Extract);
2923ca95b02SDimitry Andric       continue;
2933ca95b02SDimitry Andric     }
2943dac3a9bSDimitry Andric     ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(*UI);
2953dac3a9bSDimitry Andric     if (!SVI || !isa<UndefValue>(SVI->getOperand(1)))
2963dac3a9bSDimitry Andric       return false;
2973dac3a9bSDimitry Andric 
2983dac3a9bSDimitry Andric     Shuffles.push_back(SVI);
2993dac3a9bSDimitry Andric   }
3003dac3a9bSDimitry Andric 
3013dac3a9bSDimitry Andric   if (Shuffles.empty())
3023dac3a9bSDimitry Andric     return false;
3033dac3a9bSDimitry Andric 
3043dac3a9bSDimitry Andric   unsigned Factor, Index;
3053dac3a9bSDimitry Andric 
3063dac3a9bSDimitry Andric   // Check if the first shufflevector is DE-interleave shuffle.
307d88c1a5aSDimitry Andric   if (!isDeInterleaveMask(Shuffles[0]->getShuffleMask(), Factor, Index,
308d88c1a5aSDimitry Andric                           MaxFactor))
3093dac3a9bSDimitry Andric     return false;
3103dac3a9bSDimitry Andric 
3113dac3a9bSDimitry Andric   // Holds the corresponding index for each DE-interleave shuffle.
3123dac3a9bSDimitry Andric   SmallVector<unsigned, 4> Indices;
3133dac3a9bSDimitry Andric   Indices.push_back(Index);
3143dac3a9bSDimitry Andric 
3153dac3a9bSDimitry Andric   Type *VecTy = Shuffles[0]->getType();
3163dac3a9bSDimitry Andric 
3173dac3a9bSDimitry Andric   // Check if other shufflevectors are also DE-interleaved of the same type
3183dac3a9bSDimitry Andric   // and factor as the first shufflevector.
3193dac3a9bSDimitry Andric   for (unsigned i = 1; i < Shuffles.size(); i++) {
3203dac3a9bSDimitry Andric     if (Shuffles[i]->getType() != VecTy)
3213dac3a9bSDimitry Andric       return false;
3223dac3a9bSDimitry Andric 
3233dac3a9bSDimitry Andric     if (!isDeInterleaveMaskOfFactor(Shuffles[i]->getShuffleMask(), Factor,
3243dac3a9bSDimitry Andric                                     Index))
3253dac3a9bSDimitry Andric       return false;
3263dac3a9bSDimitry Andric 
3273dac3a9bSDimitry Andric     Indices.push_back(Index);
3283dac3a9bSDimitry Andric   }
3293dac3a9bSDimitry Andric 
3303ca95b02SDimitry Andric   // Try and modify users of the load that are extractelement instructions to
3313ca95b02SDimitry Andric   // use the shufflevector instructions instead of the load.
3323ca95b02SDimitry Andric   if (!tryReplaceExtracts(Extracts, Shuffles))
3333ca95b02SDimitry Andric     return false;
3343ca95b02SDimitry Andric 
3353dac3a9bSDimitry Andric   DEBUG(dbgs() << "IA: Found an interleaved load: " << *LI << "\n");
3363dac3a9bSDimitry Andric 
3373dac3a9bSDimitry Andric   // Try to create target specific intrinsics to replace the load and shuffles.
3383dac3a9bSDimitry Andric   if (!TLI->lowerInterleavedLoad(LI, Shuffles, Indices, Factor))
3393dac3a9bSDimitry Andric     return false;
3403dac3a9bSDimitry Andric 
3413dac3a9bSDimitry Andric   for (auto SVI : Shuffles)
3423dac3a9bSDimitry Andric     DeadInsts.push_back(SVI);
3433dac3a9bSDimitry Andric 
3443dac3a9bSDimitry Andric   DeadInsts.push_back(LI);
3453dac3a9bSDimitry Andric   return true;
3463dac3a9bSDimitry Andric }
3473dac3a9bSDimitry Andric 
3483ca95b02SDimitry Andric bool InterleavedAccess::tryReplaceExtracts(
3493ca95b02SDimitry Andric     ArrayRef<ExtractElementInst *> Extracts,
3503ca95b02SDimitry Andric     ArrayRef<ShuffleVectorInst *> Shuffles) {
3513ca95b02SDimitry Andric   // If there aren't any extractelement instructions to modify, there's nothing
3523ca95b02SDimitry Andric   // to do.
3533ca95b02SDimitry Andric   if (Extracts.empty())
3543ca95b02SDimitry Andric     return true;
3553ca95b02SDimitry Andric 
3563ca95b02SDimitry Andric   // Maps extractelement instructions to vector-index pairs. The extractlement
3573ca95b02SDimitry Andric   // instructions will be modified to use the new vector and index operands.
3583ca95b02SDimitry Andric   DenseMap<ExtractElementInst *, std::pair<Value *, int>> ReplacementMap;
3593ca95b02SDimitry Andric 
3603ca95b02SDimitry Andric   for (auto *Extract : Extracts) {
3613ca95b02SDimitry Andric     // The vector index that is extracted.
3623ca95b02SDimitry Andric     auto *IndexOperand = cast<ConstantInt>(Extract->getIndexOperand());
3633ca95b02SDimitry Andric     auto Index = IndexOperand->getSExtValue();
3643ca95b02SDimitry Andric 
3653ca95b02SDimitry Andric     // Look for a suitable shufflevector instruction. The goal is to modify the
3663ca95b02SDimitry Andric     // extractelement instruction (which uses an interleaved load) to use one
3673ca95b02SDimitry Andric     // of the shufflevector instructions instead of the load.
3683ca95b02SDimitry Andric     for (auto *Shuffle : Shuffles) {
3693ca95b02SDimitry Andric       // If the shufflevector instruction doesn't dominate the extract, we
3703ca95b02SDimitry Andric       // can't create a use of it.
3713ca95b02SDimitry Andric       if (!DT->dominates(Shuffle, Extract))
3723ca95b02SDimitry Andric         continue;
3733ca95b02SDimitry Andric 
3743ca95b02SDimitry Andric       // Inspect the indices of the shufflevector instruction. If the shuffle
3753ca95b02SDimitry Andric       // selects the same index that is extracted, we can modify the
3763ca95b02SDimitry Andric       // extractelement instruction.
3773ca95b02SDimitry Andric       SmallVector<int, 4> Indices;
3783ca95b02SDimitry Andric       Shuffle->getShuffleMask(Indices);
3793ca95b02SDimitry Andric       for (unsigned I = 0; I < Indices.size(); ++I)
3803ca95b02SDimitry Andric         if (Indices[I] == Index) {
3813ca95b02SDimitry Andric           assert(Extract->getOperand(0) == Shuffle->getOperand(0) &&
3823ca95b02SDimitry Andric                  "Vector operations do not match");
3833ca95b02SDimitry Andric           ReplacementMap[Extract] = std::make_pair(Shuffle, I);
3843ca95b02SDimitry Andric           break;
3853ca95b02SDimitry Andric         }
3863ca95b02SDimitry Andric 
3873ca95b02SDimitry Andric       // If we found a suitable shufflevector instruction, stop looking.
3883ca95b02SDimitry Andric       if (ReplacementMap.count(Extract))
3893ca95b02SDimitry Andric         break;
3903ca95b02SDimitry Andric     }
3913ca95b02SDimitry Andric 
3923ca95b02SDimitry Andric     // If we did not find a suitable shufflevector instruction, the
3933ca95b02SDimitry Andric     // extractelement instruction cannot be modified, so we must give up.
3943ca95b02SDimitry Andric     if (!ReplacementMap.count(Extract))
3953ca95b02SDimitry Andric       return false;
3963ca95b02SDimitry Andric   }
3973ca95b02SDimitry Andric 
3983ca95b02SDimitry Andric   // Finally, perform the replacements.
3993ca95b02SDimitry Andric   IRBuilder<> Builder(Extracts[0]->getContext());
4003ca95b02SDimitry Andric   for (auto &Replacement : ReplacementMap) {
4013ca95b02SDimitry Andric     auto *Extract = Replacement.first;
4023ca95b02SDimitry Andric     auto *Vector = Replacement.second.first;
4033ca95b02SDimitry Andric     auto Index = Replacement.second.second;
4043ca95b02SDimitry Andric     Builder.SetInsertPoint(Extract);
4053ca95b02SDimitry Andric     Extract->replaceAllUsesWith(Builder.CreateExtractElement(Vector, Index));
4063ca95b02SDimitry Andric     Extract->eraseFromParent();
4073ca95b02SDimitry Andric   }
4083ca95b02SDimitry Andric 
4093ca95b02SDimitry Andric   return true;
4103ca95b02SDimitry Andric }
4113ca95b02SDimitry Andric 
4123dac3a9bSDimitry Andric bool InterleavedAccess::lowerInterleavedStore(
4133dac3a9bSDimitry Andric     StoreInst *SI, SmallVector<Instruction *, 32> &DeadInsts) {
4143dac3a9bSDimitry Andric   if (!SI->isSimple())
4153dac3a9bSDimitry Andric     return false;
4163dac3a9bSDimitry Andric 
4173dac3a9bSDimitry Andric   ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SI->getValueOperand());
4183dac3a9bSDimitry Andric   if (!SVI || !SVI->hasOneUse())
4193dac3a9bSDimitry Andric     return false;
4203dac3a9bSDimitry Andric 
4213dac3a9bSDimitry Andric   // Check if the shufflevector is RE-interleave shuffle.
4223dac3a9bSDimitry Andric   unsigned Factor;
423077e1117SDimitry Andric   unsigned OpNumElts = SVI->getOperand(0)->getType()->getVectorNumElements();
424077e1117SDimitry Andric   if (!isReInterleaveMask(SVI->getShuffleMask(), Factor, MaxFactor, OpNumElts))
4253dac3a9bSDimitry Andric     return false;
4263dac3a9bSDimitry Andric 
4273dac3a9bSDimitry Andric   DEBUG(dbgs() << "IA: Found an interleaved store: " << *SI << "\n");
4283dac3a9bSDimitry Andric 
4293dac3a9bSDimitry Andric   // Try to create target specific intrinsics to replace the store and shuffle.
4303dac3a9bSDimitry Andric   if (!TLI->lowerInterleavedStore(SI, SVI, Factor))
4313dac3a9bSDimitry Andric     return false;
4323dac3a9bSDimitry Andric 
4333dac3a9bSDimitry Andric   // Already have a new target specific interleaved store. Erase the old store.
4343dac3a9bSDimitry Andric   DeadInsts.push_back(SI);
4353dac3a9bSDimitry Andric   DeadInsts.push_back(SVI);
4363dac3a9bSDimitry Andric   return true;
4373dac3a9bSDimitry Andric }
4383dac3a9bSDimitry Andric 
4393dac3a9bSDimitry Andric bool InterleavedAccess::runOnFunction(Function &F) {
440d8866befSDimitry Andric   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
441d8866befSDimitry Andric   if (!TPC || !LowerInterleavedAccesses)
4423dac3a9bSDimitry Andric     return false;
4433dac3a9bSDimitry Andric 
4443dac3a9bSDimitry Andric   DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName() << "\n");
4453dac3a9bSDimitry Andric 
4463ca95b02SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
447d8866befSDimitry Andric   auto &TM = TPC->getTM<TargetMachine>();
448d8866befSDimitry Andric   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
4493dac3a9bSDimitry Andric   MaxFactor = TLI->getMaxSupportedInterleaveFactor();
4503dac3a9bSDimitry Andric 
4513dac3a9bSDimitry Andric   // Holds dead instructions that will be erased later.
4523dac3a9bSDimitry Andric   SmallVector<Instruction *, 32> DeadInsts;
4533dac3a9bSDimitry Andric   bool Changed = false;
4543dac3a9bSDimitry Andric 
4557d523365SDimitry Andric   for (auto &I : instructions(F)) {
4563dac3a9bSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(&I))
4573dac3a9bSDimitry Andric       Changed |= lowerInterleavedLoad(LI, DeadInsts);
4583dac3a9bSDimitry Andric 
4593dac3a9bSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4603dac3a9bSDimitry Andric       Changed |= lowerInterleavedStore(SI, DeadInsts);
4613dac3a9bSDimitry Andric   }
4623dac3a9bSDimitry Andric 
4633dac3a9bSDimitry Andric   for (auto I : DeadInsts)
4643dac3a9bSDimitry Andric     I->eraseFromParent();
4653dac3a9bSDimitry Andric 
4663dac3a9bSDimitry Andric   return Changed;
4673dac3a9bSDimitry Andric }
468