xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVGatherScatterLowering.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1349cc55cSDimitry Andric //===- RISCVGatherScatterLowering.cpp - Gather/Scatter lowering -----------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This pass custom lowers llvm.gather and llvm.scatter instructions to
10349cc55cSDimitry Andric // RISCV intrinsics.
11349cc55cSDimitry Andric //
12349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
13349cc55cSDimitry Andric 
14349cc55cSDimitry Andric #include "RISCV.h"
15349cc55cSDimitry Andric #include "RISCVTargetMachine.h"
16349cc55cSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
17349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
18349cc55cSDimitry Andric #include "llvm/Analysis/VectorUtils.h"
19349cc55cSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
20349cc55cSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
21349cc55cSDimitry Andric #include "llvm/IR/IRBuilder.h"
22349cc55cSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
23349cc55cSDimitry Andric #include "llvm/IR/IntrinsicsRISCV.h"
24*bdd1243dSDimitry Andric #include "llvm/IR/PatternMatch.h"
25349cc55cSDimitry Andric #include "llvm/Transforms/Utils/Local.h"
26*bdd1243dSDimitry Andric #include <optional>
27349cc55cSDimitry Andric 
28349cc55cSDimitry Andric using namespace llvm;
29*bdd1243dSDimitry Andric using namespace PatternMatch;
30349cc55cSDimitry Andric 
31349cc55cSDimitry Andric #define DEBUG_TYPE "riscv-gather-scatter-lowering"
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric namespace {
34349cc55cSDimitry Andric 
35349cc55cSDimitry Andric class RISCVGatherScatterLowering : public FunctionPass {
36349cc55cSDimitry Andric   const RISCVSubtarget *ST = nullptr;
37349cc55cSDimitry Andric   const RISCVTargetLowering *TLI = nullptr;
38349cc55cSDimitry Andric   LoopInfo *LI = nullptr;
39349cc55cSDimitry Andric   const DataLayout *DL = nullptr;
40349cc55cSDimitry Andric 
41349cc55cSDimitry Andric   SmallVector<WeakTrackingVH> MaybeDeadPHIs;
42349cc55cSDimitry Andric 
4381ad6265SDimitry Andric   // Cache of the BasePtr and Stride determined from this GEP. When a GEP is
4481ad6265SDimitry Andric   // used by multiple gathers/scatters, this allow us to reuse the scalar
4581ad6265SDimitry Andric   // instructions we created for the first gather/scatter for the others.
4681ad6265SDimitry Andric   DenseMap<GetElementPtrInst *, std::pair<Value *, Value *>> StridedAddrs;
4781ad6265SDimitry Andric 
48349cc55cSDimitry Andric public:
49349cc55cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
50349cc55cSDimitry Andric 
51349cc55cSDimitry Andric   RISCVGatherScatterLowering() : FunctionPass(ID) {}
52349cc55cSDimitry Andric 
53349cc55cSDimitry Andric   bool runOnFunction(Function &F) override;
54349cc55cSDimitry Andric 
55349cc55cSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
56349cc55cSDimitry Andric     AU.setPreservesCFG();
57349cc55cSDimitry Andric     AU.addRequired<TargetPassConfig>();
58349cc55cSDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
59349cc55cSDimitry Andric   }
60349cc55cSDimitry Andric 
61349cc55cSDimitry Andric   StringRef getPassName() const override {
62349cc55cSDimitry Andric     return "RISCV gather/scatter lowering";
63349cc55cSDimitry Andric   }
64349cc55cSDimitry Andric 
65349cc55cSDimitry Andric private:
66349cc55cSDimitry Andric   bool isLegalTypeAndAlignment(Type *DataType, Value *AlignOp);
67349cc55cSDimitry Andric 
68349cc55cSDimitry Andric   bool tryCreateStridedLoadStore(IntrinsicInst *II, Type *DataType, Value *Ptr,
69349cc55cSDimitry Andric                                  Value *AlignOp);
70349cc55cSDimitry Andric 
71349cc55cSDimitry Andric   std::pair<Value *, Value *> determineBaseAndStride(GetElementPtrInst *GEP,
72349cc55cSDimitry Andric                                                      IRBuilder<> &Builder);
73349cc55cSDimitry Andric 
74349cc55cSDimitry Andric   bool matchStridedRecurrence(Value *Index, Loop *L, Value *&Stride,
75349cc55cSDimitry Andric                               PHINode *&BasePtr, BinaryOperator *&Inc,
76349cc55cSDimitry Andric                               IRBuilder<> &Builder);
77349cc55cSDimitry Andric };
78349cc55cSDimitry Andric 
79349cc55cSDimitry Andric } // end anonymous namespace
80349cc55cSDimitry Andric 
81349cc55cSDimitry Andric char RISCVGatherScatterLowering::ID = 0;
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric INITIALIZE_PASS(RISCVGatherScatterLowering, DEBUG_TYPE,
84349cc55cSDimitry Andric                 "RISCV gather/scatter lowering pass", false, false)
85349cc55cSDimitry Andric 
86349cc55cSDimitry Andric FunctionPass *llvm::createRISCVGatherScatterLoweringPass() {
87349cc55cSDimitry Andric   return new RISCVGatherScatterLowering();
88349cc55cSDimitry Andric }
89349cc55cSDimitry Andric 
90349cc55cSDimitry Andric bool RISCVGatherScatterLowering::isLegalTypeAndAlignment(Type *DataType,
91349cc55cSDimitry Andric                                                          Value *AlignOp) {
92349cc55cSDimitry Andric   Type *ScalarType = DataType->getScalarType();
93349cc55cSDimitry Andric   if (!TLI->isLegalElementTypeForRVV(ScalarType))
94349cc55cSDimitry Andric     return false;
95349cc55cSDimitry Andric 
96349cc55cSDimitry Andric   MaybeAlign MA = cast<ConstantInt>(AlignOp)->getMaybeAlignValue();
97*bdd1243dSDimitry Andric   if (MA && MA->value() < DL->getTypeStoreSize(ScalarType).getFixedValue())
98349cc55cSDimitry Andric     return false;
99349cc55cSDimitry Andric 
100349cc55cSDimitry Andric   // FIXME: Let the backend type legalize by splitting/widening?
101349cc55cSDimitry Andric   EVT DataVT = TLI->getValueType(*DL, DataType);
102349cc55cSDimitry Andric   if (!TLI->isTypeLegal(DataVT))
103349cc55cSDimitry Andric     return false;
104349cc55cSDimitry Andric 
105349cc55cSDimitry Andric   return true;
106349cc55cSDimitry Andric }
107349cc55cSDimitry Andric 
108349cc55cSDimitry Andric // TODO: Should we consider the mask when looking for a stride?
109349cc55cSDimitry Andric static std::pair<Value *, Value *> matchStridedConstant(Constant *StartC) {
110349cc55cSDimitry Andric   unsigned NumElts = cast<FixedVectorType>(StartC->getType())->getNumElements();
111349cc55cSDimitry Andric 
112349cc55cSDimitry Andric   // Check that the start value is a strided constant.
113349cc55cSDimitry Andric   auto *StartVal =
114349cc55cSDimitry Andric       dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement((unsigned)0));
115349cc55cSDimitry Andric   if (!StartVal)
116349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
117349cc55cSDimitry Andric   APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
118349cc55cSDimitry Andric   ConstantInt *Prev = StartVal;
119349cc55cSDimitry Andric   for (unsigned i = 1; i != NumElts; ++i) {
120349cc55cSDimitry Andric     auto *C = dyn_cast_or_null<ConstantInt>(StartC->getAggregateElement(i));
121349cc55cSDimitry Andric     if (!C)
122349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
123349cc55cSDimitry Andric 
124349cc55cSDimitry Andric     APInt LocalStride = C->getValue() - Prev->getValue();
125349cc55cSDimitry Andric     if (i == 1)
126349cc55cSDimitry Andric       StrideVal = LocalStride;
127349cc55cSDimitry Andric     else if (StrideVal != LocalStride)
128349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
129349cc55cSDimitry Andric 
130349cc55cSDimitry Andric     Prev = C;
131349cc55cSDimitry Andric   }
132349cc55cSDimitry Andric 
133349cc55cSDimitry Andric   Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
134349cc55cSDimitry Andric 
135349cc55cSDimitry Andric   return std::make_pair(StartVal, Stride);
136349cc55cSDimitry Andric }
137349cc55cSDimitry Andric 
13804eeddc0SDimitry Andric static std::pair<Value *, Value *> matchStridedStart(Value *Start,
13904eeddc0SDimitry Andric                                                      IRBuilder<> &Builder) {
14004eeddc0SDimitry Andric   // Base case, start is a strided constant.
14104eeddc0SDimitry Andric   auto *StartC = dyn_cast<Constant>(Start);
14204eeddc0SDimitry Andric   if (StartC)
14304eeddc0SDimitry Andric     return matchStridedConstant(StartC);
14404eeddc0SDimitry Andric 
145*bdd1243dSDimitry Andric   // Base case, start is a stepvector
146*bdd1243dSDimitry Andric   if (match(Start, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
147*bdd1243dSDimitry Andric     auto *Ty = Start->getType()->getScalarType();
148*bdd1243dSDimitry Andric     return std::make_pair(ConstantInt::get(Ty, 0), ConstantInt::get(Ty, 1));
149*bdd1243dSDimitry Andric   }
150*bdd1243dSDimitry Andric 
15104eeddc0SDimitry Andric   // Not a constant, maybe it's a strided constant with a splat added to it.
15204eeddc0SDimitry Andric   auto *BO = dyn_cast<BinaryOperator>(Start);
15304eeddc0SDimitry Andric   if (!BO || BO->getOpcode() != Instruction::Add)
15404eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
15504eeddc0SDimitry Andric 
15604eeddc0SDimitry Andric   // Look for an operand that is splatted.
15704eeddc0SDimitry Andric   unsigned OtherIndex = 1;
15804eeddc0SDimitry Andric   Value *Splat = getSplatValue(BO->getOperand(0));
15904eeddc0SDimitry Andric   if (!Splat) {
16004eeddc0SDimitry Andric     Splat = getSplatValue(BO->getOperand(1));
16104eeddc0SDimitry Andric     OtherIndex = 0;
16204eeddc0SDimitry Andric   }
16304eeddc0SDimitry Andric   if (!Splat)
16404eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
16504eeddc0SDimitry Andric 
16604eeddc0SDimitry Andric   Value *Stride;
16704eeddc0SDimitry Andric   std::tie(Start, Stride) = matchStridedStart(BO->getOperand(OtherIndex),
16804eeddc0SDimitry Andric                                               Builder);
16904eeddc0SDimitry Andric   if (!Start)
17004eeddc0SDimitry Andric     return std::make_pair(nullptr, nullptr);
17104eeddc0SDimitry Andric 
17204eeddc0SDimitry Andric   // Add the splat value to the start.
17304eeddc0SDimitry Andric   Builder.SetInsertPoint(BO);
17404eeddc0SDimitry Andric   Builder.SetCurrentDebugLocation(DebugLoc());
17504eeddc0SDimitry Andric   Start = Builder.CreateAdd(Start, Splat);
17604eeddc0SDimitry Andric   return std::make_pair(Start, Stride);
17704eeddc0SDimitry Andric }
17804eeddc0SDimitry Andric 
179349cc55cSDimitry Andric // Recursively, walk about the use-def chain until we find a Phi with a strided
180349cc55cSDimitry Andric // start value. Build and update a scalar recurrence as we unwind the recursion.
181349cc55cSDimitry Andric // We also update the Stride as we unwind. Our goal is to move all of the
182349cc55cSDimitry Andric // arithmetic out of the loop.
183349cc55cSDimitry Andric bool RISCVGatherScatterLowering::matchStridedRecurrence(Value *Index, Loop *L,
184349cc55cSDimitry Andric                                                         Value *&Stride,
185349cc55cSDimitry Andric                                                         PHINode *&BasePtr,
186349cc55cSDimitry Andric                                                         BinaryOperator *&Inc,
187349cc55cSDimitry Andric                                                         IRBuilder<> &Builder) {
188349cc55cSDimitry Andric   // Our base case is a Phi.
189349cc55cSDimitry Andric   if (auto *Phi = dyn_cast<PHINode>(Index)) {
190349cc55cSDimitry Andric     // A phi node we want to perform this function on should be from the
191349cc55cSDimitry Andric     // loop header.
192349cc55cSDimitry Andric     if (Phi->getParent() != L->getHeader())
193349cc55cSDimitry Andric       return false;
194349cc55cSDimitry Andric 
195349cc55cSDimitry Andric     Value *Step, *Start;
196349cc55cSDimitry Andric     if (!matchSimpleRecurrence(Phi, Inc, Start, Step) ||
197349cc55cSDimitry Andric         Inc->getOpcode() != Instruction::Add)
198349cc55cSDimitry Andric       return false;
199349cc55cSDimitry Andric     assert(Phi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
200349cc55cSDimitry Andric     unsigned IncrementingBlock = Phi->getIncomingValue(0) == Inc ? 0 : 1;
201349cc55cSDimitry Andric     assert(Phi->getIncomingValue(IncrementingBlock) == Inc &&
202349cc55cSDimitry Andric            "Expected one operand of phi to be Inc");
203349cc55cSDimitry Andric 
204349cc55cSDimitry Andric     // Only proceed if the step is loop invariant.
205349cc55cSDimitry Andric     if (!L->isLoopInvariant(Step))
206349cc55cSDimitry Andric       return false;
207349cc55cSDimitry Andric 
208349cc55cSDimitry Andric     // Step should be a splat.
209349cc55cSDimitry Andric     Step = getSplatValue(Step);
210349cc55cSDimitry Andric     if (!Step)
211349cc55cSDimitry Andric       return false;
212349cc55cSDimitry Andric 
21304eeddc0SDimitry Andric     std::tie(Start, Stride) = matchStridedStart(Start, Builder);
214349cc55cSDimitry Andric     if (!Start)
215349cc55cSDimitry Andric       return false;
216349cc55cSDimitry Andric     assert(Stride != nullptr);
217349cc55cSDimitry Andric 
218349cc55cSDimitry Andric     // Build scalar phi and increment.
219349cc55cSDimitry Andric     BasePtr =
220349cc55cSDimitry Andric         PHINode::Create(Start->getType(), 2, Phi->getName() + ".scalar", Phi);
221349cc55cSDimitry Andric     Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->getName() + ".scalar",
222349cc55cSDimitry Andric                                     Inc);
223349cc55cSDimitry Andric     BasePtr->addIncoming(Start, Phi->getIncomingBlock(1 - IncrementingBlock));
224349cc55cSDimitry Andric     BasePtr->addIncoming(Inc, Phi->getIncomingBlock(IncrementingBlock));
225349cc55cSDimitry Andric 
226349cc55cSDimitry Andric     // Note that this Phi might be eligible for removal.
227349cc55cSDimitry Andric     MaybeDeadPHIs.push_back(Phi);
228349cc55cSDimitry Andric     return true;
229349cc55cSDimitry Andric   }
230349cc55cSDimitry Andric 
231349cc55cSDimitry Andric   // Otherwise look for binary operator.
232349cc55cSDimitry Andric   auto *BO = dyn_cast<BinaryOperator>(Index);
233349cc55cSDimitry Andric   if (!BO)
234349cc55cSDimitry Andric     return false;
235349cc55cSDimitry Andric 
236349cc55cSDimitry Andric   if (BO->getOpcode() != Instruction::Add &&
237349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Or &&
238349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Mul &&
239349cc55cSDimitry Andric       BO->getOpcode() != Instruction::Shl)
240349cc55cSDimitry Andric     return false;
241349cc55cSDimitry Andric 
242349cc55cSDimitry Andric   // Only support shift by constant.
243349cc55cSDimitry Andric   if (BO->getOpcode() == Instruction::Shl && !isa<Constant>(BO->getOperand(1)))
244349cc55cSDimitry Andric     return false;
245349cc55cSDimitry Andric 
246349cc55cSDimitry Andric   // We need to be able to treat Or as Add.
247349cc55cSDimitry Andric   if (BO->getOpcode() == Instruction::Or &&
248349cc55cSDimitry Andric       !haveNoCommonBitsSet(BO->getOperand(0), BO->getOperand(1), *DL))
249349cc55cSDimitry Andric     return false;
250349cc55cSDimitry Andric 
251349cc55cSDimitry Andric   // We should have one operand in the loop and one splat.
252349cc55cSDimitry Andric   Value *OtherOp;
253349cc55cSDimitry Andric   if (isa<Instruction>(BO->getOperand(0)) &&
254349cc55cSDimitry Andric       L->contains(cast<Instruction>(BO->getOperand(0)))) {
255349cc55cSDimitry Andric     Index = cast<Instruction>(BO->getOperand(0));
256349cc55cSDimitry Andric     OtherOp = BO->getOperand(1);
257349cc55cSDimitry Andric   } else if (isa<Instruction>(BO->getOperand(1)) &&
258349cc55cSDimitry Andric              L->contains(cast<Instruction>(BO->getOperand(1)))) {
259349cc55cSDimitry Andric     Index = cast<Instruction>(BO->getOperand(1));
260349cc55cSDimitry Andric     OtherOp = BO->getOperand(0);
261349cc55cSDimitry Andric   } else {
262349cc55cSDimitry Andric     return false;
263349cc55cSDimitry Andric   }
264349cc55cSDimitry Andric 
265349cc55cSDimitry Andric   // Make sure other op is loop invariant.
266349cc55cSDimitry Andric   if (!L->isLoopInvariant(OtherOp))
267349cc55cSDimitry Andric     return false;
268349cc55cSDimitry Andric 
269349cc55cSDimitry Andric   // Make sure we have a splat.
270349cc55cSDimitry Andric   Value *SplatOp = getSplatValue(OtherOp);
271349cc55cSDimitry Andric   if (!SplatOp)
272349cc55cSDimitry Andric     return false;
273349cc55cSDimitry Andric 
274349cc55cSDimitry Andric   // Recurse up the use-def chain.
275349cc55cSDimitry Andric   if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
276349cc55cSDimitry Andric     return false;
277349cc55cSDimitry Andric 
278349cc55cSDimitry Andric   // Locate the Step and Start values from the recurrence.
279349cc55cSDimitry Andric   unsigned StepIndex = Inc->getOperand(0) == BasePtr ? 1 : 0;
280349cc55cSDimitry Andric   unsigned StartBlock = BasePtr->getOperand(0) == Inc ? 1 : 0;
281349cc55cSDimitry Andric   Value *Step = Inc->getOperand(StepIndex);
282349cc55cSDimitry Andric   Value *Start = BasePtr->getOperand(StartBlock);
283349cc55cSDimitry Andric 
284349cc55cSDimitry Andric   // We need to adjust the start value in the preheader.
285349cc55cSDimitry Andric   Builder.SetInsertPoint(
286349cc55cSDimitry Andric       BasePtr->getIncomingBlock(StartBlock)->getTerminator());
287349cc55cSDimitry Andric   Builder.SetCurrentDebugLocation(DebugLoc());
288349cc55cSDimitry Andric 
289349cc55cSDimitry Andric   switch (BO->getOpcode()) {
290349cc55cSDimitry Andric   default:
291349cc55cSDimitry Andric     llvm_unreachable("Unexpected opcode!");
292349cc55cSDimitry Andric   case Instruction::Add:
293349cc55cSDimitry Andric   case Instruction::Or: {
294349cc55cSDimitry Andric     // An add only affects the start value. It's ok to do this for Or because
295349cc55cSDimitry Andric     // we already checked that there are no common set bits.
296349cc55cSDimitry Andric 
297349cc55cSDimitry Andric     // If the start value is Zero, just take the SplatOp.
298349cc55cSDimitry Andric     if (isa<ConstantInt>(Start) && cast<ConstantInt>(Start)->isZero())
299349cc55cSDimitry Andric       Start = SplatOp;
300349cc55cSDimitry Andric     else
301349cc55cSDimitry Andric       Start = Builder.CreateAdd(Start, SplatOp, "start");
302349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
303349cc55cSDimitry Andric     break;
304349cc55cSDimitry Andric   }
305349cc55cSDimitry Andric   case Instruction::Mul: {
306349cc55cSDimitry Andric     // If the start is zero we don't need to multiply.
307349cc55cSDimitry Andric     if (!isa<ConstantInt>(Start) || !cast<ConstantInt>(Start)->isZero())
308349cc55cSDimitry Andric       Start = Builder.CreateMul(Start, SplatOp, "start");
309349cc55cSDimitry Andric 
310349cc55cSDimitry Andric     Step = Builder.CreateMul(Step, SplatOp, "step");
311349cc55cSDimitry Andric 
312349cc55cSDimitry Andric     // If the Stride is 1 just take the SplatOpt.
313349cc55cSDimitry Andric     if (isa<ConstantInt>(Stride) && cast<ConstantInt>(Stride)->isOne())
314349cc55cSDimitry Andric       Stride = SplatOp;
315349cc55cSDimitry Andric     else
316349cc55cSDimitry Andric       Stride = Builder.CreateMul(Stride, SplatOp, "stride");
317349cc55cSDimitry Andric     Inc->setOperand(StepIndex, Step);
318349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
319349cc55cSDimitry Andric     break;
320349cc55cSDimitry Andric   }
321349cc55cSDimitry Andric   case Instruction::Shl: {
322349cc55cSDimitry Andric     // If the start is zero we don't need to shift.
323349cc55cSDimitry Andric     if (!isa<ConstantInt>(Start) || !cast<ConstantInt>(Start)->isZero())
324349cc55cSDimitry Andric       Start = Builder.CreateShl(Start, SplatOp, "start");
325349cc55cSDimitry Andric     Step = Builder.CreateShl(Step, SplatOp, "step");
326349cc55cSDimitry Andric     Stride = Builder.CreateShl(Stride, SplatOp, "stride");
327349cc55cSDimitry Andric     Inc->setOperand(StepIndex, Step);
328349cc55cSDimitry Andric     BasePtr->setIncomingValue(StartBlock, Start);
329349cc55cSDimitry Andric     break;
330349cc55cSDimitry Andric   }
331349cc55cSDimitry Andric   }
332349cc55cSDimitry Andric 
333349cc55cSDimitry Andric   return true;
334349cc55cSDimitry Andric }
335349cc55cSDimitry Andric 
336349cc55cSDimitry Andric std::pair<Value *, Value *>
337349cc55cSDimitry Andric RISCVGatherScatterLowering::determineBaseAndStride(GetElementPtrInst *GEP,
338349cc55cSDimitry Andric                                                    IRBuilder<> &Builder) {
339349cc55cSDimitry Andric 
34081ad6265SDimitry Andric   auto I = StridedAddrs.find(GEP);
34181ad6265SDimitry Andric   if (I != StridedAddrs.end())
34281ad6265SDimitry Andric     return I->second;
34381ad6265SDimitry Andric 
344349cc55cSDimitry Andric   SmallVector<Value *, 2> Ops(GEP->operands());
345349cc55cSDimitry Andric 
346349cc55cSDimitry Andric   // Base pointer needs to be a scalar.
347349cc55cSDimitry Andric   if (Ops[0]->getType()->isVectorTy())
348349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
349349cc55cSDimitry Andric 
350*bdd1243dSDimitry Andric   std::optional<unsigned> VecOperand;
351349cc55cSDimitry Andric   unsigned TypeScale = 0;
352349cc55cSDimitry Andric 
353349cc55cSDimitry Andric   // Look for a vector operand and scale.
354349cc55cSDimitry Andric   gep_type_iterator GTI = gep_type_begin(GEP);
355349cc55cSDimitry Andric   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
356349cc55cSDimitry Andric     if (!Ops[i]->getType()->isVectorTy())
357349cc55cSDimitry Andric       continue;
358349cc55cSDimitry Andric 
359349cc55cSDimitry Andric     if (VecOperand)
360349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
361349cc55cSDimitry Andric 
362349cc55cSDimitry Andric     VecOperand = i;
363349cc55cSDimitry Andric 
364349cc55cSDimitry Andric     TypeSize TS = DL->getTypeAllocSize(GTI.getIndexedType());
365349cc55cSDimitry Andric     if (TS.isScalable())
366349cc55cSDimitry Andric       return std::make_pair(nullptr, nullptr);
367349cc55cSDimitry Andric 
368*bdd1243dSDimitry Andric     TypeScale = TS.getFixedValue();
369349cc55cSDimitry Andric   }
370349cc55cSDimitry Andric 
371349cc55cSDimitry Andric   // We need to find a vector index to simplify.
372349cc55cSDimitry Andric   if (!VecOperand)
373349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
374349cc55cSDimitry Andric 
375349cc55cSDimitry Andric   // We can't extract the stride if the arithmetic is done at a different size
376349cc55cSDimitry Andric   // than the pointer type. Adding the stride later may not wrap correctly.
377349cc55cSDimitry Andric   // Technically we could handle wider indices, but I don't expect that in
378349cc55cSDimitry Andric   // practice.
379349cc55cSDimitry Andric   Value *VecIndex = Ops[*VecOperand];
380349cc55cSDimitry Andric   Type *VecIntPtrTy = DL->getIntPtrType(GEP->getType());
381349cc55cSDimitry Andric   if (VecIndex->getType() != VecIntPtrTy)
382349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
383349cc55cSDimitry Andric 
384*bdd1243dSDimitry Andric   // Handle the non-recursive case.  This is what we see if the vectorizer
385*bdd1243dSDimitry Andric   // decides to use a scalar IV + vid on demand instead of a vector IV.
386*bdd1243dSDimitry Andric   auto [Start, Stride] = matchStridedStart(VecIndex, Builder);
387*bdd1243dSDimitry Andric   if (Start) {
388*bdd1243dSDimitry Andric     assert(Stride);
389*bdd1243dSDimitry Andric     Builder.SetInsertPoint(GEP);
390*bdd1243dSDimitry Andric 
391*bdd1243dSDimitry Andric     // Replace the vector index with the scalar start and build a scalar GEP.
392*bdd1243dSDimitry Andric     Ops[*VecOperand] = Start;
393*bdd1243dSDimitry Andric     Type *SourceTy = GEP->getSourceElementType();
394*bdd1243dSDimitry Andric     Value *BasePtr =
395*bdd1243dSDimitry Andric         Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
396*bdd1243dSDimitry Andric 
397*bdd1243dSDimitry Andric     // Convert stride to pointer size if needed.
398*bdd1243dSDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
399*bdd1243dSDimitry Andric     assert(Stride->getType() == IntPtrTy && "Unexpected type");
400*bdd1243dSDimitry Andric 
401*bdd1243dSDimitry Andric     // Scale the stride by the size of the indexed type.
402*bdd1243dSDimitry Andric     if (TypeScale != 1)
403*bdd1243dSDimitry Andric       Stride = Builder.CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
404*bdd1243dSDimitry Andric 
405*bdd1243dSDimitry Andric     auto P = std::make_pair(BasePtr, Stride);
406*bdd1243dSDimitry Andric     StridedAddrs[GEP] = P;
407*bdd1243dSDimitry Andric     return P;
408*bdd1243dSDimitry Andric   }
409*bdd1243dSDimitry Andric 
410*bdd1243dSDimitry Andric   // Make sure we're in a loop and that has a pre-header and a single latch.
411*bdd1243dSDimitry Andric   Loop *L = LI->getLoopFor(GEP->getParent());
412*bdd1243dSDimitry Andric   if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
413*bdd1243dSDimitry Andric     return std::make_pair(nullptr, nullptr);
414*bdd1243dSDimitry Andric 
415349cc55cSDimitry Andric   BinaryOperator *Inc;
416349cc55cSDimitry Andric   PHINode *BasePhi;
417349cc55cSDimitry Andric   if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
418349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
419349cc55cSDimitry Andric 
420349cc55cSDimitry Andric   assert(BasePhi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
421349cc55cSDimitry Andric   unsigned IncrementingBlock = BasePhi->getOperand(0) == Inc ? 0 : 1;
422349cc55cSDimitry Andric   assert(BasePhi->getIncomingValue(IncrementingBlock) == Inc &&
423349cc55cSDimitry Andric          "Expected one operand of phi to be Inc");
424349cc55cSDimitry Andric 
425349cc55cSDimitry Andric   Builder.SetInsertPoint(GEP);
426349cc55cSDimitry Andric 
427349cc55cSDimitry Andric   // Replace the vector index with the scalar phi and build a scalar GEP.
428349cc55cSDimitry Andric   Ops[*VecOperand] = BasePhi;
429349cc55cSDimitry Andric   Type *SourceTy = GEP->getSourceElementType();
430349cc55cSDimitry Andric   Value *BasePtr =
431*bdd1243dSDimitry Andric       Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
432349cc55cSDimitry Andric 
433349cc55cSDimitry Andric   // Final adjustments to stride should go in the start block.
434349cc55cSDimitry Andric   Builder.SetInsertPoint(
435349cc55cSDimitry Andric       BasePhi->getIncomingBlock(1 - IncrementingBlock)->getTerminator());
436349cc55cSDimitry Andric 
437349cc55cSDimitry Andric   // Convert stride to pointer size if needed.
438349cc55cSDimitry Andric   Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
439349cc55cSDimitry Andric   assert(Stride->getType() == IntPtrTy && "Unexpected type");
440349cc55cSDimitry Andric 
441349cc55cSDimitry Andric   // Scale the stride by the size of the indexed type.
442349cc55cSDimitry Andric   if (TypeScale != 1)
443349cc55cSDimitry Andric     Stride = Builder.CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
444349cc55cSDimitry Andric 
44581ad6265SDimitry Andric   auto P = std::make_pair(BasePtr, Stride);
44681ad6265SDimitry Andric   StridedAddrs[GEP] = P;
44781ad6265SDimitry Andric   return P;
448349cc55cSDimitry Andric }
449349cc55cSDimitry Andric 
450349cc55cSDimitry Andric bool RISCVGatherScatterLowering::tryCreateStridedLoadStore(IntrinsicInst *II,
451349cc55cSDimitry Andric                                                            Type *DataType,
452349cc55cSDimitry Andric                                                            Value *Ptr,
453349cc55cSDimitry Andric                                                            Value *AlignOp) {
454349cc55cSDimitry Andric   // Make sure the operation will be supported by the backend.
455349cc55cSDimitry Andric   if (!isLegalTypeAndAlignment(DataType, AlignOp))
456349cc55cSDimitry Andric     return false;
457349cc55cSDimitry Andric 
458349cc55cSDimitry Andric   // Pointer should be a GEP.
459349cc55cSDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
460349cc55cSDimitry Andric   if (!GEP)
461349cc55cSDimitry Andric     return false;
462349cc55cSDimitry Andric 
463349cc55cSDimitry Andric   IRBuilder<> Builder(GEP);
464349cc55cSDimitry Andric 
465349cc55cSDimitry Andric   Value *BasePtr, *Stride;
466349cc55cSDimitry Andric   std::tie(BasePtr, Stride) = determineBaseAndStride(GEP, Builder);
467349cc55cSDimitry Andric   if (!BasePtr)
468349cc55cSDimitry Andric     return false;
469349cc55cSDimitry Andric   assert(Stride != nullptr);
470349cc55cSDimitry Andric 
471349cc55cSDimitry Andric   Builder.SetInsertPoint(II);
472349cc55cSDimitry Andric 
473349cc55cSDimitry Andric   CallInst *Call;
474349cc55cSDimitry Andric   if (II->getIntrinsicID() == Intrinsic::masked_gather)
475349cc55cSDimitry Andric     Call = Builder.CreateIntrinsic(
476349cc55cSDimitry Andric         Intrinsic::riscv_masked_strided_load,
477349cc55cSDimitry Andric         {DataType, BasePtr->getType(), Stride->getType()},
478349cc55cSDimitry Andric         {II->getArgOperand(3), BasePtr, Stride, II->getArgOperand(2)});
479349cc55cSDimitry Andric   else
480349cc55cSDimitry Andric     Call = Builder.CreateIntrinsic(
481349cc55cSDimitry Andric         Intrinsic::riscv_masked_strided_store,
482349cc55cSDimitry Andric         {DataType, BasePtr->getType(), Stride->getType()},
483349cc55cSDimitry Andric         {II->getArgOperand(0), BasePtr, Stride, II->getArgOperand(3)});
484349cc55cSDimitry Andric 
485349cc55cSDimitry Andric   Call->takeName(II);
486349cc55cSDimitry Andric   II->replaceAllUsesWith(Call);
487349cc55cSDimitry Andric   II->eraseFromParent();
488349cc55cSDimitry Andric 
489349cc55cSDimitry Andric   if (GEP->use_empty())
490349cc55cSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(GEP);
491349cc55cSDimitry Andric 
492349cc55cSDimitry Andric   return true;
493349cc55cSDimitry Andric }
494349cc55cSDimitry Andric 
495349cc55cSDimitry Andric bool RISCVGatherScatterLowering::runOnFunction(Function &F) {
496349cc55cSDimitry Andric   if (skipFunction(F))
497349cc55cSDimitry Andric     return false;
498349cc55cSDimitry Andric 
499349cc55cSDimitry Andric   auto &TPC = getAnalysis<TargetPassConfig>();
500349cc55cSDimitry Andric   auto &TM = TPC.getTM<RISCVTargetMachine>();
501349cc55cSDimitry Andric   ST = &TM.getSubtarget<RISCVSubtarget>(F);
502349cc55cSDimitry Andric   if (!ST->hasVInstructions() || !ST->useRVVForFixedLengthVectors())
503349cc55cSDimitry Andric     return false;
504349cc55cSDimitry Andric 
505349cc55cSDimitry Andric   TLI = ST->getTargetLowering();
506349cc55cSDimitry Andric   DL = &F.getParent()->getDataLayout();
507349cc55cSDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
508349cc55cSDimitry Andric 
50981ad6265SDimitry Andric   StridedAddrs.clear();
51081ad6265SDimitry Andric 
511349cc55cSDimitry Andric   SmallVector<IntrinsicInst *, 4> Gathers;
512349cc55cSDimitry Andric   SmallVector<IntrinsicInst *, 4> Scatters;
513349cc55cSDimitry Andric 
514349cc55cSDimitry Andric   bool Changed = false;
515349cc55cSDimitry Andric 
516349cc55cSDimitry Andric   for (BasicBlock &BB : F) {
517349cc55cSDimitry Andric     for (Instruction &I : BB) {
518349cc55cSDimitry Andric       IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
519*bdd1243dSDimitry Andric       if (II && II->getIntrinsicID() == Intrinsic::masked_gather) {
520349cc55cSDimitry Andric         Gathers.push_back(II);
521*bdd1243dSDimitry Andric       } else if (II && II->getIntrinsicID() == Intrinsic::masked_scatter) {
522349cc55cSDimitry Andric         Scatters.push_back(II);
523349cc55cSDimitry Andric       }
524349cc55cSDimitry Andric     }
525349cc55cSDimitry Andric   }
526349cc55cSDimitry Andric 
527349cc55cSDimitry Andric   // Rewrite gather/scatter to form strided load/store if possible.
528349cc55cSDimitry Andric   for (auto *II : Gathers)
529349cc55cSDimitry Andric     Changed |= tryCreateStridedLoadStore(
530349cc55cSDimitry Andric         II, II->getType(), II->getArgOperand(0), II->getArgOperand(1));
531349cc55cSDimitry Andric   for (auto *II : Scatters)
532349cc55cSDimitry Andric     Changed |=
533349cc55cSDimitry Andric         tryCreateStridedLoadStore(II, II->getArgOperand(0)->getType(),
534349cc55cSDimitry Andric                                   II->getArgOperand(1), II->getArgOperand(2));
535349cc55cSDimitry Andric 
536349cc55cSDimitry Andric   // Remove any dead phis.
537349cc55cSDimitry Andric   while (!MaybeDeadPHIs.empty()) {
538349cc55cSDimitry Andric     if (auto *Phi = dyn_cast_or_null<PHINode>(MaybeDeadPHIs.pop_back_val()))
539349cc55cSDimitry Andric       RecursivelyDeleteDeadPHINode(Phi);
540349cc55cSDimitry Andric   }
541349cc55cSDimitry Andric 
542349cc55cSDimitry Andric   return Changed;
543349cc55cSDimitry Andric }
544