[Mlir-commits] [mlir] [mlir][spirv] Add gpu printf op lowering to spirv.CL.printf op (PR #78510)

Jakub Kuderski llvmlistbot at llvm.org
Fri Sep 27 06:27:54 PDT 2024


================
@@ -597,6 +606,124 @@ class GPUSubgroupReduceConversion final
   }
 };
 
+/// Formulate unique variable/constant name after
+/// searching in the module for existing variable/constant names.
+/// This is to avoid name collision with existing variables.
+/// Example: printfMsg0, printfMsg1, printfMsg2, ...
+std::string constructVarName(spirv::ModuleOp moduleOp, llvm::StringRef prefix) {
+  std::string name;
+  unsigned number = 0;
+
+  do {
+    name.clear();
+    name = (prefix + llvm::Twine(number++)).str();
+  } while (moduleOp.lookupSymbol(name));
+
+  return name;
+}
+
+/// Pattern to convert a gpu.printf op into a SPIR-V CLPrintf op.
+
+LogicalResult GPUPrintfConversion::matchAndRewrite(
+    gpu::PrintfOp gpuPrintfOp, OpAdaptor adaptor,
+    ConversionPatternRewriter &rewriter) const {
+
+  Location loc = gpuPrintfOp.getLoc();
+
+  auto moduleOp = gpuPrintfOp->getParentOfType<spirv::ModuleOp>();
+  if (!moduleOp)
+    return failure();
+
+  // SPIR-V global variable is used to initialize printf
+  // format string value, if there are multiple printf messages,
+  // each global var needs to be created with a unique name.
+  std::string globalVarName = constructVarName(moduleOp, "printfMsg");
+  spirv::GlobalVariableOp globalVar;
+
+  IntegerType i8Type = rewriter.getI8Type();
+  IntegerType i32Type = rewriter.getI32Type();
+
+  // Each character of printf format string is
+  // stored as a spec constant. We need to create
+  // unique name for this spec constant like
+  // @printfMsg0_sc0, @printfMsg0_sc1, ... by searching in the module
+  // for existing spec constant names.
+  auto createSpecConstant = [&](unsigned value) {
+    auto attr = rewriter.getI8IntegerAttr(value);
+    std::string specCstName =
+        constructVarName(moduleOp, (llvm::Twine(globalVarName) + "_sc").str());
----------------
kuhar wrote:

You can make `constructVarName` take `Twine` as the prefix string.

https://github.com/llvm/llvm-project/pull/78510


More information about the Mlir-commits mailing list