23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/TypeSwitch.h"
25#include "llvm/Support/DebugLog.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Support/LogicalResult.h"
28#include "llvm/Support/Regex.h"
30#define DEBUG_TYPE "ptx-builder"
36#include "mlir/Dialect/LLVMIR/BasicPtxBuilderInterface.cpp.inc"
45 auto i16 = IntegerType::get(ctx, 16);
46 auto i32 = IntegerType::get(ctx, 32);
47 auto f32 = Float32Type::get(ctx);
49 auto getRegisterTypeForScalar = [&](
Type type) -> FailureOr<char> {
62 if (
auto ptr = dyn_cast<LLVM::LLVMPointerType>(type)) {
71 loc,
"The register type could not be deduced from MLIR type. The ")
73 <<
" is not supported. Supported types are:"
74 "i1, i16, i32, i64, f32, f64,"
75 "pointers.\nPlease use llvm.bitcast if you have different type. "
76 "\nSee the constraints from here: "
77 "https://docs.nvidia.com/cuda/inline-ptx-assembly/"
78 "index.html#constraints";
83 if (
auto v = dyn_cast<VectorType>(type)) {
84 assert(v.getNumDynamicDims() == 0 &&
"Dynamic vectors are not supported");
86 int64_t lanes = v.getNumElements();
87 Type elem = v.getElementType();
91 return getRegisterTypeForScalar(elem);
115 return getRegisterTypeForScalar(widened);
118 return getRegisterTypeForScalar(type);
130 auto structTy = dyn_cast<LLVM::LLVMStructType>(structVal.
getType());
131 assert(structTy &&
"expected LLVM struct");
134 for (
unsigned i : llvm::seq<unsigned>(0, structTy.getBody().size()))
135 elems.push_back(LLVM::ExtractValueOp::create(rewriter, loc, structVal, i));
141 LDBG() << v <<
"\t Modifier : " << itype <<
"\n";
142 registerModifiers.push_back(itype);
144 Location loc = interfaceOp->getLoc();
145 auto getModifier = [&]() ->
const char * {
156 llvm_unreachable(
"Unknown PTX register modifier");
159 auto addValue = [&](
Value v) {
161 ptxOperands.push_back(v);
165 ptxOperands.push_back(v);
169 llvm::raw_string_ostream ss(registerConstraints);
171 if (
auto stype = dyn_cast<LLVM::LLVMStructType>(v.
getType())) {
175 for (
auto [idx, t] : llvm::enumerate(stype.getBody())) {
178 LLVM::ExtractValueOp::create(rewriter, loc, v, idx);
179 addValue(extractValue);
186 return rewriter.notifyMatchFailure(loc,
187 "failed to get register type");
188 ss << getModifier() << regType.value() <<
",";
197 return rewriter.notifyMatchFailure(loc,
"failed to get register type");
198 ss << getModifier() << regType.value() <<
",";
205 bool needsManualRegisterMapping,
207 if (needsManualRegisterMapping)
209 const unsigned writeOnlyVals = interfaceOp->getNumResults();
210 const unsigned readWriteVals =
214 return (writeOnlyVals + readWriteVals) > 1;
220static SmallVector<Type>
222 bool needsManualRegisterMapping,
226 TypeRange resultRange = interfaceOp->getResultTypes();
229 registerModifiers)) {
231 if (interfaceOp->getResults().size() == 1)
235 for (
auto [m, v] : llvm::zip(registerModifiers, ptxOperands))
241 for (
auto [m, v] : llvm::zip(registerModifiers, ptxOperands))
243 packed.push_back(v.getType());
244 for (
Type t : resultRange)
250 auto sTy = LLVM::LLVMStructType::getLiteral(ctx, packed,
false);
265 csv.split(toks,
',');
266 out.reserve(toks.size() + 8);
268 for (
unsigned i = 0, e = toks.size(); i < e; ++i) {
269 StringRef t = toks[i].trim();
270 if (t.consume_front(
"+")) {
271 plusIdx.push_back(i);
272 out.push_back((
"=" + t).str());
274 out.push_back(t.str());
279 for (
unsigned idx : plusIdx)
280 out.push_back(std::to_string(idx));
284 result.reserve(csv.size() + plusIdx.size() * 2);
285 llvm::raw_string_ostream os(
result);
286 for (
size_t i = 0; i < out.size(); ++i) {
300 llvm::Regex rx(llvm::formatv(R
"(\{\$({0}|{1}|{2})([0-9]+)\})",
308 StringRef ptxCode, llvm::SmallDenseSet<unsigned int> &seenRW,
309 llvm::SmallDenseSet<unsigned int> &seenW,
310 llvm::SmallDenseSet<unsigned int> &seenR,
311 llvm::SmallVectorImpl<unsigned int> &rwNums,
312 llvm::SmallVectorImpl<unsigned int> &wNums,
313 llvm::SmallVectorImpl<unsigned int> &rNums) {
316 StringRef rest = ptxCode;
318 SmallVector<StringRef, 3> m;
319 while (!rest.empty() && rx.match(rest, &m)) {
321 (void)m[2].getAsInteger(10, num);
324 if (seenRW.insert(num).second)
325 rwNums.push_back(num);
327 if (seenW.insert(num).second)
328 wNums.push_back(num);
330 if (seenR.insert(num).second)
331 rNums.push_back(num);
334 const size_t advance = (size_t)(m[0].data() - rest.data()) + m[0].size();
335 rest = rest.drop_front(advance);
366 llvm::SmallDenseSet<unsigned> seenRW, seenW, seenR;
380 for (
unsigned n : rwNums)
382 for (
unsigned n : wNums)
384 for (
unsigned n : rNums)
389 out.reserve(ptxCode.size());
391 StringRef rest = ptxCode;
394 while (!rest.empty() && rx.match(rest, &matches)) {
396 size_t absStart = (size_t)(matches[0].data() - ptxCode.data());
397 size_t absEnd = absStart + matches[0].size();
400 out.append(ptxCode.data() + prev, ptxCode.data() + absStart);
404 (
void)matches[2].getAsInteger(10, num);
407 id = rwMap.lookup(num);
409 id = wMap.lookup(num);
411 id = rMap.lookup(num);
414 out += std::to_string(
id);
418 const size_t advance =
419 (size_t)(matches[0].data() - rest.data()) + matches[0].size();
420 rest = rest.drop_front(advance);
424 out.append(ptxCode.data() + prev, ptxCode.data() + ptxCode.size());
435 constraints.split(tokens,
',');
436 assert(!tokens.empty() &&
"expected at least a predicate constraint");
438 auto isTiedConstraint = [](StringRef tok) {
440 return !tok.trim().getAsInteger(10, idx);
444 for (StringRef tok : llvm::reverse(tokens)) {
445 if (!isTiedConstraint(tok))
449 assert(numTied < tokens.size() &&
"all constraints are tied");
450 return tokens.size() - numTied - 1;
454 auto asmDialectAttr = LLVM::AsmDialectAttr::get(interfaceOp->getContext(),
455 LLVM::AsmDialect::AD_ATT);
458 interfaceOp, needsManualRegisterMapping, registerModifiers, ptxOperands);
461 if (!registerConstraints.empty() &&
462 registerConstraints[registerConstraints.size() - 1] ==
',')
463 registerConstraints.pop_back();
466 std::string ptxInstruction = interfaceOp.getPtx();
467 if (!needsManualRegisterMapping)
471 if (interfaceOp.getPredicate().has_value() &&
472 interfaceOp.getPredicate().value()) {
474 std::string predicateStr =
"@%";
475 predicateStr += std::to_string(predIdx);
476 ptxInstruction = predicateStr +
" " + ptxInstruction;
480 if (interfaceOp.hasMemoryClobber()) {
481 if (!registerConstraints.empty())
482 registerConstraints +=
",";
483 registerConstraints +=
"~{memory}";
492 mapped.reserve(ptxInstruction.size());
493 for (
size_t i = 0, e = ptxInstruction.size(); i < e; ++i) {
494 if (ptxInstruction[i] ==
'%' && i + 1 < e &&
495 llvm::isDigit(ptxInstruction[i + 1]))
496 mapped.push_back(
'$');
498 mapped.push_back(ptxInstruction[i]);
500 ptxInstruction = std::move(mapped);
502 return LLVM::InlineAsmOp::create(
503 rewriter, interfaceOp->getLoc(),
507 registerConstraints.data(),
508 interfaceOp.hasSideEffect(),
509 false, LLVM::TailCallKind::None,
516 LLVM::InlineAsmOp inlineAsmOp =
build();
517 LDBG() <<
"\n Generated PTX \n\t" << inlineAsmOp;
521 rewriter.eraseOp(interfaceOp);
525 if (needsManualRegisterMapping) {
526 rewriter.replaceOp(interfaceOp, inlineAsmOp->getResults());
532 registerModifiers)) {
535 if (interfaceOp->getNumResults() > 0) {
536 rewriter.replaceOp(interfaceOp, inlineAsmOp->getResults());
542 if (inlineAsmOp->getNumResults() > 0) {
543 Value postAsm = inlineAsmOp->getResult(0);
544 for (
auto [m, v] : llvm::zip(registerModifiers, ptxOperands)) {
547 v.replaceUsesWithIf(postAsm, [&](
OpOperand &use) {
549 return owner != interfaceOp && owner != inlineAsmOp;
554 rewriter.eraseOp(interfaceOp);
558 const bool hasRW = llvm::any_of(registerModifiers, [](
PTXRegisterMod m) {
563 assert(LLVM::LLVMStructType::classof(inlineAsmOp.getResultTypes().front()) &&
564 "expected struct return for multi-result inline asm");
565 Value structVal = inlineAsmOp.getResult(0);
570 if (!hasRW && interfaceOp->getResults().size() > 0) {
571 rewriter.replaceOp(interfaceOp, unpacked);
576 if (hasRW && interfaceOp->getResults().size() == 0) {
578 for (
auto [m, v] : llvm::zip(registerModifiers, ptxOperands)) {
581 Value repl = unpacked[idx++];
582 v.replaceUsesWithIf(repl, [&](
OpOperand &use) {
584 return owner != interfaceOp && owner != inlineAsmOp;
587 rewriter.eraseOp(interfaceOp);
595 for (
auto [m, v] : llvm::zip(registerModifiers, ptxOperands)) {
598 Value repl = unpacked[idx++];
599 v.replaceUsesWithIf(repl, [&](
OpOperand &use) {
601 return owner != interfaceOp && owner != inlineAsmOp;
606 tail.reserve(unpacked.size() - idx);
607 for (
unsigned i = idx, e = unpacked.size(); i < e; ++i)
608 tail.push_back(unpacked[i]);
610 rewriter.replaceOp(interfaceOp, tail);
static std::string canonicalizeRegisterConstraints(llvm::StringRef csv)
Canonicalize the register constraints:
constexpr llvm::StringLiteral kWriteOnlyPrefix
static SmallVector< Value > extractStructElements(PatternRewriter &rewriter, Location loc, Value structVal)
Extract every element of a struct value.
static FailureOr< char > getRegisterType(Type type, Location loc)
static constexpr int64_t kSharedMemorySpace
static unsigned getPredicateConstraintIndex(StringRef constraints)
Return the constraint index of the predicate operand.
static SmallVector< Type > packResultTypes(BasicPtxBuilderInterface interfaceOp, bool needsManualRegisterMapping, SmallVectorImpl< PTXRegisterMod > ®isterModifiers, SmallVectorImpl< Value > &ptxOperands)
Pack the result types of the interface operation.
static std::string rewriteAsmPlaceholders(llvm::StringRef ptxCode)
Rewrites {$rwN}, {$wN}, and {$rN} placeholders in ptxCode into compact $K indices:
static bool needsPackUnpack(BasicPtxBuilderInterface interfaceOp, bool needsManualRegisterMapping, SmallVectorImpl< PTXRegisterMod > ®isterModifiers)
Check if the operation needs to pack and unpack results.
constexpr llvm::StringLiteral kReadWritePrefix
constexpr llvm::StringLiteral kReadOnlyPrefix
static llvm::Regex getPredicateMappingRegex()
Returns a regex that matches {$rwN}, {$wN}, {$rN}.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
LogicalResult insertValue(Value v, PTXRegisterMod itype=PTXRegisterMod::Read)
Add an operand with the read/write input type.
LLVM::InlineAsmOp build()
Builds the inline assembly Op and returns it.
void buildAndReplaceOp()
Shortcut to build the inline assembly Op and replace or erase the original op with.
This class represents an operand of an operation.
Operation is the basic unit of execution within MLIR.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isFloat() const
Return true if this is an float type (with the specified width).
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isInteger() const
Return true if this is an integer type (with the specified width).
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Operation * getOwner() const
Return the owner of this operand.
PTXRegisterMod
Register read/write modifier to build constraint string for PTX inline https://docs....
@ Write
Write register with '=' modifier.
@ ReadWrite
ReadWrite register with '+' modifier.
@ Read
Read register with no modifier.
void countPlaceholderNumbers(StringRef ptxCode, llvm::SmallDenseSet< unsigned > &seenRW, llvm::SmallDenseSet< unsigned > &seenW, llvm::SmallDenseSet< unsigned > &seenR, llvm::SmallVectorImpl< unsigned > &rwNums, llvm::SmallVectorImpl< unsigned > &wNums, llvm::SmallVectorImpl< unsigned > &rNums)
Count the number of placeholder variables such as {$r}, {$w}, {$rw} in the PTX code.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.