LLVM  10.0.0
MVEGatherScatterLowering.cpp
Go to the documentation of this file.
1 //===- MVEGatherScatterLowering.cpp - Gather/Scatter lowering -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// This pass custom lowers llvm.gather and llvm.scatter instructions to
10 /// arm.mve.gather and arm.mve.scatter intrinsics, optimising the code to
11 /// produce a better final result as we go.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMSubtarget.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/IntrinsicsARM.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Casting.h"
40 #include <algorithm>
41 #include <cassert>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "mve-gather-scatter-lowering"
46 
48  "enable-arm-maskedgatscat", cl::Hidden, cl::init(false),
49  cl::desc("Enable the generation of masked gathers and scatters"));
50 
51 namespace {
52 
53 class MVEGatherScatterLowering : public FunctionPass {
54 public:
55  static char ID; // Pass identification, replacement for typeid
56 
57  explicit MVEGatherScatterLowering() : FunctionPass(ID) {
59  }
60 
61  bool runOnFunction(Function &F) override;
62 
63  StringRef getPassName() const override {
64  return "MVE gather/scatter lowering";
65  }
66 
67  void getAnalysisUsage(AnalysisUsage &AU) const override {
68  AU.setPreservesCFG();
71  }
72 
73 private:
74  // Check this is a valid gather with correct alignment
75  bool isLegalTypeAndAlignment(unsigned NumElements, unsigned ElemSize,
76  unsigned Alignment);
77  // Check whether Ptr is hidden behind a bitcast and look through it
78  void lookThroughBitcast(Value *&Ptr);
79  // Check for a getelementptr and deduce base and offsets from it, on success
80  // returning the base directly and the offsets indirectly using the Offsets
81  // argument
82  Value *checkGEP(Value *&Offsets, Type *Ty, Value *Ptr, IRBuilder<> Builder);
83 
84  bool lowerGather(IntrinsicInst *I);
85  // Create a gather from a base + vector of offsets
86  Value *tryCreateMaskedGatherOffset(IntrinsicInst *I, Value *Ptr,
87  IRBuilder<> Builder);
88  // Create a gather from a vector of pointers
89  Value *tryCreateMaskedGatherBase(IntrinsicInst *I, Value *Ptr,
90  IRBuilder<> Builder);
91 };
92 
93 } // end anonymous namespace
94 
96 
97 INITIALIZE_PASS(MVEGatherScatterLowering, DEBUG_TYPE,
98  "MVE gather/scattering lowering pass", false, false)
99 
101  return new MVEGatherScatterLowering();
102 }
103 
104 bool MVEGatherScatterLowering::isLegalTypeAndAlignment(unsigned NumElements,
105  unsigned ElemSize,
106  unsigned Alignment) {
107  // Do only allow non-extending gathers for now
108  if (((NumElements == 4 && ElemSize == 32) ||
109  (NumElements == 8 && ElemSize == 16) ||
110  (NumElements == 16 && ElemSize == 8)) &&
111  ElemSize / 8 <= Alignment)
112  return true;
113  LLVM_DEBUG(dbgs() << "masked gathers: instruction does not have valid "
114  << "alignment or vector type \n");
115  return false;
116 }
117 
118 Value *MVEGatherScatterLowering::checkGEP(Value *&Offsets, Type *Ty, Value *Ptr,
119  IRBuilder<> Builder) {
121  if (!GEP) {
122  LLVM_DEBUG(dbgs() << "masked gathers: no getelementpointer found\n");
123  return nullptr;
124  }
125  LLVM_DEBUG(dbgs() << "masked gathers: getelementpointer found. Loading"
126  << " from base + vector of offsets\n");
127  Value *GEPPtr = GEP->getPointerOperand();
128  if (GEPPtr->getType()->isVectorTy()) {
129  LLVM_DEBUG(dbgs() << "masked gathers: gather from a vector of pointers"
130  << " hidden behind a getelementptr currently not"
131  << " supported. Expanding.\n");
132  return nullptr;
133  }
134  if (GEP->getNumOperands() != 2) {
135  LLVM_DEBUG(dbgs() << "masked gathers: getelementptr with too many"
136  << " operands. Expanding.\n");
137  return nullptr;
138  }
139  Offsets = GEP->getOperand(1);
140  // SExt offsets inside masked gathers are not permitted by the architecture;
141  // we therefore can't fold them
142  if (ZExtInst *ZextOffs = dyn_cast<ZExtInst>(Offsets))
143  Offsets = ZextOffs->getOperand(0);
144  Type *OffsType = VectorType::getInteger(cast<VectorType>(Ty));
145  // If the offset we found does not have the type the intrinsic expects,
146  // i.e., the same type as the gather itself, we need to convert it (only i
147  // types) or fall back to expanding the gather
148  if (OffsType != Offsets->getType()) {
149  if (OffsType->getScalarSizeInBits() >
150  Offsets->getType()->getScalarSizeInBits()) {
151  LLVM_DEBUG(dbgs() << "masked gathers: extending offsets\n");
152  Offsets = Builder.CreateZExt(Offsets, OffsType, "");
153  } else {
154  LLVM_DEBUG(dbgs() << "masked gathers: no correct offset type. Can't"
155  << " create masked gather\n");
156  return nullptr;
157  }
158  }
159  // If none of the checks failed, return the gep's base pointer
160  return GEPPtr;
161 }
162 
163 void MVEGatherScatterLowering::lookThroughBitcast(Value *&Ptr) {
164  // Look through bitcast instruction if #elements is the same
165  if (auto *BitCast = dyn_cast<BitCastInst>(Ptr)) {
166  Type *BCTy = BitCast->getType();
167  Type *BCSrcTy = BitCast->getOperand(0)->getType();
168  if (BCTy->getVectorNumElements() == BCSrcTy->getVectorNumElements()) {
169  LLVM_DEBUG(dbgs() << "masked gathers: looking through bitcast\n");
170  Ptr = BitCast->getOperand(0);
171  }
172  }
173 }
174 
175 bool MVEGatherScatterLowering::lowerGather(IntrinsicInst *I) {
176  using namespace PatternMatch;
177  LLVM_DEBUG(dbgs() << "masked gathers: checking transform preconditions\n");
178 
179  // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
180  // Attempt to turn the masked gather in I into a MVE intrinsic
181  // Potentially optimising the addressing modes as we do so.
182  Type *Ty = I->getType();
183  Value *Ptr = I->getArgOperand(0);
184  unsigned Alignment = cast<ConstantInt>(I->getArgOperand(1))->getZExtValue();
185  Value *Mask = I->getArgOperand(2);
186  Value *PassThru = I->getArgOperand(3);
187 
188  if (!isLegalTypeAndAlignment(Ty->getVectorNumElements(),
189  Ty->getScalarSizeInBits(), Alignment))
190  return false;
191  lookThroughBitcast(Ptr);
192  assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
193 
194  IRBuilder<> Builder(I->getContext());
195  Builder.SetInsertPoint(I);
196  Builder.SetCurrentDebugLocation(I->getDebugLoc());
197  Value *Load = tryCreateMaskedGatherOffset(I, Ptr, Builder);
198  if (!Load)
199  Load = tryCreateMaskedGatherBase(I, Ptr, Builder);
200  if (!Load)
201  return false;
202 
203  if (!isa<UndefValue>(PassThru) && !match(PassThru, m_Zero())) {
204  LLVM_DEBUG(dbgs() << "masked gathers: found non-trivial passthru - "
205  << "creating select\n");
206  Load = Builder.CreateSelect(Mask, Load, PassThru);
207  }
208 
209  LLVM_DEBUG(dbgs() << "masked gathers: successfully built masked gather\n");
210  I->replaceAllUsesWith(Load);
211  I->eraseFromParent();
212  return true;
213 }
214 
215 Value *MVEGatherScatterLowering::tryCreateMaskedGatherBase(
216  IntrinsicInst *I, Value *Ptr, IRBuilder<> Builder) {
217  using namespace PatternMatch;
218  LLVM_DEBUG(dbgs() << "masked gathers: loading from vector of pointers\n");
219  Type *Ty = I->getType();
220  if (Ty->getVectorNumElements() != 4)
221  // Can't build an intrinsic for this
222  return nullptr;
223  Value *Mask = I->getArgOperand(2);
224  if (match(Mask, m_One()))
225  return Builder.CreateIntrinsic(Intrinsic::arm_mve_vldr_gather_base,
226  {Ty, Ptr->getType()},
227  {Ptr, Builder.getInt32(0)});
228  else
229  return Builder.CreateIntrinsic(
230  Intrinsic::arm_mve_vldr_gather_base_predicated,
231  {Ty, Ptr->getType(), Mask->getType()},
232  {Ptr, Builder.getInt32(0), Mask});
233 }
234 
235 Value *MVEGatherScatterLowering::tryCreateMaskedGatherOffset(
236  IntrinsicInst *I, Value *Ptr, IRBuilder<> Builder) {
237  using namespace PatternMatch;
238  Type *Ty = I->getType();
239  Value *Offsets;
240  Value *BasePtr = checkGEP(Offsets, Ty, Ptr, Builder);
241  if (!BasePtr)
242  return nullptr;
243 
244  unsigned Scale;
245  int GEPElemSize =
247  int ResultElemSize = Ty->getScalarSizeInBits();
248  // This can be a 32bit load scaled by 4, a 16bit load scaled by 2, or a
249  // 8bit, 16bit or 32bit load scaled by 1
250  if (GEPElemSize == 32 && ResultElemSize == 32) {
251  Scale = 2;
252  } else if (GEPElemSize == 16 && ResultElemSize == 16) {
253  Scale = 1;
254  } else if (GEPElemSize == 8) {
255  Scale = 0;
256  } else {
257  LLVM_DEBUG(dbgs() << "masked gathers: incorrect scale for load. Can't"
258  << " create masked gather\n");
259  return nullptr;
260  }
261 
262  Value *Mask = I->getArgOperand(2);
263  if (!match(Mask, m_One()))
264  return Builder.CreateIntrinsic(
265  Intrinsic::arm_mve_vldr_gather_offset_predicated,
266  {Ty, BasePtr->getType(), Offsets->getType(), Mask->getType()},
267  {BasePtr, Offsets, Builder.getInt32(Ty->getScalarSizeInBits()),
268  Builder.getInt32(Scale), Builder.getInt32(1), Mask});
269  else
270  return Builder.CreateIntrinsic(
271  Intrinsic::arm_mve_vldr_gather_offset,
272  {Ty, BasePtr->getType(), Offsets->getType()},
273  {BasePtr, Offsets, Builder.getInt32(Ty->getScalarSizeInBits()),
274  Builder.getInt32(Scale), Builder.getInt32(1)});
275 }
276 
279  return false;
280  auto &TPC = getAnalysis<TargetPassConfig>();
281  auto &TM = TPC.getTM<TargetMachine>();
282  auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
283  if (!ST->hasMVEIntegerOps())
284  return false;
286  for (BasicBlock &BB : F) {
287  for (Instruction &I : BB) {
289  if (II && II->getIntrinsicID() == Intrinsic::masked_gather)
290  Gathers.push_back(II);
291  }
292  }
293 
294  if (Gathers.empty())
295  return false;
296 
297  for (IntrinsicInst *I : Gathers)
298  lowerGather(I);
299 
300  return true;
301 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:78
void initializeMVEGatherScatterLoweringPass(PassRegistry &)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:426
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This class represents zero extension of integer types.
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1157
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
F(f)
Hexagon Common GEP
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1246
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:48
AnalysisUsage & addRequired()
Type * getPointerElementType() const
Definition: Type.h:381
Target-Independent Code Generator Pass Configuration Options.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:96
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:156
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2009
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:132
Value * getOperand(unsigned i) const
Definition: User.h:169
Pass * createMVEGatherScatterLoweringPass()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:892
static bool runOnFunction(Function &F, bool PostInlining)
INITIALIZE_PASS(MVEGatherScatterLowering, DEBUG_TYPE, "MVE gather/scattering lowering pass", false, false) Pass *llvm
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:2498
#define DEBUG_TYPE
Represent the analysis usage information of a pass.
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type...
Definition: DerivedTypes.h:468
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
unsigned getNumOperands() const
Definition: User.h:191
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:134
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type *> Types, ArrayRef< Value *> Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with args, mangled using Types.
Definition: IRBuilder.cpp:756
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:355
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:566
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:331
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:405
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
cl::opt< bool > EnableMaskedGatherScatters("enable-arm-maskedgatscat", cl::Hidden, cl::init(false), cl::desc("Enable the generation of masked gathers and scatters"))
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
This pass exposes codegen information to IR-level passes.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
This file describes how to lower LLVM code to machine code.