MLIR 24.0.0git
NVVMArithOps.cpp
Go to the documentation of this file.
1//===- NVVMArithOps.cpp - NVVM dialect arithmetic 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 `Arith` of the NVVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/NVVMOps.h"
18#include "mlir/IR/Diagnostics.h"
19#include "mlir/IR/MLIRContext.h"
20#include "mlir/IR/Operation.h"
22#include "mlir/IR/Types.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/IntrinsicsNVPTX.h"
26#include "llvm/Support/Casting.h"
27
28using namespace mlir;
29using namespace mlir::NVVM;
30
31//===----------------------------------------------------------------------===//
32// Verifier methods
33//===----------------------------------------------------------------------===//
34
35template <typename OpType>
36static LogicalResult verifyFloatBinaryOp(OpType op, StringRef opKind) {
37 mlir::NVVM::FPRoundingMode rndMode = op.getRnd();
38 mlir::NVVM::SaturationMode satMode = op.getSat();
39 bool isFTZ = op.getFtz();
40
41 mlir::Type opType = op.getRes().getType();
42 mlir::Type opBaseType = isa<VectorType>(opType)
43 ? cast<VectorType>(opType).getElementType()
44 : opType;
45
46 if (opBaseType.isF64() && (satMode != NVVM::SaturationMode::NONE || isFTZ))
47 return op.emitOpError("FTZ and saturation are not supported for ")
48 << opKind << " involving f64 type";
49
50 if (opBaseType.isF16() && !(rndMode == NVVM::FPRoundingMode::RN ||
51 rndMode == NVVM::FPRoundingMode::NONE))
52 return op.emitOpError("only RN rounding mode is supported for f16 and "
53 "vector<2xf16> ")
54 << opKind;
55
56 if (opBaseType.isBF16()) {
57 if (rndMode != NVVM::FPRoundingMode::RN &&
58 rndMode != NVVM::FPRoundingMode::NONE)
59 return op.emitOpError("only RN rounding mode is supported for bf16 and "
60 "vector<2xbf16> ")
61 << opKind;
62 if (satMode != NVVM::SaturationMode::NONE || isFTZ)
63 return op.emitOpError("FTZ and saturation are not supported for bf16 and "
64 "vector<2xbf16> ")
65 << opKind;
66 }
67
68 return success();
69}
70
71LogicalResult NVVM::AddFOp::verify() {
72 return verifyFloatBinaryOp(*this, "additions");
73}
74
75LogicalResult NVVM::SubFOp::verify() {
76 return verifyFloatBinaryOp(*this, "subtractions");
77}
78
79LogicalResult NVVM::MulFOp::verify() {
80 return verifyFloatBinaryOp(*this, "multiplications");
81}
82
83LogicalResult NVVM::FmaOp::verify() {
84 auto opType = getRes().getType();
85 mlir::NVVM::FPRoundingMode rndMode = getRnd();
86 mlir::NVVM::SaturationMode satMode = getSat();
87 bool isFTZ = getFtz();
88 bool isRelu = getRelu();
89 bool hasOOB = getOob();
90
91 auto getBaseFType = [](Type type) -> Type {
92 if (isa<VectorType>(type))
93 return cast<VectorType>(type).getElementType();
94 return type;
95 };
96
97 auto opBaseType = getBaseFType(opType);
98
99 if (rndMode == NVVM::FPRoundingMode::NONE)
100 return emitOpError("rounding mode must be specified");
101
102 if (isRelu && satMode == NVVM::SaturationMode::SAT)
103 return emitOpError("relu and saturation are not supported together");
104
105 if (hasOOB && (satMode == NVVM::SaturationMode::SAT || isFTZ))
106 return emitOpError("oob is not supported with saturation or FTZ");
107
108 if (!(opBaseType.isF16() || opBaseType.isBF16()) && (isRelu || hasOOB))
109 return emitOpError("relu and oob are only supported for f16 and bf16");
110
111 if (opBaseType.isF64() && (satMode != NVVM::SaturationMode::NONE || isFTZ))
112 return emitOpError("FTZ and saturation are not supported for f64 type");
113
114 if (opBaseType.isF16() && rndMode != NVVM::FPRoundingMode::RN)
115 return emitOpError(
116 "only RN rounding mode is supported for f16 and vector<2xf16>");
117
118 if (opBaseType.isBF16()) {
119 if (rndMode != NVVM::FPRoundingMode::RN)
120 return emitOpError(
121 "only RN rounding mode is supported for bf16 and vector<2xbf16>");
122 if (satMode != NVVM::SaturationMode::NONE || isFTZ)
123 return emitOpError(
124 "FTZ and saturation are not supported for bf16 and vector<2xbf16>");
125 }
126
127 return success();
128}
129
130LogicalResult NVVM::SqrtOp::verify() {
131 if (getRnd() == NVVM::FPRoundingMode::NONE)
132 return emitOpError("rounding mode cannot be None");
133
134 if (getRes().getType().isF64() && getFtz())
135 return emitOpError("FTZ is not supported for f64");
136
137 return success();
138}
139
140LogicalResult NVVM::DivFOp::verify() {
141 bool isApprox = getApprox();
142 bool isFull = getFull();
143 bool isF64 = getRes().getType().isF64();
144 bool isFtz = getFtz();
145 NVVM::FPRoundingMode rndMode = getRnd();
146
147 if (isApprox && isFull)
148 return emitOpError("'approx' and 'full' are mutually exclusive");
149
150 if (isApprox || isFull) {
151 if (isF64)
152 return emitOpError("'approx' and 'full' forms are f32-only");
153 if (rndMode != NVVM::FPRoundingMode::NONE)
154 return emitOpError(
155 "'approx' and 'full' forms do not accept a rounding mode");
156 return success();
157 }
158
159 // Rounded form below.
160 if (rndMode == NVVM::FPRoundingMode::NONE)
161 return emitOpError("rounding mode cannot be None for the rounded divide");
162 if (isF64 && isFtz)
163 return emitOpError("FTZ is not supported for f64");
164
165 return success();
166}
167
168//===----------------------------------------------------------------------===//
169// Canonicalization patterns
170//===----------------------------------------------------------------------===//
171
174
175 LogicalResult matchAndRewrite(SubFOp op,
176 PatternRewriter &rewriter) const override {
177 Location loc = op.getLoc();
178 Value negRhs =
179 LLVM::FNegOp::create(rewriter, loc, op.getRhs().getType(), op.getRhs());
180
181 rewriter.replaceOpWithNewOp<AddFOp>(op, op.getType(), op.getLhs(), negRhs,
182 op.getRnd(), op.getSat(), op.getFtz());
183 return success();
184 }
185};
186
187void SubFOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
188 MLIRContext *context) {
189 patterns.add<ConvertFsubToFnegFadd>(context);
190}
191
192//===----------------------------------------------------------------------===//
193// getIntrinsicID/getIntrinsicIDAndArgs methods
194//===----------------------------------------------------------------------===//
195
197CosOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
198 llvm::IRBuilderBase &builder) {
199 auto thisOp = cast<NVVM::CosOp>(op);
200 llvm::Intrinsic::ID id = thisOp.getFtz()
201 ? llvm::Intrinsic::nvvm_cos_approx_ftz_f
202 : llvm::Intrinsic::nvvm_cos_approx_f;
203 return {id, {mt.lookupValue(thisOp.getSrc())}};
204}
205
207SinOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
208 llvm::IRBuilderBase &builder) {
209 auto thisOp = cast<NVVM::SinOp>(op);
210 llvm::Intrinsic::ID id = thisOp.getFtz()
211 ? llvm::Intrinsic::nvvm_sin_approx_ftz_f
212 : llvm::Intrinsic::nvvm_sin_approx_f;
213 return {id, {mt.lookupValue(thisOp.getSrc())}};
214}
215
217Log2Op::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
218 llvm::IRBuilderBase &builder) {
219 auto thisOp = cast<NVVM::Log2Op>(op);
220 llvm::Intrinsic::ID id = thisOp.getFtz()
221 ? llvm::Intrinsic::nvvm_lg2_approx_ftz_f
222 : llvm::Intrinsic::nvvm_lg2_approx_f;
223 return {id, {mt.lookupValue(thisOp.getSrc())}};
224}
225
227Ex2Op::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
228 llvm::IRBuilderBase &builder) {
229 auto thisOp = cast<NVVM::Ex2Op>(op);
230 llvm::Intrinsic::ID id = thisOp.getFtz()
231 ? llvm::Intrinsic::nvvm_ex2_approx_ftz
232 : llvm::Intrinsic::nvvm_ex2_approx;
233 return {id, {mt.lookupValue(thisOp.getSrc())}};
234}
235
236LogicalResult NVVM::Ex2Op::verify() {
237 auto vectorType = dyn_cast<VectorType>(getSrc().getType());
238 if (!vectorType)
239 return success();
240
241 if (vectorType.getElementType().isF16() && getFtz())
242 return emitOpError("FTZ is not supported for vector<2xf16>");
243 if (vectorType.getElementType().isBF16() && !getFtz())
244 return emitOpError("FTZ is required for vector<2xbf16>");
245 return success();
246}
247
249RsqrtOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
250 llvm::IRBuilderBase &builder) {
251 auto thisOp = cast<NVVM::RsqrtOp>(op);
252 Type t = thisOp.getRes().getType();
253 bool isFtz = thisOp.getFtz();
254
255 llvm::Intrinsic::ID id = [&] {
256 if (t.isF32()) {
257 return isFtz ? llvm::Intrinsic::nvvm_rsqrt_approx_ftz_f
258 : llvm::Intrinsic::nvvm_rsqrt_approx_f;
259 }
260 // f64
261 return isFtz ? llvm::Intrinsic::nvvm_rsqrt_approx_ftz_d
262 : llvm::Intrinsic::nvvm_rsqrt_approx_d;
263 }();
264
265 return {id, {mt.lookupValue(thisOp.getSrc())}};
266}
267
269SqrtOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
270 llvm::IRBuilderBase &builder) {
271 auto thisOp = cast<NVVM::SqrtOp>(op);
272 Type t = thisOp.getRes().getType();
273 NVVM::FPRoundingMode rndMode = thisOp.getRnd();
274 bool isFtz = thisOp.getFtz();
275
276 // RM is one of RN/RM/RP/RZ (verifier rejects NONE).
277 // Subtracting 1 maps RN=1..RZ=4 to 0..3.
278 unsigned rndIndex = static_cast<unsigned>(rndMode) - 1;
279
280 static constexpr llvm::Intrinsic::ID f32IDs[] = {
281 llvm::Intrinsic::nvvm_sqrt_rn_f,
282 llvm::Intrinsic::nvvm_sqrt_rm_f,
283 llvm::Intrinsic::nvvm_sqrt_rp_f,
284 llvm::Intrinsic::nvvm_sqrt_rz_f,
285 };
286 static constexpr llvm::Intrinsic::ID f32FTZIDs[] = {
287 llvm::Intrinsic::nvvm_sqrt_rn_ftz_f,
288 llvm::Intrinsic::nvvm_sqrt_rm_ftz_f,
289 llvm::Intrinsic::nvvm_sqrt_rp_ftz_f,
290 llvm::Intrinsic::nvvm_sqrt_rz_ftz_f,
291 };
292 static constexpr llvm::Intrinsic::ID f64IDs[] = {
293 llvm::Intrinsic::nvvm_sqrt_rn_d,
294 llvm::Intrinsic::nvvm_sqrt_rm_d,
295 llvm::Intrinsic::nvvm_sqrt_rp_d,
296 llvm::Intrinsic::nvvm_sqrt_rz_d,
297 };
298
299 llvm::Intrinsic::ID id =
300 t.isF32() ? (isFtz ? f32FTZIDs[rndIndex] : f32IDs[rndIndex])
301 : f64IDs[rndIndex];
302
303 return {id, {mt.lookupValue(thisOp.getSrc())}};
304}
305
307SqrtApproxOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
308 llvm::IRBuilderBase &builder) {
309 auto thisOp = cast<NVVM::SqrtApproxOp>(op);
310 llvm::Intrinsic::ID id = thisOp.getFtz()
311 ? llvm::Intrinsic::nvvm_sqrt_approx_ftz_f
312 : llvm::Intrinsic::nvvm_sqrt_approx_f;
313 return {id, {mt.lookupValue(thisOp.getSrc())}};
314}
315
317DivFOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
318 llvm::IRBuilderBase &builder) {
319 auto thisOp = cast<NVVM::DivFOp>(op);
320 bool isFtz = thisOp.getFtz();
321
322 llvm::Intrinsic::ID id;
323
324 if (thisOp.getApprox()) {
325 id = isFtz ? llvm::Intrinsic::nvvm_div_approx_ftz_f
326 : llvm::Intrinsic::nvvm_div_approx_f;
327 } else if (thisOp.getFull()) {
328 // Intrinsic Naming quirk: int_nvvm_div_full has no `_f` suffix (unlike
329 // approx).
330 id = isFtz ? llvm::Intrinsic::nvvm_div_full_ftz
331 : llvm::Intrinsic::nvvm_div_full;
332 } else {
333 // Rounded form — three 4-entry tables indexed by (rndMode - 1).
334 unsigned rndIndex = static_cast<unsigned>(thisOp.getRnd()) - 1;
335
336 static constexpr llvm::Intrinsic::ID f32IDs[] = {
337 llvm::Intrinsic::nvvm_div_rn_f,
338 llvm::Intrinsic::nvvm_div_rm_f,
339 llvm::Intrinsic::nvvm_div_rp_f,
340 llvm::Intrinsic::nvvm_div_rz_f,
341 };
342 static constexpr llvm::Intrinsic::ID f32FTZIDs[] = {
343 llvm::Intrinsic::nvvm_div_rn_ftz_f,
344 llvm::Intrinsic::nvvm_div_rm_ftz_f,
345 llvm::Intrinsic::nvvm_div_rp_ftz_f,
346 llvm::Intrinsic::nvvm_div_rz_ftz_f,
347 };
348 static constexpr llvm::Intrinsic::ID f64IDs[] = {
349 llvm::Intrinsic::nvvm_div_rn_d,
350 llvm::Intrinsic::nvvm_div_rm_d,
351 llvm::Intrinsic::nvvm_div_rp_d,
352 llvm::Intrinsic::nvvm_div_rz_d,
353 };
354 Type t = thisOp.getRes().getType();
355 id = t.isF32() ? (isFtz ? f32FTZIDs[rndIndex] : f32IDs[rndIndex])
356 : f64IDs[rndIndex];
357 }
358
359 return {id,
360 {mt.lookupValue(thisOp.getLhs()), mt.lookupValue(thisOp.getRhs())}};
361}
362
363static llvm::Value *getAsPackedI32(llvm::Value *arg,
364 llvm::IRBuilderBase &builder) {
365 return builder.CreateBitCast(arg,
366 llvm::Type::getInt32Ty(builder.getContext()));
367}
368
369NVVM::IDArgPair DotAccumulate4WayOp::getIntrinsicIDAndArgs(
370 Operation &op, LLVM::ModuleTranslation &mt, llvm::IRBuilderBase &builder) {
371 auto curOp = cast<NVVM::DotAccumulate4WayOp>(op);
372
374 args.push_back(getAsPackedI32(mt.lookupValue(curOp.getA()), builder));
375 args.push_back(getAsPackedI32(mt.lookupValue(curOp.getB()), builder));
376 args.push_back(mt.lookupValue(curOp.getC()));
377
378 bool isASigned = curOp.getAType() == NVVM::DotAccumulateType::SIGNED;
379 bool isBSigned = curOp.getBType() == NVVM::DotAccumulateType::SIGNED;
380 unsigned type = (isASigned << 1) | isBSigned;
381 const llvm::Intrinsic::ID ids[] = {
382 llvm::Intrinsic::nvvm_idp4a_u_u,
383 llvm::Intrinsic::nvvm_idp4a_u_s,
384 llvm::Intrinsic::nvvm_idp4a_s_u,
385 llvm::Intrinsic::nvvm_idp4a_s_s,
386 };
387 return {ids[type], args};
388}
389
390NVVM::IDArgPair DotAccumulate2WayOp::getIntrinsicIDAndArgs(
391 Operation &op, LLVM::ModuleTranslation &mt, llvm::IRBuilderBase &builder) {
392 auto curOp = cast<NVVM::DotAccumulate2WayOp>(op);
393
395 args.push_back(getAsPackedI32(mt.lookupValue(curOp.getA()), builder));
396 args.push_back(getAsPackedI32(mt.lookupValue(curOp.getB()), builder));
397 args.push_back(builder.getInt1(curOp.getBHi()));
398 args.push_back(mt.lookupValue(curOp.getC()));
399
400 bool isASigned = curOp.getAType() == NVVM::DotAccumulateType::SIGNED;
401 bool isBSigned = curOp.getBType() == NVVM::DotAccumulateType::SIGNED;
402 unsigned type = (isASigned << 1) | isBSigned;
403 const llvm::Intrinsic::ID ids[] = {
404 llvm::Intrinsic::nvvm_idp2a_u_u,
405 llvm::Intrinsic::nvvm_idp2a_u_s,
406 llvm::Intrinsic::nvvm_idp2a_s_u,
407 llvm::Intrinsic::nvvm_idp2a_s_s,
408 };
409 return {ids[type], args};
410}
411
412#define GET_OP_CLASSES
413#include "mlir/Dialect/LLVMIR/NVVMArithOps.cpp.inc"
return success()
static LogicalResult verifyFloatBinaryOp(OpType op, StringRef opKind)
static llvm::Value * getAsPackedI32(llvm::Value *arg, llvm::IRBuilderBase &builder)
Implementation class for module translation.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
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
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF64() const
Definition Types.cpp:41
bool isF32() const
Definition Types.cpp:40
bool isF16() const
Definition Types.cpp:38
bool isBF16() const
Definition Types.cpp:37
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
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
LogicalResult matchAndRewrite(SubFOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})