MLIR 24.0.0git
NVVMDataMovementOps.cpp
Go to the documentation of this file.
1//===- NVVMDataMovementOps.cpp - NVVM dialect data movement ops -----------===//
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 defines the ops of op partition `DataMovement` of the NVVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/NVVMOps.h"
17#include "mlir/IR/Diagnostics.h"
18#include "mlir/IR/MLIRContext.h"
19#include "mlir/IR/Operation.h"
20#include "mlir/IR/Types.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/IntrinsicsNVPTX.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/NVPTXAddrSpace.h"
28
29#include <cassert>
30#include <optional>
31
32using namespace mlir;
33using namespace mlir::NVVM;
34
35//===----------------------------------------------------------------------===//
36// Verifier methods
37//===----------------------------------------------------------------------===//
38
39LogicalResult BulkStoreOp::verify() {
40 if (getInitVal() != 0)
41 return emitOpError("only 0 is supported for initVal, got ") << getInitVal();
42 return success();
43}
44
45LogicalResult AsyncStoreGlobalOp::verify() {
46 NVVM::MemScopeKind scope = getScope();
47 bool isMmio = getMmio();
48 bool isMultimem = getMultimem();
49
50 if (scope != MemScopeKind::SYS && scope != MemScopeKind::GPU)
51 return emitOpError("scope must be either SYS or GPU");
52
53 if (isMmio && scope != MemScopeKind::SYS)
54 return emitOpError("mmio is only supported for SYS scope");
55
56 if (isMmio && isMultimem)
57 return emitOpError("multimem is not supported with mmio");
58
59 return success();
60}
61
62LogicalResult NVVM::PrefetchOp::verify() {
63 using MemSpace = NVVM::NVVMMemorySpace;
64 using CacheLevel = NVVM::PrefetchCacheLevel;
65
66 unsigned addressSpace =
67 llvm::cast<LLVM::LLVMPointerType>(getAddr().getType()).getAddressSpace();
68 std::optional<NVVM::CacheEvictionPriority> evictPriority = getEvictPriority();
69 std::optional<NVVM::PrefetchCacheLevel> cacheLevel = getCacheLevel();
70
71 if (getTensormap() && cacheLevel)
72 return emitOpError("cannot specify both tensormap and cache level");
73
74 if (getTensormap()) {
75 if (addressSpace != MemSpace::Generic &&
76 addressSpace != MemSpace::Constant) {
77 return emitOpError(
78 "prefetch tensormap requires a generic or constant pointer");
79 }
80
81 if (evictPriority) {
82 return emitOpError(
83 "prefetch tensormap does not support eviction priority");
84 }
85
86 if (getInParamSpace() && addressSpace != MemSpace::Generic) {
87 return emitOpError(
88 "in_param_space can only be specified for a generic pointer");
89 }
90
91 } else if (cacheLevel) {
92 if (addressSpace != MemSpace::Generic && addressSpace != MemSpace::Global &&
93 addressSpace != MemSpace::Local) {
94 return emitOpError("prefetch to cache level requires a generic, global, "
95 "or local pointer");
96 }
97
98 if (getUniform()) {
99 if (*cacheLevel != CacheLevel::L1) {
100 return emitOpError(
101 "unsupported cache level, the only supported uniform "
102 "cache level is L1");
103 }
104
105 if (addressSpace != MemSpace::Generic) {
106 return emitOpError(
107 "prefetch to uniform cache requires a generic pointer");
108 }
109 }
110
111 if (evictPriority) {
112 if (*cacheLevel != CacheLevel::L2)
113 return emitOpError(
114 "cache eviction priority supported only for cache level L2");
115
116 if (addressSpace != MemSpace::Global)
117 return emitOpError("cache eviction priority requires a global pointer");
118
119 if (*evictPriority != NVVM::CacheEvictionPriority::EvictNormal &&
120 *evictPriority != NVVM::CacheEvictionPriority::EvictLast)
121 return emitOpError(
122 "unsupported cache eviction priority, only evict_last and "
123 "evict_normal are supported");
124 }
125
126 if (getPredicate())
127 return emitOpError("predicate supported only on prefetch tensormap");
128
129 } else {
130 return emitOpError(
131 "requires specification of either cache level or tensormap");
132 }
133
134 return success();
135}
136
137LogicalResult ShflOp::verify() {
138 auto returnStructType = llvm::dyn_cast<LLVM::LLVMStructType>(getType());
139
140 auto verifyTypeError = [&](Twine desc, Type expectedType,
141 Type actualType) -> LogicalResult {
142 return emitOpError("expected " + desc + " to be of type ")
143 << expectedType << " but got " << actualType << " instead";
144 };
145
146 if (returnStructType) {
147 if (!getReturnValueAndIsValid())
148 return emitOpError("\"return_value_and_is_valid\" attribute must be "
149 "specified when the return type is a struct type");
150
151 if (returnStructType.getBody().size() != 2)
152 return emitOpError("expected return type to be a two-element struct");
153
154 llvm::ArrayRef<Type> returnStruct = returnStructType.getBody();
155 auto resultType = returnStruct[0];
156 if (resultType != getVal().getType())
157 return verifyTypeError("first element in the returned struct",
158 getVal().getType(), resultType);
159
160 auto predicateType = returnStruct[1];
161 if (!predicateType.isInteger(1))
162 return verifyTypeError("second element in the returned struct",
163 mlir::IntegerType::get(getContext(), 1),
164 predicateType);
165 } else {
166 if (getReturnValueAndIsValid())
167 return emitOpError("expected return type to be a two-element struct");
168
169 if (getType() != getVal().getType())
170 return verifyTypeError("return type", getVal().getType(), getType());
171 }
172 return success();
173}
174
175LogicalResult
176ShflOp::inferReturnTypes(MLIRContext *context, std::optional<Location> location,
177 ShflOp::Adaptor adaptor,
178 SmallVectorImpl<Type> &inferredReturnTypes) {
179 Type valType = adaptor.getVal().getType();
180 if (adaptor.getReturnValueAndIsValid())
181 inferredReturnTypes.push_back(LLVM::LLVMStructType::getLiteral(
182 context, {valType, IntegerType::get(context, 1)}));
183 else
184 inferredReturnTypes.push_back(valType);
185 return success();
186}
187
188LogicalResult PermuteOp::verify() {
189 using Mode = NVVM::PermuteMode;
190 bool hasHi = static_cast<bool>(getHi());
191
192 switch (getMode()) {
193 case Mode::DEFAULT:
194 case Mode::F4E:
195 case Mode::B4E:
196 if (!hasHi)
197 return emitError("mode '") << getMode() << "' requires 'hi' operand.";
198 break;
199 case Mode::RC8:
200 case Mode::ECL:
201 case Mode::ECR:
202 case Mode::RC16:
203 if (hasHi)
204 return emitError("mode '")
205 << getMode() << "' does not accept 'hi' operand.";
206 break;
207 }
208
209 return success();
210}
211
212//===----------------------------------------------------------------------===//
213// getIntrinsicID/getIntrinsicIDAndArgs methods
214//===----------------------------------------------------------------------===//
215
216mlir::NVVM::IDArgPair AsyncStoreGlobalOp::getIntrinsicIDAndArgs(
217 Operation &op, LLVM::ModuleTranslation &mt, llvm::IRBuilderBase &builder) {
219 auto thisOp = cast<NVVM::AsyncStoreGlobalOp>(op);
220 mlir::NVVM::MemScopeKind scope = thisOp.getScope();
221 bool isMmio = thisOp.getMmio();
222
223 llvm::Value *addr = mt.lookupValue(thisOp.getAddr());
224 llvm::Value *value = mt.lookupValue(thisOp.getValue());
225 llvm::Value *isMultimem = builder.getInt1(thisOp.getMultimem());
226
227 if (scope == MemScopeKind::SYS) {
228 return isMmio ? IDArgPair(llvm::Intrinsic::nvvm_st_async_mmio_sys,
229 {addr, value})
230 : IDArgPair(llvm::Intrinsic::nvvm_st_async_sys,
231 {addr, value, isMultimem});
232 } else if (scope == MemScopeKind::GPU) {
233 return IDArgPair(llvm::Intrinsic::nvvm_st_async_gpu,
234 {addr, value, isMultimem});
235 }
236 llvm_unreachable("unsupported scope for AsyncStoreGlobalOp");
237}
238
239llvm::Value *mlir::NVVM::getParamCastedAddr(llvm::Value *addr,
240 llvm::IRBuilderBase &builder) {
241 return builder.CreateAddrSpaceCast(
242 addr, builder.getPtrTy(llvm::NVPTXAS::ADDRESS_SPACE_ENTRY_PARAM));
243}
244
246PrefetchOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
247 llvm::IRBuilderBase &builder) {
248 auto thisOp = cast<NVVM::PrefetchOp>(op);
249 using MemSpace = NVVM::NVVMMemorySpace;
250 using CacheLevel = NVVM::PrefetchCacheLevel;
251
252 std::optional<NVVM::PrefetchCacheLevel> cacheLevel = thisOp.getCacheLevel();
253 std::optional<NVVM::CacheEvictionPriority> evictPriority =
254 thisOp.getEvictPriority();
255 unsigned addressSpace =
256 llvm::cast<LLVM::LLVMPointerType>(thisOp.getAddr().getType())
257 .getAddressSpace();
258
260 llvm::Value *addr = mt.lookupValue(thisOp.getAddr());
261 args.push_back(thisOp.getInParamSpace() ? getParamCastedAddr(addr, builder)
262 : addr);
263
264 if (thisOp.getTensormap())
265 return {llvm::Intrinsic::nvvm_prefetch_tensormap, args};
266
267 assert(cacheLevel && "expected cache level for non-tensormap prefetch");
268
269 if (thisOp.getUniform() && *cacheLevel == CacheLevel::L1)
270 return {llvm::Intrinsic::nvvm_prefetchu_L1, args};
271
272 if (evictPriority && *cacheLevel == CacheLevel::L2) {
273 switch (*evictPriority) {
274 case NVVM::CacheEvictionPriority::EvictLast:
275 return {llvm::Intrinsic::nvvm_prefetch_global_L2_evict_last, args};
276 case NVVM::CacheEvictionPriority::EvictNormal:
277 return {llvm::Intrinsic::nvvm_prefetch_global_L2_evict_normal, args};
278 default:
279 llvm_unreachable("Invalid cache eviction priority");
280 }
281 }
282
283 switch (static_cast<MemSpace>(addressSpace)) {
284 case MemSpace::Generic:
285 return *cacheLevel == CacheLevel::L1
286 ? NVVM::IDArgPair({llvm::Intrinsic::nvvm_prefetch_L1, args})
287 : NVVM::IDArgPair({llvm::Intrinsic::nvvm_prefetch_L2, args});
288 case MemSpace::Global:
289 return *cacheLevel == CacheLevel::L1
291 {llvm::Intrinsic::nvvm_prefetch_global_L1, args})
292 : NVVM::IDArgPair(
293 {llvm::Intrinsic::nvvm_prefetch_global_L2, args});
294 case MemSpace::Local:
295 return *cacheLevel == CacheLevel::L1
297 {llvm::Intrinsic::nvvm_prefetch_local_L1, args})
298 : NVVM::IDArgPair(
299 {llvm::Intrinsic::nvvm_prefetch_local_L2, args});
300 default:
301 llvm_unreachable("Invalid pointer address space");
302 }
303}
304
306PermuteOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
307 llvm::IRBuilderBase &builder) {
308 auto thisOp = cast<NVVM::PermuteOp>(op);
309 NVVM::PermuteMode mode = thisOp.getMode();
310
311 static constexpr llvm::Intrinsic::ID IDs[] = {
312 llvm::Intrinsic::nvvm_prmt, llvm::Intrinsic::nvvm_prmt_f4e,
313 llvm::Intrinsic::nvvm_prmt_b4e, llvm::Intrinsic::nvvm_prmt_rc8,
314 llvm::Intrinsic::nvvm_prmt_ecl, llvm::Intrinsic::nvvm_prmt_ecr,
315 llvm::Intrinsic::nvvm_prmt_rc16};
316
317 unsigned modeIndex = static_cast<unsigned>(mode);
318 llvm::SmallVector<llvm::Value *> args;
319 args.push_back(mt.lookupValue(thisOp.getLo()));
320
321 // Only first 3 modes (Default, f4e, b4e) need the hi operand.
322 if (modeIndex < 3)
323 args.push_back(mt.lookupValue(thisOp.getHi()));
324
325 args.push_back(mt.lookupValue(thisOp.getSelector()));
326
327 return {IDs[modeIndex], args};
328}
329
330//===----------------------------------------------------------------------===//
331// sparse.compress and sparse.decompress Ops
332//===----------------------------------------------------------------------===//
333
334// Returns the number of 32-bit registers in a metadata register bundle, which
335// is either an i32 or a vector of i32.
336static unsigned getNumSPRegisters(Type type) {
337 if (auto vecTy = dyn_cast<VectorType>(type))
338 return vecTy.getNumElements();
339 return 1;
340}
341
342// The repeat factor of spcompress and spdecompress is a power of two up to 64.
343static bool isValidSPRepFactor(unsigned repFactor) {
344 return llvm::isPowerOf2_32(repFactor) && repFactor <= 64;
345}
346
347LogicalResult SparseCompressOp::verify() {
348 auto dataTy = cast<VectorType>(getData().getType());
349 auto compressedTy = cast<VectorType>(getCompressedData().getType());
350 if (dataTy.getElementType() != compressedTy.getElementType())
351 return emitOpError(
352 "expects data and compressed data to have the same element type");
353
354 // data occupies 2 * repFactor 32-bit registers.
355 unsigned elemSize = dataTy.getElementTypeBitWidth();
356 unsigned dataBits = dataTy.getNumElements() * elemSize;
357 unsigned repFactor = dataBits / 64;
358 if (dataBits % 64 != 0 || !isValidSPRepFactor(repFactor))
359 return emitOpError("expects data to occupy 2 * repFactor 32-bit "
360 "registers, where repFactor is a power of two up to 64");
361
362 // spcompress only supports the 2:4 sparsity factor.
363 if (2 * compressedTy.getNumElements() != dataTy.getNumElements())
364 return emitOpError(
365 "expects compressed data to have half as many elements as data");
366
367 unsigned numMetadataRegs =
368 llvm::divideCeil(repFactor * getIdxSize(), elemSize);
369 if (getNumSPRegisters(getMetadata().getType()) != numMetadataRegs)
370 return emitOpError("expects metadata to occupy ")
371 << numMetadataRegs << " 32-bit register(s)";
372
373 return success();
374}
375
376LogicalResult SparseDecompressOp::verify() {
377 auto dataTy = cast<VectorType>(getData().getType());
378 auto compressedTy = cast<VectorType>(getCompressedData().getType());
379 if (dataTy.getElementType() != compressedTy.getElementType())
380 return emitOpError(
381 "expects data and compressed data to have the same element type");
382
383 // data holds repFactor groups of numTgt elements, and compressed data holds
384 // numSrc elements for each of those groups.
385 unsigned idxSize = getIdxSize();
386 unsigned numTgt = getNumTgt();
387 unsigned numData = dataTy.getNumElements();
388 unsigned numCompressed = compressedTy.getNumElements();
389 unsigned repFactor = numData / numTgt;
390 if (numData % numTgt != 0 || !isValidSPRepFactor(repFactor))
391 return emitOpError("expects data to have repFactor * num_tgt elements, "
392 "where repFactor is a power of two up to 64");
393
394 unsigned numSrc = numCompressed / repFactor;
395 if (numCompressed % repFactor != 0 ||
396 !llvm::is_contained({1u, 2u, 4u}, numSrc) || numSrc >= numTgt)
397 return emitOpError("unsupported sparsity factor: compressed data has ")
398 << numCompressed << " elements for " << repFactor << " group(s) of "
399 << numTgt << " elements";
400
401 unsigned elemSize = dataTy.getElementTypeBitWidth();
402 unsigned dataBits = numData * elemSize;
403 if (dataBits < 32 || dataBits > 4096)
404 return emitOpError("expects data to be between 32 and 4096 bits");
405
406 if (numSrc * elemSize > 32)
407 return emitOpError("expects at most 32 bits of compressed data per group");
408
409 if (idxSize == 2 && numTgt > 4)
410 return emitOpError("expects num_tgt to be at most 4 if idx_size is 2");
411
412 unsigned numMetadataRegs = llvm::divideCeil(numSrc * idxSize * repFactor, 32);
413 if (getNumSPRegisters(getMetadata().getType()) != numMetadataRegs)
414 return emitOpError("expects metadata to occupy ")
415 << numMetadataRegs << " 32-bit register(s)";
416
417 return success();
418}
419
420#define GET_OP_CLASSES
421#include "mlir/Dialect/LLVMIR/NVVMDataMovementOps.cpp.inc"
return success()
b getContext())
static bool isValidSPRepFactor(unsigned repFactor)
static unsigned getNumSPRegisters(Type type)
Implementation class for module translation.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
llvm::Value * getParamCastedAddr(llvm::Value *addr, llvm::IRBuilderBase &builder)
Returns addr cast to the kernel parameter address space.
std::pair< llvm::Intrinsic::ID, llvm::SmallVector< llvm::Value * > > IDArgPair
A pair type of LLVM's Intrinsic ID and args (which are llvm values).
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.