MLIR  20.0.0git
OptimizeSharedMemory.cpp
Go to the documentation of this file.
1 //===- OptimizeSharedMemory.cpp - MLIR NVGPU pass implementation ----------===//
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 file implements transforms to optimize accesses to shared memory.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 
26 namespace mlir {
27 namespace nvgpu {
28 #define GEN_PASS_DEF_OPTIMIZESHAREDMEMORY
29 #include "mlir/Dialect/NVGPU/Transforms/Passes.h.inc"
30 } // namespace nvgpu
31 } // namespace mlir
32 
33 using namespace mlir;
34 using namespace mlir::nvgpu;
35 
36 /// The size of a shared memory line according to NV documentation.
37 constexpr int64_t kSharedMemoryLineSizeBytes = 128;
38 /// We optimize for 128bit accesses, but this can be made an argument in the
39 /// future.
40 constexpr int64_t kDefaultVectorSizeBits = 128;
41 
42 /// Uses `srcIndexValue` to permute `tgtIndexValue` via
43 /// `result = xor(floordiv(srcIdxVal,permuteEveryN),
44 /// floordiv(tgtIdxVal,vectorSize)))
45 /// + tgtIdxVal % vectorSize`
46 /// This is done using an optimized sequence of `arith` operations.
48  ArrayRef<Value> indices, MemRefType memrefTy,
49  int64_t srcDim, int64_t tgtDim) {
50  // Adjust the src index to change how often the permutation changes
51  // if necessary.
52  Value src = indices[srcDim];
53 
54  // We only want to permute every N iterations of the target dim where N is
55  // ceil(sharedMemoryLineSizeBytes / dimSizeBytes(tgtDim)).
56  const int64_t permuteEveryN = std::max<int64_t>(
57  1, kSharedMemoryLineSizeBytes / ((memrefTy.getDimSize(tgtDim) *
58  memrefTy.getElementTypeBitWidth()) /
59  8));
60 
61  // clang-format off
62  // Index bit representation (b0 = least significant bit) for dim(1)
63  // of a `memref<?x?xDT>` is as follows:
64  // N := log2(128/elementSizeBits)
65  // M := log2(dimSize(1))
66  // then
67  // bits[0:N] = sub-vector element offset
68  // bits[N:M] = vector index
69  // clang-format on
70  int64_t n =
71  llvm::Log2_64(kDefaultVectorSizeBits / memrefTy.getElementTypeBitWidth());
72  int64_t m = llvm::Log2_64(memrefTy.getDimSize(tgtDim));
73 
74  // Capture bits[0:(M-N)] of src by first creating a (M-N) mask.
75  int64_t mask = (1LL << (m - n)) - 1;
76  if (permuteEveryN > 1)
77  mask = mask << llvm::Log2_64(permuteEveryN);
78  Value srcBits = b.create<arith::ConstantIndexOp>(loc, mask);
79  srcBits = b.create<arith::AndIOp>(loc, src, srcBits);
80 
81  // Use the src bits to permute the target bits b[N:M] containing the
82  // vector offset.
83  if (permuteEveryN > 1) {
84  int64_t shlBits = n - llvm::Log2_64(permuteEveryN);
85  if (shlBits > 0) {
86  Value finalShiftVal = b.create<arith::ConstantIndexOp>(loc, shlBits);
87  srcBits = b.createOrFold<arith::ShLIOp>(loc, srcBits, finalShiftVal);
88  } else if (shlBits < 0) {
89  Value finalShiftVal = b.create<arith::ConstantIndexOp>(loc, -1 * shlBits);
90  srcBits = b.createOrFold<arith::ShRUIOp>(loc, srcBits, finalShiftVal);
91  }
92  } else {
93  Value finalShiftVal = b.create<arith::ConstantIndexOp>(loc, n);
94  srcBits = b.createOrFold<arith::ShLIOp>(loc, srcBits, finalShiftVal);
95  }
96 
97  Value permutedVectorIdx =
98  b.create<arith::XOrIOp>(loc, indices[tgtDim], srcBits);
99  return permutedVectorIdx;
100 }
101 
102 static void transformIndices(OpBuilder &builder, Location loc,
103  SmallVector<Value, 4> &indices,
104  MemRefType memrefTy, int64_t srcDim,
105  int64_t tgtDim) {
106  indices[tgtDim] =
107  permuteVectorOffset(builder, loc, indices, memrefTy, srcDim, tgtDim);
108 }
109 
110 /// Return all operations within `parentOp` that read from or write to
111 /// `shmMemRef`.
112 static LogicalResult
113 getShmReadAndWriteOps(Operation *parentOp, Value shmMemRef,
115  SmallVector<Operation *, 16> &writeOps) {
116  parentOp->walk([&](Operation *op) {
117  MemoryEffectOpInterface iface = dyn_cast<MemoryEffectOpInterface>(op);
118  if (!iface)
119  return;
120  std::optional<MemoryEffects::EffectInstance> effect =
121  iface.getEffectOnValue<MemoryEffects::Read>(shmMemRef);
122  if (effect) {
123  readOps.push_back(op);
124  return;
125  }
126  effect = iface.getEffectOnValue<MemoryEffects::Write>(shmMemRef);
127  if (effect)
128  writeOps.push_back(op);
129  });
130 
131  // Restrict to a supported set of ops. We also require at least 2D access,
132  // although this could be relaxed.
133  if (llvm::any_of(readOps, [](Operation *op) {
134  return !isa<memref::LoadOp, vector::LoadOp, nvgpu::LdMatrixOp>(op) ||
135  getIndices(op).size() < 2;
136  }))
137  return failure();
138  if (llvm::any_of(writeOps, [](Operation *op) {
139  return !isa<memref::StoreOp, vector::StoreOp, nvgpu::DeviceAsyncCopyOp>(
140  op) ||
141  getIndices(op).size() < 2;
142  }))
143  return failure();
144 
145  return success();
146 }
147 
148 llvm::LogicalResult
150  Value memrefValue) {
151  auto memRefType = dyn_cast<MemRefType>(memrefValue.getType());
152  if (!memRefType || !NVGPUDialect::hasSharedMemoryAddressSpace(memRefType))
153  return failure();
154 
155  // Abort if the given value has any sub-views; we do not do any alias
156  // analysis.
157  bool hasSubView = false;
158  parentOp->walk([&](memref::SubViewOp subView) { hasSubView = true; });
159  if (hasSubView)
160  return failure();
161 
162  // Check if this is necessary given the assumption of 128b accesses:
163  // If dim[rank-1] is small enough to fit 8 rows in a 128B line.
164  const int64_t rowSize = memRefType.getDimSize(memRefType.getRank() - 1);
165  const int64_t rowsPerLine =
166  (8 * kSharedMemoryLineSizeBytes / memRefType.getElementTypeBitWidth()) /
167  rowSize;
168  const int64_t threadGroupSize =
169  1LL << (7 - llvm::Log2_64(kDefaultVectorSizeBits / 8));
170  if (rowsPerLine >= threadGroupSize)
171  return failure();
172 
173  // Get sets of operations within the function that read/write to shared
174  // memory.
175  SmallVector<Operation *, 16> shmReadOps;
176  SmallVector<Operation *, 16> shmWriteOps;
177  if (failed(getShmReadAndWriteOps(parentOp, memrefValue, shmReadOps,
178  shmWriteOps)))
179  return failure();
180 
181  if (shmReadOps.empty() || shmWriteOps.empty())
182  return failure();
183 
184  OpBuilder builder(parentOp->getContext());
185 
186  int64_t tgtDim = memRefType.getRank() - 1;
187  int64_t srcDim = memRefType.getRank() - 2;
188 
189  // Transform indices for the ops writing to shared memory.
190  while (!shmWriteOps.empty()) {
191  Operation *shmWriteOp = shmWriteOps.back();
192  shmWriteOps.pop_back();
193  builder.setInsertionPoint(shmWriteOp);
194 
195  auto indices = getIndices(shmWriteOp);
196  SmallVector<Value, 4> transformedIndices(indices.begin(), indices.end());
197  transformIndices(builder, shmWriteOp->getLoc(), transformedIndices,
198  memRefType, srcDim, tgtDim);
199  setIndices(shmWriteOp, transformedIndices);
200  }
201 
202  // Transform indices for the ops reading from shared memory.
203  while (!shmReadOps.empty()) {
204  Operation *shmReadOp = shmReadOps.back();
205  shmReadOps.pop_back();
206  builder.setInsertionPoint(shmReadOp);
207 
208  auto indices = getIndices(shmReadOp);
209  SmallVector<Value, 4> transformedIndices(indices.begin(), indices.end());
210  transformIndices(builder, shmReadOp->getLoc(), transformedIndices,
211  memRefType, srcDim, tgtDim);
212  setIndices(shmReadOp, transformedIndices);
213  }
214 
215  return success();
216 }
217 
218 namespace {
219 class OptimizeSharedMemoryPass
220  : public nvgpu::impl::OptimizeSharedMemoryBase<OptimizeSharedMemoryPass> {
221 public:
222  OptimizeSharedMemoryPass() = default;
223 
224  void runOnOperation() override {
225  Operation *op = getOperation();
226  SmallVector<memref::AllocOp> shmAllocOps;
227  op->walk([&](memref::AllocOp allocOp) {
228  if (!NVGPUDialect::hasSharedMemoryAddressSpace(allocOp.getType()))
229  return;
230  shmAllocOps.push_back(allocOp);
231  });
232  for (auto allocOp : shmAllocOps) {
233  if (failed(optimizeSharedMemoryReadsAndWrites(getOperation(),
234  allocOp.getMemref())))
235  return;
236  }
237  }
238 };
239 } // namespace
240 
242  return std::make_unique<OptimizeSharedMemoryPass>();
243 }
constexpr int64_t kSharedMemoryLineSizeBytes
The size of a shared memory line according to NV documentation.
static void transformIndices(OpBuilder &builder, Location loc, SmallVector< Value, 4 > &indices, MemRefType memrefTy, int64_t srcDim, int64_t tgtDim)
constexpr int64_t kDefaultVectorSizeBits
We optimize for 128bit accesses, but this can be made an argument in the future.
static Value permuteVectorOffset(OpBuilder &b, Location loc, ArrayRef< Value > indices, MemRefType memrefTy, int64_t srcDim, int64_t tgtDim)
Uses srcIndexValue to permute tgtIndexValue via `result = xor(floordiv(srcIdxVal,permuteEveryN),...
static LogicalResult getShmReadAndWriteOps(Operation *parentOp, Value shmMemRef, SmallVector< Operation *, 16 > &readOps, SmallVector< Operation *, 16 > &writeOps)
Return all operations within parentOp that read from or write to shmMemRef.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
This class helps build Operations.
Definition: Builders.h:216
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:407
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition: Builders.h:529
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition: Operation.h:798
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
llvm::LogicalResult optimizeSharedMemoryReadsAndWrites(Operation *parentOp, Value memrefValue)
Passes.
std::unique_ptr< Pass > createOptimizeSharedMemoryPass()
Create a pass to optimize shared memory reads and writes.
void setIndices(Operation *op, ArrayRef< Value > indices)
Set the indices that the given load/store operation is operating on.
Definition: Utils.cpp:38
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition: Utils.cpp:18
Include the generated interface declarations.
The following effect indicates that the operation reads from some resource.
The following effect indicates that the operation writes to some resource.