[Mlir-commits] [mlir] [MLIR][Wasm] Introduce the WasmSSA MLIR dialect (PR #149233)
Ferdinand Lemaire
llvmlistbot at llvm.org
Fri Jul 18 00:03:20 PDT 2025
https://github.com/flemairen6 updated https://github.com/llvm/llvm-project/pull/149233
>From d8b21ad8f276fe085197abf67ff93a6365391613 Mon Sep 17 00:00:00 2001
From: Luc Forget <dev at alias.lforget.fr>
Date: Mon, 30 Jun 2025 15:10:12 +0200
Subject: [PATCH] [mlir][wasm] Introduce the MLIR wasm dialect
This dialect is an SSA representation of a WebAssembly program.
---------
Co-authored-by: Ferdinand Lemaire <ferdinand.lemaire at woven-planet.global>
Co-authored-by: Jessica Paquette <jessica.paquette at woven-planet.global>
---
mlir/include/mlir/Dialect/CMakeLists.txt | 1 +
.../Dialect/WebAssemblySSA/CMakeLists.txt | 1 +
.../Dialect/WebAssemblySSA/IR/CMakeLists.txt | 13 +
.../WebAssemblySSA/IR/WebAssemblySSA.h | 55 ++
.../WebAssemblySSA/IR/WebAssemblySSABase.td | 25 +
.../IR/WebAssemblySSAInterfaces.h | 28 +
.../IR/WebAssemblySSAInterfaces.td | 186 +++++
.../WebAssemblySSA/IR/WebAssemblySSAOps.td | 674 ++++++++++++++++++
.../WebAssemblySSA/IR/WebAssemblySSATypes.td | 86 +++
mlir/include/mlir/InitAllDialects.h | 2 +
mlir/lib/Dialect/CMakeLists.txt | 1 +
.../lib/Dialect/WebAssemblySSA/CMakeLists.txt | 1 +
.../Dialect/WebAssemblySSA/IR/CMakeLists.txt | 24 +
.../IR/WebAssemblySSADialect.cpp | 38 +
.../IR/WebAssemblySSAInterfaces.cpp | 61 ++
.../WebAssemblySSA/IR/WebAssemblySSAOps.cpp | 510 +++++++++++++
.../WebAssemblySSA/IR/WebAssemblySSATypes.cpp | 36 +
.../WebAssemblySSA/custom_parser/global.mlir | 44 ++
.../custom_parser/global_illegal.mlir | 23 +
.../WebAssemblySSA/custom_parser/import.mlir | 17 +
.../WebAssemblySSA/custom_parser/local.mlir | 45 ++
21 files changed, 1871 insertions(+)
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/CMakeLists.txt
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/CMakeLists.txt
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.td
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.td
create mode 100644 mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.td
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/CMakeLists.txt
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/IR/CMakeLists.txt
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSADialect.cpp
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.cpp
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp
create mode 100644 mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.cpp
create mode 100644 mlir/test/Dialect/WebAssemblySSA/custom_parser/global.mlir
create mode 100644 mlir/test/Dialect/WebAssemblySSA/custom_parser/global_illegal.mlir
create mode 100644 mlir/test/Dialect/WebAssemblySSA/custom_parser/import.mlir
create mode 100644 mlir/test/Dialect/WebAssemblySSA/custom_parser/local.mlir
diff --git a/mlir/include/mlir/Dialect/CMakeLists.txt b/mlir/include/mlir/Dialect/CMakeLists.txt
index 56dc97282fa4a..eb6075ac76c85 100644
--- a/mlir/include/mlir/Dialect/CMakeLists.txt
+++ b/mlir/include/mlir/Dialect/CMakeLists.txt
@@ -41,5 +41,6 @@ add_subdirectory(Transform)
add_subdirectory(UB)
add_subdirectory(Utils)
add_subdirectory(Vector)
+add_subdirectory(WebAssemblySSA)
add_subdirectory(X86Vector)
add_subdirectory(XeGPU)
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/CMakeLists.txt b/mlir/include/mlir/Dialect/WebAssemblySSA/CMakeLists.txt
new file mode 100644
index 0000000000000..f33061b2d87cf
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(IR)
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/CMakeLists.txt b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/CMakeLists.txt
new file mode 100644
index 0000000000000..fa41a0caabf91
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/CMakeLists.txt
@@ -0,0 +1,13 @@
+set(LLVM_TARGET_DEFINITIONS WebAssemblySSATypes.td)
+mlir_tablegen(WebAssemblySSATypeConstraints.h.inc -gen-type-constraint-decls)
+mlir_tablegen(WebAssemblySSATypeConstraints.cpp.inc -gen-type-constraint-defs)
+
+set (LLVM_TARGET_DEFINITIONS WebAssemblySSAInterfaces.td)
+mlir_tablegen(WebAssemblySSAInterfaces.h.inc -gen-op-interface-decls)
+mlir_tablegen(WebAssemblySSAInterfaces.cpp.inc -gen-op-interface-defs)
+add_public_tablegen_target(MLIRWebAssemblySSAInterfacesIncGen)
+
+set(LLVM_TARGET_DEFINITIONS WebAssemblySSAOps.td)
+
+add_mlir_dialect(WebAssemblySSAOps wasmssa)
+add_mlir_doc(WebAssemblySSAOps WebAssemblySSAOps Dialects/ -gen-dialect-doc)
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h
new file mode 100644
index 0000000000000..816f7ef008d4a
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h
@@ -0,0 +1,55 @@
+//===- WebAssemblySSA.h - WebAssemblySSA dialect ------------------*- C++-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSA_H_
+#define MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSA_H_
+
+#include "mlir/Bytecode/BytecodeOpInterface.h"
+#include "mlir/IR/Dialect.h"
+
+//===----------------------------------------------------------------------===//
+// WebAssemblyDialect
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOpsDialect.h.inc"
+
+//===----------------------------------------------------------------------===//
+// WebAssembly Dialect Types
+//===----------------------------------------------------------------------===//
+
+#define GET_TYPEDEF_CLASSES
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOpsTypes.h.inc"
+
+//===----------------------------------------------------------------------===//
+// WebAssembly Interfaces
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h"
+
+//===----------------------------------------------------------------------===//
+// WebAssembly Dialect Operations
+//===----------------------------------------------------------------------===//
+#include "mlir/IR/SymbolTable.h"
+#include "mlir/Interfaces/CallInterfaces.h"
+#include "mlir/Interfaces/FunctionInterfaces.h"
+#include "mlir/Interfaces/InferTypeOpInterface.h"
+
+//===----------------------------------------------------------------------===//
+// WebAssembly Constraints
+//===----------------------------------------------------------------------===//
+
+namespace mlir {
+namespace wasmssa {
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypeConstraints.h.inc"
+}
+} // namespace mlir
+
+#define GET_OP_CLASSES
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.h.inc"
+
+#endif // MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSA_H_
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td
new file mode 100644
index 0000000000000..cdc4d4864344f
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td
@@ -0,0 +1,25 @@
+//===- WebAssemblySSABase.td - Base defs for wasmssa dialect -*- tablegen -*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef WEBASSEMBLYSSA_BASE
+#define WEBASSEMBLYSSA_BASE
+
+include "mlir/IR/EnumAttr.td"
+include "mlir/IR/OpBase.td"
+
+def WasmSSA_Dialect : Dialect {
+ let name = "wasmssa";
+ let cppNamespace = "::mlir::wasmssa";
+ let description = [{
+ The `wasmssa` dialect is intended to represent WebAssembly
+ modules in SSA form for easier manipulation.
+ }];
+ let useDefaultTypePrinterParser = true;
+}
+
+#endif //WEBASSEMBLYSSA_BASE
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h
new file mode 100644
index 0000000000000..03c4021b1421b
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h
@@ -0,0 +1,28 @@
+//===- WebAssemblySSAInterfaces.h - WebAssemblySSA Interfaces ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines op interfaces for the WebAssemblySSA dialect in MLIR.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSAINTERFACES_H_
+#define MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSAINTERFACES_H_
+
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/OpDefinition.h"
+
+namespace mlir::wasmssa {
+namespace detail {
+LogicalResult verifyConstantExpressionInterface(Operation *op);
+LogicalResult verifyWasmSSALabelBranchingInterface(Operation *op);
+} // namespace detail
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h.inc"
+} // namespace mlir::wasmssa
+
+#endif // MLIR_DIALECT_WEBASSEMBLYSSA_IR_WEBASSEMBLYSSAINTERFACES_H_
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.td b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.td
new file mode 100644
index 0000000000000..7857556871c3f
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.td
@@ -0,0 +1,186 @@
+//===-- WebAssemblySSAInterfaces.td - WebAssemblySSA Interfaces -*- tablegen -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines interfaces for the WebAssemblySSA dialect in MLIR.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef WEBASSEMBLYSSA_INTERFACES
+#define WEBASSEMBLYSSA_INTERFACES
+
+include "mlir/IR/OpBase.td"
+include "mlir/IR/BuiltinAttributes.td"
+
+def WasmSSALabelLevelInterface : OpInterface<"WasmSSALabelLevelInterface"> {
+ let description = [{
+ Operation that defines one level of nesting for wasm branching.
+ These operation region can be targeted by branch instructions.
+ }];
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ "Returns the target block address",
+ /*returnType=*/ "::mlir::Block*",
+ /*methodName=*/ "getLabelTarget",
+ /*args=*/ (ins)
+ >
+ ];
+}
+
+def WasmSSALabelBranchingInterface : OpInterface<"WasmSSALabelBranchingInterface"> {
+ let description = [{
+ Wasm operation that targets a label for a jump.
+ }];
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ "Returns the number of context to break from",
+ /*returnType=*/ "size_t",
+ /*methodName=*/ "getExitLevel",
+ /*args=*/ (ins)
+ >,
+ InterfaceMethod<
+ /*desc=*/ "Returns the destination of this operation",
+ /*returnType=*/ "WasmSSALabelLevelInterface",
+ /*methodName=*/ "getTargetOp",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{
+ return *WasmSSALabelBranchingInterface::getTargetOpFromBlock($_op.getOperation()->getBlock(), $_op.getExitLevel());
+ }]
+ >,
+ InterfaceMethod<
+ /*desc=*/ "Return the target control flow ops that defined the label of this operation",
+ /*returnType=*/ "::mlir::Block*",
+ /*methodName=*/ "getTarget",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{}],
+ /*defaultImpl=*/ [{
+ auto op = mlir::cast<WasmSSALabelBranchingInterface>(this->getOperation());
+ return op.getTargetOp().getLabelTarget();
+ }]
+ >
+ ];
+ let extraClassDeclaration = [{
+ static ::llvm::FailureOr<WasmSSALabelLevelInterface> getTargetOpFromBlock(::mlir::Block *block, uint32_t level);
+ }];
+ let verify = [{return verifyWasmSSALabelBranchingInterface($_op);}];
+}
+
+def WasmSSAImportOpInterface : OpInterface<"WasmSSAImportOpInterface"> {
+ let description = [{
+ Operation that imports a symbol from an external wasm module;
+ }];
+
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ "Returns the module name for the import",
+ /*returnType=*/ "::llvm::StringRef",
+ /*methodName=*/ "getModuleName",
+ /*args=*/ (ins)
+ >,
+ InterfaceMethod<
+ /*desc=*/ "Returns the import name for the import",
+ /*returnType=*/ "::llvm::StringRef",
+ /*methodName=*/ "getImportName",
+ /*args=*/ (ins)
+ >,
+ InterfaceMethod<
+ /*desc=*/ "Returns the wasm index based symbol of the op",
+ /*returnType=*/ "::mlir::StringAttr",
+ /*methodName=*/ "getSymbolName",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{}],
+ /*defaultImpl=*/ [{
+ auto op = mlir::cast<ConcreteOp>(this->getOperation());
+ return op.getSymNameAttr();
+ }]
+ >,
+ InterfaceMethod<
+ /*desc=*/ "Returns the qualified name of the import",
+ /*returnType=*/ "std::string",
+ /*methodName=*/ "getQualifiedImportName",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{
+ return ($_op.getModuleName() + llvm::Twine{"::"} + $_op.getImportName()).str();
+ }]
+ >,
+ ];
+}
+
+def WasmSSAConstantExpressionInitializerInterface :
+ OpInterface<"WasmSSAConstantExpressionInitializerInterface"> {
+ let description = [{
+ Operation that must be constant initialized. This
+ interface adds a verifier that checks that all ops
+ within the initializer region are "constant expressions"
+ as defined by the WASM standard.
+ }];
+
+ let verify = [{ return detail::verifyConstantExpressionInterface($_op); }];
+}
+
+def WasmSSAConstantExprCheckInterface :
+ OpInterface<"WasmSSAConstantExprCheckInterface"> {
+ let description = [{
+ Base interface for operations that can be used in a Wasm Constant Expression.
+ It shouldn't be used directly, use one of the derived instead.
+ }];
+
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ [{
+ Returns success if the current operation is valid in a constant expression context.
+ }],
+ /*returnType=*/ "::mlir::LogicalResult",
+ /*methodName=*/ "isValidInConstantExpr",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{
+ return $_op.verifyConstantExprValidity();
+ }]
+ >
+ ];
+}
+
+def WasmSSAContextuallyConstantExprInterface :
+ OpInterface<"WasmSSAContextuallyConstantExprInterface", [WasmSSAConstantExprCheckInterface]> {
+ let description = [{
+ Base interface for operations that can be used in a Wasm Constant Expression
+ depending on the context.
+ }];
+
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ [{
+ Returns success if the current operation is valid in a constant expression context.
+ }],
+ /*returnType=*/ "::mlir::LogicalResult",
+ /*methodName=*/ "verifyConstantExprValidity",
+ /*args=*/ (ins)
+ >
+ ];
+}
+
+def WasmSSAConstantExprInterface :
+ OpInterface<"WasmSSAConstantExprInterface", [WasmSSAConstantExprCheckInterface]> {
+ let description = [{
+ Base interface for operations that can always be used in a Wasm Constant Expression.
+ }];
+
+ let methods = [
+ InterfaceMethod<
+ /*desc=*/ [{
+ Returns success if the current operation is valid in a constant expression context.
+ }],
+ /*returnType=*/ "::mlir::LogicalResult",
+ /*methodName=*/ "verifyConstantExprValidity",
+ /*args=*/ (ins),
+ /*methodBody=*/ [{}],
+ /*DefaultImplementation=*/ [{ return success(); }]
+ >
+ ];
+}
+
+#endif // WEBASSEMBLYSSA_INTERFACES
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.td b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.td
new file mode 100644
index 0000000000000..9e370920f3173
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.td
@@ -0,0 +1,674 @@
+//===- WebAssemblySSAOps.td - WebAssemblySSA op definitions -*- tablegen -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef WEBASSEMBLYSSA_OPS
+#define WEBASSEMBLYSSA_OPS
+
+
+include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td"
+include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.td"
+include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.td"
+
+include "mlir/Interfaces/FunctionInterfaces.td"
+include "mlir/Interfaces/InferTypeOpInterface.td"
+include "mlir/IR/BuiltinAttributeInterfaces.td"
+include "mlir/IR/SymbolInterfaces.td"
+
+class WasmSSA_Op<string mnemonic, list<Trait> traits = []> :
+ Op<WasmSSA_Dialect, mnemonic, traits>;
+
+class WasmSSA_BlockLikeOp<string mnemonic, string summaryStr> :
+ WasmSSA_Op<mnemonic, [Terminator, DeclareOpInterfaceMethods<WasmSSALabelLevelInterface>]> {
+ let summary = summaryStr;
+ let arguments = (ins Variadic<WasmSSA_ValType>: $inputs);
+ let regions = (region AnyRegion: $body);
+ let successors = (successor AnySuccessor: $target);
+ let extraClassDeclaration = [{
+ ::mlir::Block* createBlock() {
+ auto &block = getBody().emplaceBlock();
+ for (auto input : getInputs())
+ block.addArgument(input.getType(), input.getLoc());
+ return █
+ }
+ }];
+ let assemblyFormat = "(`(`$inputs^`)` `:` type($inputs))? attr-dict `:` $body `>` $target";
+}
+
+def WasmSSA_BlockOp : WasmSSA_BlockLikeOp<"block", "Create a nesting level"> {}
+
+def WasmSSA_LoopOp : WasmSSA_BlockLikeOp<"loop", "Create a nesting level similar to Block Op, except that it has itself as a successor."> {}
+
+def WasmSSA_BlockReturnOp : WasmSSA_Op<"block_return", [Terminator,
+ DeclareOpInterfaceMethods<WasmSSALabelBranchingInterface>]> {
+ let summary = "Return from the current block";
+ let arguments = (ins Variadic<WasmSSA_ValType>: $inputs);
+ let extraClassDeclaration = [{
+ ::mlir::Block* getTarget();
+ }];
+ let assemblyFormat = "($inputs^ `:` type($inputs))? attr-dict";
+}
+
+def WasmSSA_BranchIfOp : WasmSSA_Op<"branch_if", [
+ Terminator,
+ DeclareOpInterfaceMethods<WasmSSALabelBranchingInterface>]> {
+ let summary = "Jump to target level if condition has non-zero value";
+ let arguments = (ins I32: $condition,
+ UI32Attr: $exitLevel,
+ Variadic<WasmSSA_ValType>: $inputs);
+ let successors = (successor AnySuccessor: $elseSuccessor);
+ let assemblyFormat = "$condition `to` `level` $exitLevel (`with` `args` `(`$inputs^ `:` type($inputs)`)`)? `else` $elseSuccessor attr-dict";
+}
+
+def WasmSSA_ConstOp : WasmSSA_Op<"const", [
+ AllTypesMatch<["value", "result"]>, WasmSSAConstantExprInterface]> {
+ let summary = "Operator that represents a constant value";
+ let arguments = (ins TypedAttrInterface: $value);
+ let results = (outs WasmSSA_NumericType: $result);
+ let assemblyFormat = "$value attr-dict";
+}
+
+def WasmSSA_FuncOp : WasmSSA_Op<"func", [
+ AffineScope, AutomaticAllocationScope,
+ DeclareOpInterfaceMethods<FunctionOpInterface>,
+ IsolatedFromAbove,
+ Symbol]> {
+ let description = [{
+ Represents a Wasm function definition.
+
+ In Wasm function, locals and function arguments are interchangeable.
+ They are for instance both accessed using `local.get` instruction.
+
+ On the other hand, a function type is defined as a pair of tuples of Wasm value types.
+ To model this, the wasm.func operation has:
+
+ - A function type that represents the corresponding wasm type (tuples of value types)
+
+ - Arguments of the entry block of type `!wasm<local T>`, with T the corresponding type
+ in the function type.
+ }];
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ WasmSSA_FuncTypeAttr: $functionType,
+ OptionalAttr<DictArrayAttr>:$arg_attrs,
+ OptionalAttr<DictArrayAttr>:$res_attrs,
+ DefaultValuedAttr<StrAttr, "\"nested\"">:$sym_visibility);
+ let regions = (region AnyRegion: $body);
+ let extraClassDeclaration = [{
+
+ /// Create the entry block for the function with parameters wrapped in local ref.
+ ::mlir::Block* addEntryBlock();
+
+ //===------------------------------------------------------------------===//
+ // FunctionOpInterface Methods
+ //===------------------------------------------------------------------===//
+
+ /// Returns the region on the current operation that is callable. This may
+ /// return null in the case of an external callable object, e.g. an external
+ /// function.
+ ::mlir::Region *getCallableRegion() { return isExternal() ? nullptr : &getBody(); }
+
+ ::mlir::LogicalResult verifyBody();
+
+ /// Returns the argument types of this function.
+ ArrayRef<Type> getArgumentTypes() { return getFunctionType().getInputs(); }
+
+ /// Returns the result types of this function.
+ ArrayRef<Type> getResultTypes() { return getFunctionType().getResults(); }
+ }];
+
+ let builders = [
+ OpBuilder<(ins "llvm::StringRef":$symbol, "FunctionType":$funcType )>
+ ];
+ let hasCustomAssemblyFormat = 1;
+}
+
+def WasmSSA_FuncCallOp : WasmSSA_Op<"call"> {
+ let summary = "Calling a wasm function";
+ let arguments = (ins FlatSymbolRefAttr: $callee,
+ Variadic<WasmSSA_ValType>: $operands);
+ let results = (outs Variadic<WasmSSA_ValType>: $results);
+ let assemblyFormat = "$callee (`(`$operands^`)`)? attr-dict `:` functional-type($operands, $results)";
+ let description = [{
+ Emits a call to callee.
+ }];
+}
+
+def WasmSSA_FuncImportOp : WasmSSA_Op<"import_func", [
+ Symbol,
+ CallableOpInterface,
+ WasmSSAImportOpInterface]> {
+ let summary = "Importing a function variable";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ StrAttr: $moduleName,
+ StrAttr: $importName,
+ WasmSSA_FuncTypeAttr: $type,
+ OptionalAttr<DictArrayAttr>:$arg_attrs,
+ OptionalAttr<DictArrayAttr>:$res_attrs,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let extraClassDeclaration = [{
+ bool isDeclaration() const { return true; }
+
+ Region *getCallableRegion() { return nullptr; }
+
+ llvm::ArrayRef<Type> getArgumentTypes() {
+ return getType().getInputs();
+ }
+
+ llvm::ArrayRef<Type> getResultTypes() {
+ return getType().getResults();
+ }
+ }];
+ let builders = [
+ OpBuilder<(ins "StringRef":$symbol,
+ "StringRef":$moduleName,
+ "StringRef":$importName,
+ "FunctionType": $type)>
+ ];
+ let assemblyFormat = "$importName `from` $moduleName `as` $sym_name attr-dict";
+}
+
+def WasmSSA_GlobalOp : WasmSSA_Op<"global", [
+ AffineScope, AutomaticAllocationScope,
+ IsolatedFromAbove, Symbol, WasmSSAConstantExpressionInitializerInterface]> {
+ let summary= "WebAssembly global value";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ WasmSSA_ValTypeAttr: $type,
+ UnitAttr: $isMutable,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let description = [{
+ WebAssembly global variable.
+ Body contains the initialization instructions for the variable value.
+ }];
+ let regions = (region AnyRegion: $initializer);
+
+ let builders = [
+ OpBuilder<(ins "StringRef":$symbol,
+ "Type": $type,
+ "bool": $isMutable)>
+ ];
+ let hasCustomAssemblyFormat = 1;
+}
+
+def WasmSSA_GlobalImportOp : WasmSSA_Op<"import_global", [
+ Symbol,
+ WasmSSAImportOpInterface]> {
+ let summary = "Importing a global variable";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ StrAttr: $moduleName,
+ StrAttr: $importName,
+ WasmSSA_ValTypeAttr: $type,
+ UnitAttr: $isMutable,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let extraClassDeclaration = [{
+ bool isDeclaration() const { return true; }
+ }];
+ let builders = [
+ OpBuilder<(ins "StringRef":$symbol,
+ "StringRef":$moduleName,
+ "StringRef":$importName,
+ "Type": $type,
+ "bool": $isMutable)>
+ ];
+ let hasCustomAssemblyFormat = 1;
+}
+
+def WasmSSA_GlobalGetOp : WasmSSA_Op<"global_get", [DeclareOpInterfaceMethods<WasmSSAContextuallyConstantExprInterface>]> {
+ let summary = "Returns the value of the global passed as argument.";
+ let arguments = (ins FlatSymbolRefAttr: $global);
+ let results = (outs WasmSSA_ValType: $global_val);
+ let assemblyFormat = "$global attr-dict `:` type($global_val)";
+}
+
+def WasmSSA_IfOp : WasmSSA_Op<"if", [Terminator,
+ DeclareOpInterfaceMethods<WasmSSALabelLevelInterface>]> {
+ let summary = "Execute the if region if condition value is nonzero, the else region otherwise.";
+ let arguments = (ins I32:$condition, Variadic<WasmSSA_ValType>: $inputs);
+ let regions = (region AnyRegion: $if, AnyRegion: $else);
+ let successors = (successor AnySuccessor: $target);
+ let extraClassDeclaration = [{
+ private:
+ inline ::mlir::Block* createBlock(::mlir::Region& region) {
+ assert(region.empty() && "Creating entry block on non empty region");
+ assert(region.getParentOp() == this->getOperation() &&
+ "Creating block for region that isn't part of the current op");
+ auto &block = region.emplaceBlock();
+ for (auto input : getInputs())
+ block.addArgument(input.getType(), input.getLoc());
+ return █
+ }
+
+ public:
+ ::mlir::Block* createIfBlock() {
+ return createBlock(getIf());
+ }
+ ::mlir::Block* createElseBlock() {
+ return createBlock(getElse());
+ }
+ }];
+}
+
+def WasmSSA_LocalOp : WasmSSA_Op<"local", [
+ DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
+ let summary = "Declaration of local variable";
+ let arguments = (ins WasmSSA_ValTypeAttr: $type);
+ let results = (outs WasmSSA_LocalRef: $result);
+ let assemblyFormat = "`of` `type` $type attr-dict";
+}
+
+def WasmSSA_LocalGetOp : WasmSSA_Op<"local_get", [
+ DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
+ let summary = "Set local to value and return the operand.";
+ let arguments = (ins WasmSSA_LocalRef: $localVar);
+ let results = (outs WasmSSA_ValType: $result);
+ let assemblyFormat = "$localVar `:` type($localVar) attr-dict";
+ let hasVerifier = 1;
+}
+
+def WasmSSA_LocalSetOp : WasmSSA_Op<"local_set"> {
+ let summary = "Set local to given value";
+ let arguments = (ins WasmSSA_LocalRef: $localVar,
+ WasmSSA_ValType: $value);
+ let hasVerifier = 1;
+ let assemblyFormat = "$localVar `:` type($localVar) `to` $value `:` type($value) attr-dict";
+}
+
+def WasmSSA_LocalTeeOp : WasmSSA_Op<"local_tee", [
+ DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
+ let summary = "Set local to value and return the operand.";
+ let arguments = (ins WasmSSA_LocalRef: $localVar,
+ WasmSSA_ValType: $value);
+ let results = (outs WasmSSA_ValType: $result);
+ let hasVerifier = 1;
+ let assemblyFormat = "$localVar `:` type($localVar) `to` $value `:` type($value) attr-dict";
+}
+
+def WasmSSA_MemOp : WasmSSA_Op<"memory", [Symbol]> {
+ let summary= "WebAssembly memory definition";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ WasmSSA_LimitTypeAttr: $limits,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let builders = [
+ OpBuilder<(ins
+ "llvm::StringRef":$symbol,
+ "LimitType":$limit)>
+ ];
+}
+
+def WasmSSA_MemImportOp : WasmSSA_Op<"import_mem", [Symbol, WasmSSAImportOpInterface]> {
+ let summary = "Importing a memory";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ StrAttr: $moduleName,
+ StrAttr: $importName,
+ WasmSSA_LimitTypeAttr: $limits,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let extraClassDeclaration = [{
+ bool isDeclaration() const { return true; }
+ }];
+ let builders = [OpBuilder<(ins
+ "llvm::StringRef":$symbol,
+ "llvm::StringRef":$moduleName,
+ "llvm::StringRef":$importName,
+ "wasmssa::LimitType":$limits)>];
+ let assemblyFormat = "$importName `from` $moduleName `as` $sym_name attr-dict";
+}
+
+def WasmSSA_TableOp : WasmSSA_Op<"table", [Symbol]> {
+ let summary= "WebAssembly table value";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ WasmSSA_TableTypeAttr: $type,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let builders = [OpBuilder<(ins
+ "llvm::StringRef":$symbol,
+ "wasmssa::TableType":$type)>];
+}
+
+def WasmSSA_TableImportOp : WasmSSA_Op<"import_table", [Symbol, WasmSSAImportOpInterface]> {
+ let summary = "Importing a table";
+ let arguments = (ins SymbolNameAttr: $sym_name,
+ StrAttr: $moduleName,
+ StrAttr: $importName,
+ WasmSSA_TableTypeAttr: $type,
+ OptionalAttr<StrAttr>:$sym_visibility);
+ let extraClassDeclaration = [{
+ bool isDeclaration() const { return true; }
+ }];
+ let assemblyFormat = "$importName `from` $moduleName `as` $sym_name attr-dict";
+ let builders = [OpBuilder<(ins
+ "llvm::StringRef":$symbol,
+ "llvm::StringRef":$moduleName,
+ "llvm::StringRef":$importName,
+ "wasmssa::TableType":$type)>];
+}
+
+def WasmSSA_ReturnOp : WasmSSA_Op<"return", [Terminator]> {
+ let summary = "Return from the current function frame";
+ let arguments = (ins Variadic<WasmSSA_ValType>: $operands);
+ let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?";
+ let builders = [
+ OpBuilder<(ins)>
+ ];
+}
+
+// ---- Numeric ops
+
+class WasmSSA_BinaryNumericalOp<string mnemonic, string summaryStr,
+ list<Type> validOpTypes> :
+ WasmSSA_Op<mnemonic, [AllTypesMatch<["lhs", "rhs", "result"]>]> {
+ let summary = summaryStr;
+ let arguments = (ins AnyTypeOf<validOpTypes>:$lhs, AnyTypeOf<validOpTypes>:$rhs);
+ let results = (outs AnyTypeOf<validOpTypes>:$result);
+ let assemblyFormat = "$lhs $rhs `:` type($lhs) attr-dict";
+}
+
+def WasmSSA_AddOp : WasmSSA_BinaryNumericalOp<"add",
+ "Sum two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_AndOp : WasmSSA_BinaryNumericalOp<"and",
+ "Compute the bitwise AND between two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_DivOp : WasmSSA_BinaryNumericalOp<"div",
+ "Division between floating point values",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_DivUIOp : WasmSSA_BinaryNumericalOp<"div_ui",
+ "Divide values interpreted as unsigned int",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_DivSIOp : WasmSSA_BinaryNumericalOp<"div_si",
+ "Divide values interpreted as signed int",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_MulOp : WasmSSA_BinaryNumericalOp<"mul",
+ "Multiply two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_OrOp : WasmSSA_BinaryNumericalOp<"or",
+ "Compute the bitwise OR of two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_SubOp : WasmSSA_BinaryNumericalOp<"sub",
+ "Subtract two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_RemUIOp : WasmSSA_BinaryNumericalOp<"rem_ui",
+ "Calculate the remainder of dividing two integer values as an unsigned integer",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_RemSIOp : WasmSSA_BinaryNumericalOp<"rem_si",
+ "Calculate the remainder of dividing two integer values as signed integer",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_XOrOp : WasmSSA_BinaryNumericalOp<"xor",
+ "Compute the bitwise XOR of two values",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_MinOp : WasmSSA_BinaryNumericalOp<"min",
+ "Compute the minimum of two floating point values.",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_MaxOp : WasmSSA_BinaryNumericalOp<"max",
+ "Compute the minimum of two floating point values.",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_CopySignOp : WasmSSA_BinaryNumericalOp<"copysign",
+ "Copy sign from one floating point vaue to the other.",
+ [WasmSSA_FPType]>{}
+
+class WasmSSA_BinaryComparisonOp<string mnemonic, string summaryStr,
+ list<Type> validOpTypes> :
+ WasmSSA_Op<mnemonic, [AllTypesMatch<["lhs", "rhs"]>]> {
+ let summary = summaryStr;
+ let arguments = (ins AnyTypeOf<validOpTypes>:$lhs, AnyTypeOf<validOpTypes>:$rhs);
+ let results = (outs I32:$result);
+ let assemblyFormat = "$lhs $rhs `:` type($lhs) `->` type($result) attr-dict";
+}
+
+def WasmSSA_EqOp : WasmSSA_BinaryComparisonOp<"eq",
+ "Check if two values are equal",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_NeOp : WasmSSA_BinaryComparisonOp<"ne",
+ "Check if two values are different",
+ [WasmSSA_NumericType]>{}
+
+def WasmSSA_LtSIOp : WasmSSA_BinaryComparisonOp<"lt_si",
+ "Check if a signed integer value is less than another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_LtUIOp : WasmSSA_BinaryComparisonOp<"lt_ui",
+ "Check if an unsigned integer value is less than another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_LeSIOp : WasmSSA_BinaryComparisonOp<"le_si",
+ "Check if a signed integer value is less or equal to another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_LeUIOp : WasmSSA_BinaryComparisonOp<"le_ui",
+ "Check if an unsigned integer value is less or equal to another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_GtSIOp : WasmSSA_BinaryComparisonOp<"gt_si",
+ "Check if a signed integer value is greater than another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_GtUIOp : WasmSSA_BinaryComparisonOp<"gt_ui",
+ "Check if an unsigned integer value is greater than another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_GeSIOp : WasmSSA_BinaryComparisonOp<"ge_si",
+ "Check if a signed integer value is greater or equal to another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_GeUIOp : WasmSSA_BinaryComparisonOp<"ge_ui",
+ "Check if an unsigned integer value is greater or equal to another",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_LtOp : WasmSSA_BinaryComparisonOp<"lt",
+ "Check if a float value is less than another",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_LeOp : WasmSSA_BinaryComparisonOp<"le",
+ "Check if a float value is less or equal to another",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_GtOp : WasmSSA_BinaryComparisonOp<"gt",
+ "Check if a float value is greater than another",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_GeOp : WasmSSA_BinaryComparisonOp<"ge",
+ "Check if a float value is greater or equal to another",
+ [WasmSSA_FPType]>{}
+
+// Integer shift and rotate operations.
+class WasmSSA_ShiftRotateOp<string mnemonic, string summaryStr> :
+ WasmSSA_Op<mnemonic, [AllTypesMatch<["val", "bits", "result"]>]> {
+ let summary = summaryStr;
+ let arguments = (ins WasmSSA_IntegerType:$val, WasmSSA_IntegerType:$bits);
+ let results = (outs WasmSSA_IntegerType:$result);
+ let assemblyFormat = "$val `by` $bits `bits` `:` type($val) attr-dict";
+}
+
+def WasmSSA_ShLOp : WasmSSA_ShiftRotateOp<"shl",
+ [{Consume an integer and an integer shift amount. The first
+ integer shall be shifted left by N bits, where N is the value of the second
+ integer.}]
+ >{}
+
+def WasmSSA_ShRSOp : WasmSSA_ShiftRotateOp<"shr_s",
+ [{Arithmetic right shift.
+
+ Consume an integer and an integer shift amount. The first
+ integer shall be shifted right by N bits, where N is the value of the
+ second integer.
+
+ Vacated bits on the left shall be filled with the sign bit.}]
+ >{}
+
+def WasmSSA_ShRUOp : WasmSSA_ShiftRotateOp<"shr_u",
+ [{Logical right shift.
+
+ Consume an integer, and an integer shift amount. The first
+ integer shall be shifted right by N bits, where N is the value of the
+ second integer.
+
+ Vacated bits on the left shall be filled with zeroes.}]
+ >{}
+
+def WasmSSA_RotlOp : WasmSSA_ShiftRotateOp<"rotl",
+ [{Rotate left.
+
+ Consume an integer and an integer rotate. The first
+ integer shall be rotated left by N bits, where N is the value of the
+ second integer.}]
+ >{}
+
+def WasmSSA_RotrOp : WasmSSA_ShiftRotateOp<"rotr",
+ [{Rotate right.
+
+ Consume an integer, and an integer rotate. The first
+ integer shall be rotated right by N bits, where N is the value of the
+ second integer.}]
+ >{}
+
+class WasmSSA_ConversionOp<string mnemonic, string summaryStr,
+ list<Type> ValidInputTypes,
+ list<Type> ValidOutputTypes> :
+ WasmSSA_Op<mnemonic> {
+ let summary = summaryStr;
+ let arguments = (ins AnyTypeOf<ValidInputTypes>:$input);
+ let results = (outs AnyTypeOf<ValidOutputTypes>:$result);
+ let assemblyFormat = "$input `:` type($input) `to` type($result) attr-dict";
+}
+
+def WasmSSA_ConvertUOp : WasmSSA_ConversionOp<"convert_u",
+ [{Convert integer, interpreted as binary encoded positive value, to floating-point value.
+
+ Consume an integer and produces a floating point value containing the rounded value of the original operand. Rounding is round to nearest, tie to even.}],
+ [WasmSSA_IntegerType],
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_ConvertSOp : WasmSSA_ConversionOp<"convert_s",
+ [{Convert integer interpreted as 2's complement signed value to floating-point value.
+
+ Consume an integer and produces a floating point value containing the rounded value of the original operand. Rounding is round to nearest, tie to even.}],
+ [WasmSSA_IntegerType],
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_DemoteOp : WasmSSA_ConversionOp<"demote",
+ "Convert a f64 value to f32",
+ [F64],
+ [F32]>{}
+
+def WasmSSA_ExtendSI32Op : WasmSSA_Op<"extend_i32_s">{
+ let summary = [{Sign extend i32 to i64.}];
+ let arguments = (ins I32:$input);
+ let results = (outs I64:$result);
+ let assemblyFormat = "$input `to` type($result) attr-dict";
+}
+
+def WasmSSA_ExtendUI32Op : WasmSSA_Op<"extend_i32_u">{
+ let summary = [{Zero extend i32 to i64.}];
+ let arguments = (ins I32:$input);
+ let results = (outs I64:$result);
+ let assemblyFormat = "$input `to` type($result) attr-dict";
+}
+
+def WasmSSA_ExtendLowBitsSOp : WasmSSA_Op<"extend", [AllTypesMatch<["input", "result"]>]> {
+ let summary = "";
+ let description = [{
+ Extend low bytes of a value to fit a given width.
+ For instance, signed extension from 8 low bits of the 32-bits integer value
+ 254 (0x000000FE) would produce the value -2 (0xFFFFFFFE).
+
+ This corresponds to the `extendnn` instruction of Wasm, which shouldn't be
+ confused with the `extend_inn` Wasm instruction, for which all input bits
+ are used and widened to wider output type.
+ In this operation, input and output types are the same.
+ }];
+ let arguments = (ins WasmSSA_IntegerType:$input, Builtin_IntegerAttr: $bitsToTake);
+ let results = (outs WasmSSA_IntegerType: $result);
+ let hasVerifier = 1;
+ let hasCustomAssemblyFormat = 1;
+}
+
+def WasmSSA_PromoteOp : WasmSSA_ConversionOp<"promote",
+ "Get f64 representation of a f32 value.",
+ [Builtin_Float32],
+ [Builtin_Float64]>{}
+
+def WasmSSA_WrapOp : WasmSSA_ConversionOp<"wrap",
+ "Cast an i64 to i32 by using a wrapping mechanism: y = x mod 2^32",
+ [I64],
+ [I32]>{}
+// Reinterpret ops are basically all one-offs. They all have an unique,
+// type-postfixed opcode, and support exactly one input and output type.
+def WasmSSA_ReinterpretOp : WasmSSA_ConversionOp<"reinterpret",
+ [{Reinterpret the value represented by a bit vector by
+ bit-casting it to another type of same representation width.}],
+ [WasmSSA_NumericType], [WasmSSA_NumericType]>{
+ let assemblyFormat = "$input `:` type($input) `as` type($result) attr-dict";
+ let hasVerifier = 1;
+}
+
+class WasmSSA_UnaryNumericalOp<string mnemonic,
+ string summaryStr,
+ list<Type> validOpTypes> :
+ WasmSSA_Op<mnemonic, [AllTypesMatch<["src", "result"]>]> {
+ let summary = summaryStr;
+ let arguments = (ins AnyTypeOf<validOpTypes>:$src);
+ let results = (outs AnyTypeOf<validOpTypes>:$result);
+ let assemblyFormat = "$src`:` type($src) attr-dict";
+}
+
+def WasmSSA_AbsOp : WasmSSA_UnaryNumericalOp<"abs",
+ "Floating point absolute value",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_CeilOp : WasmSSA_UnaryNumericalOp<"ceil",
+ "Ceil rounding of floating point value",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_FloorOp : WasmSSA_UnaryNumericalOp<"floor",
+ "Floor rounding of floating point value",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_NegOp : WasmSSA_UnaryNumericalOp<"neg",
+ "Floating point negation",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_SqrtOp : WasmSSA_UnaryNumericalOp<"sqrt",
+ "Floating point square root",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_TruncOp : WasmSSA_UnaryNumericalOp<"trunc",
+ "Trunc of floating point value",
+ [WasmSSA_FPType]>{}
+
+def WasmSSA_CtzOp : WasmSSA_UnaryNumericalOp<"ctz",
+ "Count trailing zeroes of an integer",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_ClzOp : WasmSSA_UnaryNumericalOp<"clz",
+ "Count leading zeroes of an integer",
+ [WasmSSA_IntegerType]>{}
+
+def WasmSSA_EqzOp : WasmSSA_Op<"eqz", []> {
+ let summary = "Check if the given value is equal to zero";
+ let arguments = (ins WasmSSA_IntegerType: $input);
+ let results = (outs I32: $result);
+ let assemblyFormat = "$input`:` type($input) `->` type($result) attr-dict";
+}
+
+
+def WasmSSA_PopCntOp : WasmSSA_UnaryNumericalOp<"popcnt",
+ "Population count of an integer.",
+ [WasmSSA_IntegerType]>{}
+
+
+#endif // WEBASSEMBLYSSA_OPS
diff --git a/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.td b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.td
new file mode 100644
index 0000000000000..1ab2196d70b34
--- /dev/null
+++ b/mlir/include/mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.td
@@ -0,0 +1,86 @@
+//===- WebAssemblySSATypes.td - WebAssemblySSA types def ----*- tablegen -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef WEBASSEMBLYSSA_TYPES
+#define WEBASSEMBLYSSA_TYPES
+
+include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSABase.td"
+
+include "mlir/IR/AttrTypeBase.td"
+include "mlir/IR/BuiltinTypes.td"
+include "mlir/IR/CommonAttrConstraints.td"
+include "mlir/IR/CommonTypeConstraints.td"
+
+def WasmSSA_IntegerType : AnyTypeOf<[I32, I64]>;
+def WasmSSA_FPType: AnyTypeOf<[F32, F64]>;
+def WasmSSA_NumericType : AnyTypeOf<[WasmSSA_IntegerType, WasmSSA_FPType]>{
+ let cppFunctionName = "isWasmNumericType";
+}
+def WasmSSA_VecType : AnyTypeOf<[I128]>;
+
+class WasmSSA_Type<string name, string typeMnemonic, list<Trait> traits = []>
+ : TypeDef<WasmSSA_Dialect, name, traits> {
+ let mnemonic = typeMnemonic;
+}
+
+def WasmSSA_FuncRefType : WasmSSA_Type<"FuncRef", "funcref"> {
+ let summary = "Opaque type for function reference";
+ let assemblyFormat = "";
+}
+
+def WasmSSA_ExternRefType : WasmSSA_Type<"ExternRef", "externref"> {
+ let summary = "Opaque type for external reference";
+}
+
+def WasmSSA_RefType : AnyTypeOf<[WasmSSA_FuncRefType, WasmSSA_ExternRefType]> {
+ let cppFunctionName = "isWasmRefType";
+}
+
+def WasmSSA_ValType : AnyTypeOf<[WasmSSA_NumericType, WasmSSA_VecType, WasmSSA_RefType]> {
+ let cppFunctionName = "isWasmValueType";
+}
+
+def WasmSSA_ResultType : TupleOf<[WasmSSA_ValType]>;
+
+def WasmSSA_FuncType : TypeAlias<FunctionType>;
+
+def WasmSSA_LimitType : WasmSSA_Type<"Limit", "limit"> {
+ let summary = "Wasm limit type";
+ let parameters = (ins "uint32_t":$min,
+ "std::optional<uint32_t>":$max);
+ let hasCustomAssemblyFormat = 1;
+}
+
+def WasmSSA_LocalRef : WasmSSA_Type<"LocalRef", "local"> {
+ let summary = "Type of a local variable";
+ let parameters = (ins WasmSSA_ValType: $elementType);
+ let assemblyFormat = "`ref` `to` $elementType";
+ let builders = [TypeBuilderWithInferredContext<(ins "Type":$typeParam), [{
+ return get(typeParam.getContext(), typeParam);
+ }]>,];
+}
+
+def WasmSSA_TableType : WasmSSA_Type<"Table", "tabletype"> {
+ let summary = "Wasm table type";
+ let parameters = (ins WasmSSA_RefType:$reference,
+ WasmSSA_LimitType:$limit);
+ let assemblyFormat = "$reference $limit";
+}
+
+def WasmSSA_FuncTypeAttr : TypeAttrOf<WasmSSA_FuncType>;
+def WasmSSA_LimitTypeAttr : TypeAttrOf<WasmSSA_LimitType>;
+def WasmSSA_TableTypeAttr : TypeAttrOf<WasmSSA_TableType>;
+def WasmSSA_ValTypeAttr : TypeAttrOf<WasmSSA_ValType>;
+
+def WasmSSA_IntegerAttr : AnyAttrOf<[I32Attr, I64Attr]>;
+def WasmSSA_FPAttr : AnyAttrOf<[F32Attr, F64Attr]>;
+def WasmSSA_NumericAttr : AnyAttrOf<[WasmSSA_IntegerAttr, WasmSSA_FPAttr]>;
+def WasmSSA_VecAttr : TypedSignlessIntegerAttrBase<
+ I128, "::llvm::APInt", "128 bits signless integer attribute">;
+
+#endif // WEBASSEMBLYSSA_TYPES
diff --git a/mlir/include/mlir/InitAllDialects.h b/mlir/include/mlir/InitAllDialects.h
index c6fcf1a0d510b..5f3676a25d561 100644
--- a/mlir/include/mlir/InitAllDialects.h
+++ b/mlir/include/mlir/InitAllDialects.h
@@ -96,6 +96,7 @@
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Vector/Transforms/SubsetOpInterfaceImpl.h"
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h"
#include "mlir/Dialect/X86Vector/X86VectorDialect.h"
#include "mlir/Dialect/XeGPU/IR/XeGPU.h"
#include "mlir/IR/Dialect.h"
@@ -152,6 +153,7 @@ inline void registerAllDialects(DialectRegistry ®istry) {
transform::TransformDialect,
ub::UBDialect,
vector::VectorDialect,
+ wasmssa::WasmSSADialect,
x86vector::X86VectorDialect,
xegpu::XeGPUDialect,
xevm::XeVMDialect>();
diff --git a/mlir/lib/Dialect/CMakeLists.txt b/mlir/lib/Dialect/CMakeLists.txt
index 3cc52ebc0a8d9..b0403783d0752 100644
--- a/mlir/lib/Dialect/CMakeLists.txt
+++ b/mlir/lib/Dialect/CMakeLists.txt
@@ -41,6 +41,7 @@ add_subdirectory(Transform)
add_subdirectory(UB)
add_subdirectory(Utils)
add_subdirectory(Vector)
+add_subdirectory(WebAssemblySSA)
add_subdirectory(X86Vector)
add_subdirectory(XeGPU)
diff --git a/mlir/lib/Dialect/WebAssemblySSA/CMakeLists.txt b/mlir/lib/Dialect/WebAssemblySSA/CMakeLists.txt
new file mode 100644
index 0000000000000..f33061b2d87cf
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(IR)
diff --git a/mlir/lib/Dialect/WebAssemblySSA/IR/CMakeLists.txt b/mlir/lib/Dialect/WebAssemblySSA/IR/CMakeLists.txt
new file mode 100644
index 0000000000000..b106b8b7c2264
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/IR/CMakeLists.txt
@@ -0,0 +1,24 @@
+add_mlir_dialect_library(MLIRWasmSSADialect
+ WebAssemblySSAOps.cpp
+ WebAssemblySSADialect.cpp
+ WebAssemblySSAInterfaces.cpp
+ WebAssemblySSATypes.cpp
+
+ ADDITIONAL_HEADER_DIRS
+ ${MLIR_MAIN_INCLUDE_DIR}/mlir/Dialect/WebAssemblySSA
+
+ DEPENDS
+ MLIRWebAssemblySSAOpsIncGen
+ MLIRWebAssemblySSAInterfacesIncGen
+
+ LINK_LIBS PUBLIC
+ MLIRCastInterfaces
+ MLIRDataLayoutInterfaces
+ MLIRDialect
+ MLIRInferTypeOpInterface
+ MLIRIR
+ MLIRSupport
+
+ PRIVATE
+ MLIRFunctionInterfaces
+ )
diff --git a/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSADialect.cpp b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSADialect.cpp
new file mode 100644
index 0000000000000..a37e77256d970
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSADialect.cpp
@@ -0,0 +1,38 @@
+//===- WebAssemblyDialect.cpp - MLIR WebAssembly dialect implementation ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h"
+
+#include "llvm/ADT/TypeSwitch.h"
+
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/DialectImplementation.h"
+#include "mlir/Support/LLVM.h"
+
+using namespace mlir;
+using namespace mlir::wasmssa;
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOpsDialect.cpp.inc"
+
+//===----------------------------------------------------------------------===//
+// TableGen'd types definitions
+//===----------------------------------------------------------------------===//
+
+#define GET_TYPEDEF_CLASSES
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOpsTypes.cpp.inc"
+
+void wasmssa::WasmSSADialect::initialize() {
+ addOperations<
+#define GET_OP_LIST
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp.inc"
+ >();
+ addTypes<
+#define GET_TYPEDEF_LIST
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOpsTypes.cpp.inc"
+ >();
+}
diff --git a/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.cpp b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.cpp
new file mode 100644
index 0000000000000..0b43f2f671062
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.cpp
@@ -0,0 +1,61 @@
+//===- WebAssemblySSAInterfaces.cpp - WebAssemblySSA Interfaces -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines op interfaces for the WebAssemblySSA dialect in MLIR.
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.h"
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h"
+#include "mlir/IR/Operation.h"
+#include "mlir/IR/Visitors.h"
+#include "mlir/Support/LLVM.h"
+
+namespace mlir::wasmssa {
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAInterfaces.cpp.inc"
+
+namespace detail {
+LogicalResult verifyWasmSSALabelBranchingInterface(Operation *op) {
+ auto branchInterface = dyn_cast<WasmSSALabelBranchingInterface>(op);
+ auto res = WasmSSALabelBranchingInterface::getTargetOpFromBlock(
+ op->getBlock(), branchInterface.getExitLevel());
+ return success(succeeded(res));
+}
+
+LogicalResult verifyConstantExpressionInterface(Operation *op) {
+ Region &initializerRegion = op->getRegion(0);
+ auto resultState =
+ initializerRegion.walk([&](Operation *currentOp) -> WalkResult {
+ if (isa<ReturnOp>(currentOp))
+ return WalkResult::advance();
+ if (auto interfaceOp =
+ dyn_cast<WasmSSAConstantExprCheckInterface>(currentOp)) {
+ if (interfaceOp.isValidInConstantExpr().succeeded())
+ return WalkResult::advance();
+ }
+ op->emitError("Expected a constant initializer for this operator, got ")
+ << currentOp;
+ return WalkResult::interrupt();
+ });
+ return success(!resultState.wasInterrupted());
+}
+} // namespace detail
+
+llvm::FailureOr<WasmSSALabelLevelInterface>
+WasmSSALabelBranchingInterface::getTargetOpFromBlock(::mlir::Block *block,
+ uint32_t breakLevel) {
+ WasmSSALabelLevelInterface res{};
+ for (size_t curLevel{0}; curLevel <= breakLevel; curLevel++) {
+ res = dyn_cast_or_null<WasmSSALabelLevelInterface>(block->getParentOp());
+ if (!res)
+ return failure();
+ block = res->getBlock();
+ }
+ return res;
+}
+} // namespace mlir::wasmssa
diff --git a/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp
new file mode 100644
index 0000000000000..00bb83caa9ee6
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp
@@ -0,0 +1,510 @@
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h"
+
+#include "mlir/IR/Attributes.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/Dialect.h"
+#include "mlir/IR/Region.h"
+#include "mlir/IR/SymbolTable.h"
+#include "mlir/Interfaces/FunctionImplementation.h"
+#include "llvm/Support/Casting.h"
+
+//===----------------------------------------------------------------------===//
+// TableGen'd op method definitions
+//===----------------------------------------------------------------------===//
+
+#define GET_OP_CLASSES
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSAOps.cpp.inc"
+
+#include "mlir/IR/OpImplementation.h"
+#include "mlir/IR/Types.h"
+#include "llvm/Support/LogicalResult.h"
+
+using namespace mlir;
+using namespace mlir::wasmssa;
+
+namespace {
+inline LogicalResult
+inferTeeGetResType(ValueRange operands,
+ ::llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
+ if (operands.empty())
+ return failure();
+ auto opType = llvm::dyn_cast<LocalRefType>(operands.front().getType());
+ if (!opType)
+ return failure();
+ inferredReturnTypes.push_back(opType.getElementType());
+ return success();
+}
+
+ParseResult parseImportOp(OpAsmParser &parser, OperationState &result) {
+ std::string importName;
+ auto *ctx = parser.getContext();
+ ParseResult res = parser.parseString(&importName);
+ result.addAttribute("importName", StringAttr::get(ctx, importName));
+
+ std::string fromStr;
+ res = parser.parseKeywordOrString(&fromStr);
+ if (failed(res) || fromStr != "from")
+ return failure();
+
+ std::string moduleName;
+ res = parser.parseString(&moduleName);
+ if (failed(res))
+ return failure();
+ result.addAttribute("moduleName", StringAttr::get(ctx, moduleName));
+
+ std::string asStr;
+ res = parser.parseKeywordOrString(&asStr);
+ if (failed(res) || asStr != "as")
+ return failure();
+
+ StringAttr symbolName;
+ res = parser.parseSymbolName(symbolName, SymbolTable::getSymbolAttrName(),
+ result.attributes);
+ return res;
+}
+} // namespace
+
+//===----------------------------------------------------------------------===//
+// BlockOp
+//===----------------------------------------------------------------------===//
+
+Block *BlockOp::getLabelTarget() { return getTarget(); }
+
+//===----------------------------------------------------------------------===//
+// BlockReturnOp
+//===----------------------------------------------------------------------===//
+
+std::size_t BlockReturnOp::getExitLevel() { return 0; }
+
+Block *BlockReturnOp::getTarget() {
+ return cast<WasmSSALabelBranchingInterface>(getOperation())
+ .getTargetOp()
+ .getOperation()
+ ->getSuccessor(0);
+}
+
+//===----------------------------------------------------------------------===//
+// ExtendLowBitsSOp
+//===----------------------------------------------------------------------===//
+
+ParseResult ExtendLowBitsSOp::parse(::mlir::OpAsmParser &parser,
+ ::mlir::OperationState &result) {
+ OpAsmParser::UnresolvedOperand operand;
+ uint64_t nBits;
+ auto parseRes = parser.parseInteger(nBits);
+ parseRes = parser.parseKeyword("low");
+ parseRes = parser.parseKeyword("bits");
+ parseRes = parser.parseKeyword("from");
+ parseRes = parser.parseOperand(operand);
+ parseRes = parser.parseColon();
+ Type inType;
+ parseRes = parser.parseType(inType);
+ if (!inType.isInteger())
+ return failure();
+ llvm::SmallVector<Value, 1> opVal;
+ parseRes = parser.resolveOperand(operand, inType, opVal);
+ if (parseRes.failed())
+ return failure();
+ result.addOperands(opVal);
+ result.addAttribute(
+ ExtendLowBitsSOp::getBitsToTakeAttrName(OperationName{
+ ExtendLowBitsSOp::getOperationName(), parser.getContext()}),
+ parser.getBuilder().getI64IntegerAttr(nBits));
+ result.addTypes(inType);
+ return success();
+}
+
+void ExtendLowBitsSOp::print(OpAsmPrinter &p) {
+ p << " " << getBitsToTake().getUInt() << " low bits from ";
+ p.printOperand(getInput());
+ p << ": " << getInput().getType();
+}
+
+LogicalResult ExtendLowBitsSOp::verify() {
+ auto bitsToTake = getBitsToTake().getValue().getLimitedValue();
+ if (bitsToTake != 32 && bitsToTake != 16 && bitsToTake != 8)
+ return emitError("Extend op can only take 8, 16 or 32 bits. Got ")
+ << bitsToTake;
+
+ if (bitsToTake >= getInput().getType().getIntOrFloatBitWidth())
+ return emitError("Trying to extend the ")
+ << bitsToTake << " low bits from a " << getInput().getType()
+ << " value";
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// FuncOp
+//===----------------------------------------------------------------------===//
+
+Block *FuncOp::addEntryBlock() {
+ if (!getBody().empty()) {
+ emitError("Adding entry block to a FuncOp which already has one.");
+ return &getBody().front();
+ }
+ Block &block = getBody().emplaceBlock();
+ for (auto argType : getFunctionType().getInputs())
+ block.addArgument(LocalRefType::get(argType), getLoc());
+ return █
+}
+
+void FuncOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, llvm::StringRef symbol,
+ FunctionType funcType) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("functionType", TypeAttr::get(funcType));
+ odsState.addRegion();
+}
+
+ParseResult FuncOp::parse(::mlir::OpAsmParser &parser,
+ ::mlir::OperationState &result) {
+ auto buildFuncType = [&parser](Builder &builder, ArrayRef<Type> argTypes,
+ ArrayRef<Type> results,
+ function_interface_impl::VariadicFlag,
+ std::string &) {
+ llvm::SmallVector<Type> argTypesWithoutLocal{};
+ argTypesWithoutLocal.reserve(argTypes.size());
+ llvm::for_each(argTypes, [&parser, &argTypesWithoutLocal](Type argType) {
+ auto refType = dyn_cast<LocalRefType>(argType);
+ auto loc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
+ if (!refType) {
+ mlir::emitError(loc, "Invalid type for wasm.func argument. Expecting "
+ "!wasm<local T>, got ")
+ << argType << ".";
+ return;
+ }
+ argTypesWithoutLocal.push_back(refType.getElementType());
+ });
+
+ return builder.getFunctionType(argTypesWithoutLocal, results);
+ };
+
+ return function_interface_impl::parseFunctionOp(
+ parser, result, /*allowVariadic=*/false,
+ getFunctionTypeAttrName(result.name), buildFuncType,
+ getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
+}
+
+LogicalResult FuncOp::verifyBody() {
+ if (getBody().empty())
+ return success();
+ Block &entry = getBody().front();
+ if (entry.getNumArguments() != getFunctionType().getNumInputs())
+ return emitError("Entry block should have same number of arguments as "
+ "function type. Function type has ")
+ << getFunctionType().getNumInputs() << ", entry block has "
+ << entry.getNumArguments() << ".";
+
+ for (auto [argNo, funcSignatureType, blockType] : llvm::enumerate(
+ getFunctionType().getInputs(), entry.getArgumentTypes())) {
+ auto blockLocalRefType = dyn_cast<LocalRefType>(blockType);
+ if (!blockLocalRefType)
+ return emitError("Entry block argument type should be LocalRefType, got ")
+ << blockType << " for block argument " << argNo << ".";
+ if (blockLocalRefType.getElementType() != funcSignatureType)
+ return emitError("Func argument type #")
+ << argNo << "(" << funcSignatureType
+ << ") doesn't match entry block referenced type ("
+ << blockLocalRefType.getElementType() << ").";
+ }
+ return success();
+}
+
+void FuncOp::print(OpAsmPrinter &p) {
+ function_interface_impl::printFunctionOp(
+ p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
+ getArgAttrsAttrName(), getResAttrsAttrName());
+}
+
+//===----------------------------------------------------------------------===//
+// FuncImportOp
+//===----------------------------------------------------------------------===//
+
+void FuncImportOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, StringRef symbol,
+ StringRef moduleName, StringRef importName,
+ FunctionType type) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("moduleName", odsBuilder.getStringAttr(moduleName));
+ odsState.addAttribute("importName", odsBuilder.getStringAttr(importName));
+ odsState.addAttribute("type", TypeAttr::get(type));
+}
+
+//===----------------------------------------------------------------------===//
+// GlobalOp
+//===----------------------------------------------------------------------===//
+
+void GlobalOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, llvm::StringRef symbol,
+ Type type, bool isMutable) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("type", TypeAttr::get(type));
+ if (isMutable)
+ odsState.addAttribute("isMutable", odsBuilder.getUnitAttr());
+ odsState.addRegion();
+}
+
+// Custom formats
+ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) {
+ StringAttr symbolName;
+ Type globalType;
+ auto *ctx = parser.getContext();
+ auto res = parser.parseSymbolName(
+ symbolName, SymbolTable::getSymbolAttrName(), result.attributes);
+
+ res = parser.parseType(globalType);
+ result.addAttribute(getTypeAttrName(result.name), TypeAttr::get(globalType));
+ std::string mutableString;
+ res = parser.parseOptionalKeywordOrString(&mutableString);
+ if (res.succeeded() && mutableString == "mutable")
+ result.addAttribute("isMutable", UnitAttr::get(ctx));
+ std::string visibilityString;
+ res = parser.parseOptionalKeywordOrString(&visibilityString);
+ if (res.succeeded())
+ result.addAttribute("sym_visibility",
+ StringAttr::get(ctx, visibilityString));
+ res = parser.parseColon();
+ Region *globalInitRegion = result.addRegion();
+ res = parser.parseRegion(*globalInitRegion);
+ return res;
+}
+
+void GlobalOp::print(OpAsmPrinter &printer) {
+ printer << " @" << getSymName().str() << " " << getType();
+ if (getIsMutable())
+ printer << " mutable";
+ if (auto vis = getSymVisibility())
+ printer << " " << *vis;
+ printer << " :";
+ Region &body = getRegion();
+ if (!body.empty()) {
+ printer << ' ';
+ printer.printRegion(body, /*printEntryBlockArgs=*/false,
+ /*printBlockTerminators=*/true);
+ }
+}
+
+//===----------------------------------------------------------------------===//
+// GlobalGetOp
+//===----------------------------------------------------------------------===//
+
+// Custom interface overrides
+LogicalResult GlobalGetOp::verifyConstantExprValidity() {
+ StringRef referencedSymbol = getGlobal();
+ Operation *symTableOp =
+ getOperation()->getParentWithTrait<OpTrait::SymbolTable>();
+ Operation *definitionOp =
+ SymbolTable::lookupSymbolIn(symTableOp, referencedSymbol);
+ if (!definitionOp)
+ return failure();
+ auto definitionImport = llvm::dyn_cast<GlobalImportOp>(definitionOp);
+ if (!definitionImport || definitionImport.getIsMutable()) {
+ return emitError("global.get op is considered constant if it's referring "
+ "to a import.global symbol marked non-mutable.");
+ }
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// GlobalImportOp
+//===----------------------------------------------------------------------===//
+
+void GlobalImportOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, StringRef symbol,
+ StringRef moduleName, StringRef importName,
+ Type type, bool isMutable) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("moduleName", odsBuilder.getStringAttr(moduleName));
+ odsState.addAttribute("importName", odsBuilder.getStringAttr(importName));
+ odsState.addAttribute("type", TypeAttr::get(type));
+ if (isMutable)
+ odsState.addAttribute("isMutable", odsBuilder.getUnitAttr());
+}
+
+ParseResult GlobalImportOp::parse(OpAsmParser &parser, OperationState &result) {
+ auto *ctx = parser.getContext();
+ ParseResult res = parseImportOp(parser, result);
+ if (res.failed())
+ return failure();
+ std::string mutableOrSymVisString;
+ res = parser.parseOptionalKeywordOrString(&mutableOrSymVisString);
+ if (res.succeeded() && mutableOrSymVisString == "mutable") {
+ result.addAttribute("isMutable", UnitAttr::get(ctx));
+ res = parser.parseOptionalKeywordOrString(&mutableOrSymVisString);
+ }
+
+ if (res.succeeded())
+ result.addAttribute("sym_visibility",
+ StringAttr::get(ctx, mutableOrSymVisString));
+ res = parser.parseColon();
+
+ Type importedType;
+ res = parser.parseType(importedType);
+ if (res.succeeded())
+ result.addAttribute(getTypeAttrName(result.name),
+ TypeAttr::get(importedType));
+ return res;
+}
+
+void GlobalImportOp::print(OpAsmPrinter &printer) {
+ printer << " \"" << getImportName() << "\" from \"" << getModuleName()
+ << "\" as @" << getSymName();
+ if (getIsMutable())
+ printer << " mutable";
+ if (auto vis = getSymVisibility())
+ printer << " " << *vis;
+ printer << " : " << getType();
+}
+
+//===----------------------------------------------------------------------===//
+// IfOp
+//===----------------------------------------------------------------------===//
+
+Block *IfOp::getLabelTarget() { return getTarget(); }
+
+//===----------------------------------------------------------------------===//
+// LocalOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult LocalOp::inferReturnTypes(
+ MLIRContext *context, ::std::optional<Location> location,
+ ValueRange operands, DictionaryAttr attributes, OpaqueProperties properties,
+ RegionRange regions, ::llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
+ LocalOp::GenericAdaptor<ValueRange> adaptor{operands, attributes, properties,
+ regions};
+ auto type = adaptor.getTypeAttr();
+ if (!type)
+ return failure();
+ auto resType = LocalRefType::get(type.getContext(), type.getValue());
+ inferredReturnTypes.push_back(resType);
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// LocalGetOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult LocalGetOp::inferReturnTypes(
+ MLIRContext *context, ::std::optional<Location> location,
+ ValueRange operands, DictionaryAttr attributes, OpaqueProperties properties,
+ RegionRange regions, ::llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
+ return inferTeeGetResType(operands, inferredReturnTypes);
+}
+
+LogicalResult LocalGetOp::verify() {
+ return success(getLocalVar().getType().getElementType() ==
+ getResult().getType());
+}
+
+//===----------------------------------------------------------------------===//
+// LocalSetOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult LocalSetOp::verify() {
+ return success(getLocalVar().getType().getElementType() ==
+ getValue().getType());
+}
+
+//===----------------------------------------------------------------------===//
+// LocalTeeOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult LocalTeeOp::inferReturnTypes(
+ MLIRContext *context, ::std::optional<Location> location,
+ ValueRange operands, DictionaryAttr attributes, OpaqueProperties properties,
+ RegionRange regions, ::llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
+ return inferTeeGetResType(operands, inferredReturnTypes);
+}
+
+LogicalResult LocalTeeOp::verify() {
+ return success(getLocalVar().getType().getElementType() ==
+ getValue().getType() &&
+ getValue().getType() == getResult().getType());
+}
+
+//===----------------------------------------------------------------------===//
+// LoopOp
+//===----------------------------------------------------------------------===//
+
+Block *LoopOp::getLabelTarget() { return &getBody().front(); }
+
+//===----------------------------------------------------------------------===//
+// MemOp
+//===----------------------------------------------------------------------===//
+
+void MemOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, llvm::StringRef symbol,
+ LimitType limit) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("limits", TypeAttr::get(limit));
+}
+
+//===----------------------------------------------------------------------===//
+// MemImportOp
+//===----------------------------------------------------------------------===//
+
+void MemImportOp::build(mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState,
+ llvm::StringRef symbol, llvm::StringRef moduleName,
+ llvm::StringRef importName, LimitType limits) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("moduleName", odsBuilder.getStringAttr(moduleName));
+ odsState.addAttribute("importName", odsBuilder.getStringAttr(importName));
+ odsState.addAttribute("limits", TypeAttr::get(limits));
+}
+
+//===----------------------------------------------------------------------===//
+// ReinterpretOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult ReinterpretOp::verify() {
+ auto inT = getInput().getType();
+ auto resT = getResult().getType();
+ if (inT == resT)
+ return emitError("reinterpret input and output type should be distinct.");
+ if (inT.getIntOrFloatBitWidth() != resT.getIntOrFloatBitWidth())
+ return emitError() << "input type (" << inT << ") and output type (" << resT
+ << ") have incompatible bit widths.";
+ return success();
+}
+
+//===----------------------------------------------------------------------===//
+// ReturnOp
+//===----------------------------------------------------------------------===//
+
+void ReturnOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState) {}
+
+//===----------------------------------------------------------------------===//
+// TableOp
+//===----------------------------------------------------------------------===//
+
+void TableOp::build(::mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState, llvm::StringRef symbol,
+ TableType type) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("type", TypeAttr::get(type));
+}
+
+//===----------------------------------------------------------------------===//
+// TableImportOp
+//===----------------------------------------------------------------------===//
+
+void TableImportOp::build(mlir::OpBuilder &odsBuilder,
+ ::mlir::OperationState &odsState,
+ llvm::StringRef symbol, llvm::StringRef moduleName,
+ llvm::StringRef importName, TableType type) {
+ odsState.addAttribute("sym_name", odsBuilder.getStringAttr(symbol));
+ odsState.addAttribute("sym_visibility", odsBuilder.getStringAttr("nested"));
+ odsState.addAttribute("moduleName", odsBuilder.getStringAttr(moduleName));
+ odsState.addAttribute("importName", odsBuilder.getStringAttr(importName));
+ odsState.addAttribute("type", TypeAttr::get(type));
+}
diff --git a/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.cpp b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.cpp
new file mode 100644
index 0000000000000..27b3af5af0a6f
--- /dev/null
+++ b/mlir/lib/Dialect/WebAssemblySSA/IR/WebAssemblySSATypes.cpp
@@ -0,0 +1,36 @@
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSA.h"
+#include "mlir/IR/OpImplementation.h"
+#include "mlir/IR/Types.h"
+#include "llvm/Support/LogicalResult.h"
+
+#include <optional>
+
+namespace mlir::wasmssa {
+#include "mlir/Dialect/WebAssemblySSA/IR/WebAssemblySSATypeConstraints.cpp.inc"
+} // namespace mlir::wasmssa
+
+using namespace mlir;
+using namespace mlir::wasmssa;
+
+Type LimitType::parse(::mlir::AsmParser &parser) {
+ auto res = parser.parseLSquare();
+ uint32_t minLimit{0};
+ std::optional<uint32_t> maxLimit{std::nullopt};
+ res = parser.parseInteger(minLimit);
+ res = parser.parseColon();
+ uint32_t maxValue{0};
+ auto maxParseRes = parser.parseOptionalInteger(maxValue);
+ if (maxParseRes.has_value() && (*maxParseRes).succeeded())
+ maxLimit = maxValue;
+
+ res = parser.parseRSquare();
+ return LimitType::get(parser.getContext(), minLimit, maxLimit);
+}
+
+void LimitType::print(AsmPrinter &printer) const {
+ printer << '[' << getMin() << ':';
+ auto maxLim = getMax();
+ if (maxLim)
+ printer << *maxLim;
+ printer << ']';
+}
diff --git a/mlir/test/Dialect/WebAssemblySSA/custom_parser/global.mlir b/mlir/test/Dialect/WebAssemblySSA/custom_parser/global.mlir
new file mode 100644
index 0000000000000..b9b342052ff1b
--- /dev/null
+++ b/mlir/test/Dialect/WebAssemblySSA/custom_parser/global.mlir
@@ -0,0 +1,44 @@
+// RUN: mlir-opt %s | FileCheck %s
+
+module {
+ wasmssa.import_global "from_js" from "env" as @global_0 nested : i32
+
+ wasmssa.global @global_1 i32 : {
+ %0 = wasmssa.const 10 : i32
+ wasmssa.return %0 : i32
+ }
+ wasmssa.global @global_2 i32 mutable : {
+ %0 = wasmssa.const 17 : i32
+ wasmssa.return %0 : i32
+ }
+ wasmssa.global @global_3 i32 mutable : {
+ %0 = wasmssa.const 10 : i32
+ wasmssa.return %0 : i32
+ }
+ wasmssa.global @global_4 i32 : {
+ %0 = wasmssa.global_get @global_0 : i32
+ wasmssa.return %0 : i32
+ }
+}
+
+// CHECK-LABEL: wasmssa.import_global "from_js" from "env" as @global_0 nested : i32
+
+// CHECK-LABEL: wasmssa.global @global_1 i32 : {
+// CHECK: %[[VAL_0:.*]] = wasmssa.const 10 : i32
+// CHECK: wasmssa.return %[[VAL_0]] : i32
+// CHECK: }
+
+// CHECK-LABEL: wasmssa.global @global_2 i32 mutable : {
+// CHECK: %[[VAL_0:.*]] = wasmssa.const 17 : i32
+// CHECK: wasmssa.return %[[VAL_0]] : i32
+// CHECK: }
+
+// CHECK-LABEL: wasmssa.global @global_3 i32 mutable : {
+// CHECK: %[[VAL_0:.*]] = wasmssa.const 10 : i32
+// CHECK: wasmssa.return %[[VAL_0]] : i32
+// CHECK: }
+
+// CHECK-LABEL: wasmssa.global @global_4 i32 : {
+// CHECK: %[[VAL_0:.*]] = wasmssa.global_get @global_0 : i32
+// CHECK: wasmssa.return %[[VAL_0]] : i32
+// CHECK: }
diff --git a/mlir/test/Dialect/WebAssemblySSA/custom_parser/global_illegal.mlir b/mlir/test/Dialect/WebAssemblySSA/custom_parser/global_illegal.mlir
new file mode 100644
index 0000000000000..c824593e8cdf5
--- /dev/null
+++ b/mlir/test/Dialect/WebAssemblySSA/custom_parser/global_illegal.mlir
@@ -0,0 +1,23 @@
+// RUN: mlir-opt %s -verify-diagnostics --split-input-file
+
+module {
+ // expected-error at +1 {{Expected a constant initializer for this operator}}
+ wasmssa.global @illegal i32 mutable : {
+ %0 = wasmssa.const 17: i32
+ %1 = wasmssa.const 35: i32
+ %2 = wasmssa.add %0 %1 : i32
+ wasmssa.return %2 : i32
+ }
+}
+
+// -----
+
+module {
+ wasmssa.import_global "glob" from "my_module" as @global_0 mutable nested : i32
+ // expected-error at +1 {{Expected a constant initializer for this operator}}
+ wasmssa.global @global_1 i32 : {
+ // expected-error at +1 {{global.get op is considered constant if it's referring to a import.global symbol marked non-mutable}}
+ %0 = wasmssa.global_get @global_0 : i32
+ wasmssa.return %0 : i32
+ }
+}
diff --git a/mlir/test/Dialect/WebAssemblySSA/custom_parser/import.mlir b/mlir/test/Dialect/WebAssemblySSA/custom_parser/import.mlir
new file mode 100644
index 0000000000000..3cc05486c4a4d
--- /dev/null
+++ b/mlir/test/Dialect/WebAssemblySSA/custom_parser/import.mlir
@@ -0,0 +1,17 @@
+// RUN: mlir-opt %s | FileCheck %s
+
+module {
+ wasmssa.import_func "foo" from "my_module" as @func_0 {sym_visibility = "nested", type = (i32) -> ()}
+ wasmssa.import_func "bar" from "my_module" as @func_1 {sym_visibility = "nested", type = (i32) -> ()}
+ wasmssa.import_table "table" from "my_module" as @table_0 {sym_visibility = "nested", type = !wasmssa<tabletype !wasmssa.funcref [2:]>}
+ wasmssa.import_mem "mem" from "my_module" as @mem_0 {limits = !wasmssa<limit[2:]>, sym_visibility = "nested"}
+ wasmssa.import_global "glob" from "my_module" as @global_0 nested : i32
+ wasmssa.import_global "glob_mut" from "my_other_module" as @global_1 mutable nested : i32
+}
+
+// CHECK-LABEL: wasmssa.import_func "foo" from "my_module" as @func_0 {sym_visibility = "nested", type = (i32) -> ()}
+// CHECK: wasmssa.import_func "bar" from "my_module" as @func_1 {sym_visibility = "nested", type = (i32) -> ()}
+// CHECK: wasmssa.import_table "table" from "my_module" as @table_0 {sym_visibility = "nested", type = !wasmssa<tabletype !wasmssa.funcref [2:]>}
+// CHECK: wasmssa.import_mem "mem" from "my_module" as @mem_0 {limits = !wasmssa<limit[2:]>, sym_visibility = "nested"}
+// CHECK: wasmssa.import_global "glob" from "my_module" as @global_0 nested : i32
+// CHECK: wasmssa.import_global "glob_mut" from "my_other_module" as @global_1 mutable nested : i32
diff --git a/mlir/test/Dialect/WebAssemblySSA/custom_parser/local.mlir b/mlir/test/Dialect/WebAssemblySSA/custom_parser/local.mlir
new file mode 100644
index 0000000000000..3f6423fa2a1f5
--- /dev/null
+++ b/mlir/test/Dialect/WebAssemblySSA/custom_parser/local.mlir
@@ -0,0 +1,45 @@
+// RUN: mlir-opt %s | FileCheck %s
+
+module {
+ wasmssa.func nested @func_0() -> f32 {
+ %0 = wasmssa.local of type f32
+ %1 = wasmssa.local of type f32
+ %2 = wasmssa.const 8.000000e+00 : f32
+ %3 = wasmssa.const 1.200000e+01 : f32
+ %4 = wasmssa.add %2 %3 : f32
+ wasmssa.return %4 : f32
+ }
+ wasmssa.func nested @func_1() -> i32 {
+ %0 = wasmssa.local of type i32
+ %1 = wasmssa.local of type i32
+ %2 = wasmssa.const 8 : i32
+ %3 = wasmssa.const 12 : i32
+ %4 = wasmssa.add %2 %3 : i32
+ wasmssa.return %4 : i32
+ }
+ wasmssa.func nested @func_2(%arg0: !wasmssa<local ref to i32>) -> i32 {
+ %0 = wasmssa.const 3 : i32
+ wasmssa.return %0 : i32
+ }
+}
+
+// CHECK-LABEL: wasmssa.func nested @func_0() -> f32 {
+// CHECK: %[[VAL_0:.*]] = wasmssa.local of type f32
+// CHECK: %[[VAL_1:.*]] = wasmssa.local of type f32
+// CHECK: %[[VAL_2:.*]] = wasmssa.const 8.000000e+00 : f32
+// CHECK: %[[VAL_3:.*]] = wasmssa.const 1.200000e+01 : f32
+// CHECK: %[[VAL_4:.*]] = wasmssa.add %[[VAL_2]] %[[VAL_3]] : f32
+// CHECK: wasmssa.return %[[VAL_4]] : f32
+
+// CHECK-LABEL: wasmssa.func nested @func_1() -> i32 {
+// CHECK: %[[VAL_0:.*]] = wasmssa.local of type i32
+// CHECK: %[[VAL_1:.*]] = wasmssa.local of type i32
+// CHECK: %[[VAL_2:.*]] = wasmssa.const 8 : i32
+// CHECK: %[[VAL_3:.*]] = wasmssa.const 12 : i32
+// CHECK: %[[VAL_4:.*]] = wasmssa.add %[[VAL_2]] %[[VAL_3]] : i32
+// CHECK: wasmssa.return %[[VAL_4]] : i32
+
+// CHECK-LABEL: wasmssa.func nested @func_2(
+// CHECK-SAME: %[[ARG0:.*]]: !wasmssa<local ref to i32>) -> i32 {
+// CHECK: %[[VAL_0:.*]] = wasmssa.const 3 : i32
+// CHECK: wasmssa.return %[[VAL_0]] : i32
More information about the Mlir-commits
mailing list