Commit graph

2137 commits

Author SHA1 Message Date
Benjamin Kramer
dc6cd6a29a
[mlir] Honor IntrHasSideEffects on IntrNoMem LLVM intrinsics (#212760)
`[IntrNoMem, IntrHasSideEffects]` is a perfectly valid intrinsic trait
combination, and MLIR would CSE/DCE those without checking. This mirrors
how LLVM models this, see getEffectiveME in IntrinsicEmitter.cpp
2026-07-30 14:32:20 +02:00
Luke Hutton
f8c1d988e1
[mlir][tosa] Remove availability interfaces from profile conformance (#207809)
This commit removes the "QueryProfileInterface" and
"QueryExtensionInterface" as they are superfluous in most cases, with
TosaComplianceData.h.inc already providing much of the data we need.
Removing these also helps prevent mistakes as observed in:
https://github.com/llvm/llvm-project/pull/206687

This commit removes these interfaces and updates the profile conformance
to extract supported profile/extension information from
TosaComplianceData.h.inc instead.

One factor that isn't duplicated is operations that rely on extensions,
but do not declare any data type support. This is a small set of
operations, such as tosa.custom, tosa.cond_if, tosa.while_loop and
tosa.const_shape, and we can add them to the TosaComplianceData.h.inc
file as needed.
2026-07-30 11:47:06 +01:00
lorenzo chelini
9cdb4219e8
[MLIR] Validate directly parsed optional operand types (#212493)
Commit 6c51938067 ([MLIR] Guard optional operand resolution in
generated op parsers) guarded resolution of every optional operand to
avoid indexing an empty inferred type range. The guard also skipped
resolveOperands when an optional operand was absent but an independently
optional type directive was present. This accepted malformed assembly
and silently discarded the orphan type when printing the operation.

Keep the guard for inferred type resolutions, which may access an empty
optional type vector, but always resolve directly parsed type ranges so
resolveOperands validates operand/type cardinality. Add coverage for
both valid forms and a type-only negative reproducer.
2026-07-29 08:34:23 +02:00
Natanael Cintean
e432cb1296
[mlir]Add resultSegmentSizes/operandSegmentSizes to prop-dict. (#211222)
`setPropertiesFromParsedAttr` (generated by `OpFormatGen.cpp` for ops
using a custom `assemblyFormat`) rejects the trait-injected
`operandSegmentSizes` /. `resultSegmentSizes` properties when they
appear in a `prop-dict`, even though the printer emits them there for ops
whose format uses a bulk operand/result type directive
(`type(operands)`, `type(results)`, `functional-type(operands, results)`).

This breaks round-tripping: any op combining `AttrSizedOperandSegments`
/ `AttrSizedResultSegments` with such a bulk directive fails to re-parse
its own printed output, because printer-side elision of these keys
(introduced in #115930) is intentionally skipped in that case — the
sizes can't be reconstructed from individually-typed operand/result 
groups, so they must survive in the text, but the custom parser was never
taught to read them back.

`setPropertiesFromAttr` (used by the generic-form parser, bytecode, and
C++ construction) already special-cases these two keys, so this change
makes `setPropertiesFromParsedAttr` mirror that behavior: keys are
accepted from the dictionary attr when the corresponding trait is present,
and required exactly when the format can't reconstruct the sizes itself
(i.e. when `fmt.allOperands` / `fmt.allResultTypes` is true). Otherwise the
key remains optional, since `genParserVariadicSegmentResolution`
overwrites it with the sizes inferred from the parsed operand/result
groups.

The contents of the PR as well as description has been made using
github-copilot. However I've reviewed the contents and tested locally
the change.

Fixes #211220
2026-07-28 13:11:34 +00:00
Ryan Thomas Lynch
9428725fa0
[mlir-tblgen] Emit named result indices (#210542)
similar to https://github.com/llvm/llvm-project/pull/146839

useful for cases such as being able to programmatically update the
result segment sizes or clone an operation via `OperationState` while
editing just a few results, programmatically
2026-07-20 13:07:22 +02:00
Momchil Velikov
1651159f32
[MLIR] Install missing standalone helper tools (#205066)
Standalone MLIR installs CMake package files that can reference helper
executables needed by downstream builds. Most helper tools already have
install paths available through existing LLVM tool and utility install
options, but `mlir-src-sharder` does not pass an install destination to
`add_tablegen` and `mlir-irdl-to-cpp` does not define an install rule.

Install those two missing helpers.

Co-authored-by: Luca Fancellu <luca.fancellu@arm.com>
2026-07-13 09:33:38 +01:00
Alexis Engelke
3aec6a40bb
[Support] Remove virtual functions from formatv (#207516)
Currently, formatv erases types using a base class and calls the virtual
function format() to format the objects. To avoid these vtables,
refactor formatv to instead store function_refs to a functor (struct
with overloaded operator()). This saves ~5kiB in vtables.

Additionally, add a static assertion that a formatter is present instead
of relying on errors due to missing templates. This requires a little
change to MLIR's tgfmt to use a different name -- previously, the
substitution failure on ArrayRef<> would cause the variadic function to
be skipped, but a static assertion failure is not a substitution error.

Also, simplify the code in FormatVariadicDetails to use if constexpr
instead of template overloads with enable_if, making the code shorter
and easier to read.
2026-07-05 08:45:49 +02:00
Jacques Pienaar
238dbdce63
[mlirbc] Add IntegerSetAttr (#207482)
Serialize IntegerSetAttr using VarInt for numDims and numSymbols and
arrays for contraints and eqFlags. Add ArrayWithKnownSize` an Array
variant that omits the length prefix when the size is known from a
previously serialized member. This avoids encoding redundant array
lengths when, for example, two arrays are always the same size.

Assisted-By: Gemini
2026-07-04 05:06:36 +00:00
Christopher Bate
5c561a32a5
[MLIR] Fix broken 'Successor<CPred<...>>' functionality in mlir-tblgen (#205375)
Previously, mlir-tblgen would generate incorrect C++ code when
passing a custom constraint to `Successor<...>`. The code would fail
to compile. We lacked end-to-end tests for this functionality and all
in-tree dialects only use `AnySuccessor` for their successors.

Custom C++ predicates for an Operation's successor(s) can be useful
in order to generate verification for certain conditions (e.g. that the
successor is the "next" block). This commit fixes the mlir-tblgen
functionality and adds end-to-end tests in the Test dialect for single
and variadic successors.

Assisted-by: Claude
2026-06-25 12:36:58 -06:00
Nikolas Klauser
34bdee76b8
Remove unused variables in the monorepo (#204994)
https://github.com/llvm/llvm-project/pull/203084 adds diagnostics about
unused variables to the libc++ containers. This patch is the fallout
from the projects I tried to build with it.
2026-06-24 11:50:30 +02:00
Ege Beysel
836f91b3a1
[mlir][tblgen]: forward overloaded interface methods to external models (#203507)
The FallbackModel/ExternalModel forwarders generated for an OpInterface
dispatched to the concrete model by the method's unique name (e.g.
`getOverloadedValue_1`), whereas the Model path already forwards by the
method's source name. For an interface that overloads a method this
prevents an external model from overriding an overload by its real name.
Forward by the source name in both paths so external models can
implement overloaded interface methods. No change for non-overloaded
methods, where the unique and source names coincide.

Previously, the external model interfaces exposed the internal name
mangling that we do for overloaded methods to the implementers,
prohibiting them from overriding these. This PR fixes that and hides the
internal name mangling from the implementers/users, and exposes source
names for overloaded methods, symmetrically to the `Model` case. E.g.
this PR allows:

```cpp
// An external model can override an OVERLOADED
// interface method by its normal (source) name.

struct BaseInterface {
  // Two overloads, both with default implementations.
  int overloadedMethod(int a)        { return a * 2; }
  int overloadedMethod(int a, int b) { return a * b; }
};

struct SpecializedInterface
    : public BaseInterface::ExternalModel<SpecializedInterface, some::Op> {

  // First overload: always worked, nothing about it is mangled.
  int overloadedMethod(int a) { ... }

  // Second overload: this is the case the PR fixes. Internally the overload is
  // given a mangled name, and the generated forwarder used to dispatch to that
  // mangled name, so this source-name override was bypassed: the call fell
  // through to the default (`a * b`), or failed to compile if no default
  // existed. The PR forwards by the source name instead, so this override is
  // the one that runs.
  int overloadedMethod(int a, int b) { return a * b + 3; }
};
```

You can also find a more concrete use-case of this in this (yet) [draft
PR](https://github.com/llvm/llvm-project/pull/204007) that depends on
this PR.

Assisted-by: Claude Code

---------

Signed-off-by: Ege Beysel <beyselege@gmail.com>
2026-06-18 09:23:07 +02:00
Maksim Levental
675fceb6a3
[mlir-tblgen] Render enum keyword alternatives in generated attr/type docs (#203677)
When mlir-tblgen generates documentation for AttrDefs/TypeDefs that have
EnumParameter fields, it previously rendered the raw C++ type (e.g.
`::mlir::ns::MyEnum`) in the syntax block. This is unhelpful for users
who need to know the valid keyword values.

This patch:
1. Adds an `EnumInfo enum = enumInfo;` field to the `EnumParameter`
TableGen class, persisting the enum record for tooling to inspect.
2. Modifies `emitAttrOrTypeDefAssemblyFormat` in OpDocGen.cpp to detect
EnumParameter fields and render their cases as backtick-quoted
alternatives (e.g. `` `read` | `read_write` ``).
3. Adds a test case to gen-dialect-doc.td verifying the new behavior.

Before:
```
  #my_dialect.my_attr<
    int32_t,   # index
    ::mlir::ns::MyEnum,   # access
  >
```

After:
```
  #my_dialect.my_attr<
    int32_t,   # index
    `read` | `read_write`,   # access
  >
```

Co-Authored-By: Claude

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Federico Bruzzone <federico.bruzzone.i@gmail.com>
Co-authored-by: makslevental <m_levental@apple.com>
2026-06-15 12:33:03 -07:00
crockeea
358412632f
[MLIR][ODS] Do not emit code when printing empty lists in Type/Attr assembly printer (NFC) (#201174)
In TableGen's code generator, `DefFormat::genCommaSeparatedPrinter` can
emit code like
```
void FooType::print(::mlir::AsmPrinter &odsPrinter) const {
  ::mlir::Builder odsBuilder(getContext());
  odsPrinter << "<";
  {
    bool _firstPrinted = true;
  }
  odsPrinter << ">";
}
```

This results in unused variable warnings for `_firstPrinted` when
compiling the table-gen'd code:
```
warning: unused variable '_firstPrinted' [-Wunused-variable]
  158 |     bool _firstPrinted = true;
```

The solution to this is to not emit the `{ bool _firstPrinted = true; }`
block when list being printed is empty. This PR adds a guard around the
code that emits the `{ bool _firstPrinted = true; }`: it is now only
emitted if there are arguments to print. In this case, additional code
is emitted which uses `_firstPrinted`.
2026-06-10 23:09:05 +02:00
Fangrui Song
f7f6e6f401
[mlir] Remove unused DenseMapInfo::getEmptyKey (#201991)
After #201281 DenseMapInfo<T>::getEmptyKey() is no longer used by
DenseMap. Remove the unused getEmptyKey definitions and dead sentinel
uses.
2026-06-06 12:33:34 -07:00
Matthias Springer
67aaa03dac
[mlir][IR] Add builtin TokenType (#195640)
Introduces a new parameterless, opaque, builtin SSA value type,
`!token`. A token cannot appear in a value-forwarding position such as
`cf.br`, `arith.select`, `scf.for` iter-args or function call/return.
Walking back from any token use reaches the producing operation without
crossing such a boundary. Tokens carry no runtime data and cannot
constant-fold.

This contract is enforced by changing the default ODS `AnyType`
predicate to exclude tokens. In addition, token-producing and
token-consuming ops must opt in by implementing the `ProducesToken` and
`ConsumesToken` traits. The IR verifier checks for the presence of these
traits.

Note: CSE, DCE, hoisting, and `OperationEquivalence` remain unchanged. A
stronger contract (e.g., uniqueness, arity, paired lifetime), if
desirable based on the semantics of token-producing and token-consuming
ops, can be expressed at the op level via existing mechanisms (side
effects, block arguments, traits, attributes), keeping the type
orthogonal to operation-level transformations. This mirrors LLVM's
`token` type.

Other changes:
* Builtin bytecode: new entry for `TokenType`.
* AsmParser / AsmPrinter: `token` keyword for the textual format.
* Remove `LLVMTokenType` from the LLVM dialect and use the builtin
`TokenType` instead.
* Async dialect: references to `async::TokenType` are qualified to
disambiguate from the new builtin `TokenType`.
* Documentation: new `mlir/docs/Tokens.md` covering the structural
contract, design rationale, and ODS integration.

No changes to `Operation`, the generic op syntax, the bytecode op
encoding, or core C++ APIs around `Operation`.

This commit is in preparation of adding support for breaking exit from
regions. (E.g., early exit from loops.)

RFC:
https://discourse.llvm.org/t/rfc-add-a-builtin-token-type-to-mlir/90706

Assisted-by: claude-opus-4.7-thinking-high

---------

Co-authored-by: Mehdi Amini <joker.eph@gmail.com>
2026-06-02 12:33:46 +02:00
Fangrui Song
4b91251dd8
[mlir] Remove unused DenseMapInfo::getTombstoneKey (#200633)
#200595 changed DenseMap to no longer create tombstone buckets, so
DenseMapInfo<T>::getTombstoneKey() is never called. Remove dead
definitions and dead tombstone branches.
2026-06-01 14:27:21 -07:00
Alan Li
862ba4798e
Reland "[MLIR] Add IntegerDivisibilityAnalysis and InferIntDivisibilityOpInterface" (#198110)
Relands #197728, which was reverted in #198048 because it broke
shared-library builds.


## Summary of build fix:
`IntegerDivisibilityAnalysis.cpp` calls
`mlir::getConstantIntValue(OpFoldResult)`, which is defined in
`mlir/lib/Dialect/Utils/StaticValueUtils.cpp`. Without this link
dependency, shared-library
builds of `libMLIRAnalysis.so` fail with undefined references.

This was the root cause of
https://github.com/llvm/llvm-project/pull/198048.
2026-05-18 16:01:06 -04:00
Kewen Meng
88afb5af47
Revert "[MLIR] Add IntegerDivisibilityAnalysis and InferIntDivisibilityOpInterface" (#198048)
Reverts llvm/llvm-project#197728

unblock bots: 
https://lab.llvm.org/buildbot/#/builders/226
https://lab.llvm.org/buildbot/#/builders/203
2026-05-15 17:25:31 -07:00
Alan Li
ba0fef9f9e
[MLIR] Add IntegerDivisibilityAnalysis and InferIntDivisibilityOpInterface (#197728)
This patch is a port from
https://github.com/iree-org/iree/blob/main/compiler/src/iree/compiler/Dialect/Util/Analysis/IntegerDivisibilityAnalysis.cpp
to upstream

It introduces a dataflow analysis that tracks integer divisibility
(divisor + remainder lattice) for SSA values, plus an op interface
`InferIntDivisibilityOpInterface` for ops to participate.

It adds:
* `IntegerDivisibilityAnalysis` produces a `Divisibility` lattice
`{divisor, remainder}`
* `InferIntDivisibilityOpInterface` interface
* External-model implementations for `arith` and `affine` ops
* `test-int-divisibility` test pass + lit tests

Example:
Here is the usual approach to laod element `i` from `i4` buffer emulated
in `i8` buffer:
```mlir
  %byte_idx = arith.divui %i, %c2 : index
  %bit_off  = arith.remui %i, %c2 : index
  %byte     = memref.load %buf[%byte_idx] : memref<?xi8>
  %shifted  = arith.shrui %byte, %bit_off_as_i8
  %nibble   = arith.andi  %shifted, %c0xF : i8
```
If `i` comes from `affine.apply (d0) -> (d0 * 8 + 0)` over loop IV,
analysis derives `divisor=8, remainder=0` for `%i`. Then we can emit
more concise code by avoiding the shift. There are more scenarios that
could benefit from this analysis.
2026-05-15 19:11:39 -04:00
Diksha
1537c32236
[mlir] Use add_tablegen() for mlir-src-sharder to fix aarch64 cross-compile (#196202)
`add_tablegen()` already sets `MLIR_SRC_SHARDER_TABLEGEN_EXE` to the
native host-tool path during cross-compilation (via
`build_native_tool`). The leftover manual
`set(MLIR_SRC_SHARDER_TABLEGEN_EXE mlir-src-sharder PARENT_SCOPE)`
clobbered that path with the bare binary name, causing aarch64
cross-builds to fail with:

```
/bin/sh: 1: mlir-src-sharder: not found
```

when sharding `TestOps`. Switching `mlir-src-sharder` from
`add_llvm_executable` to `add_tablegen` (and dropping the redundant
`set(... PARENT_SCOPE)`) lets the existing cross-compile machinery point
consumers at the host build of the tool.
2026-05-12 20:27:28 +02:00
Max191
d4ba0194f5
[mlir] Add analysis filter in dataflow solver (#192998)
Adds an optional filtering control function to the dataflow solver's
initializeAndRun callback, which controls which analyses will be
initialized when running the solver. This makes it possible to reuse
existing dataflow solver instances that have already run to a fixpoint
without re-initializing all of the analyses that have already converged.

A new analysis and test pass is also added, which illustrates how the
filtering can be useful to run a staged analysis, which would not have
been possible before. The example analysis, called `BarAnalysis`,
depends on the converged state of the `FooAnalysis`. The Bar analysis is
a forward analysis that tracks, for each program point, whether any of
the preceding program points hold a `foo_state` that is divisible by 4.
In the example test, the control flow graph looks like the following:

```
  entry-block
   /       \
bb0         bb2
    \     /
      bb1
```
The `foo_state` of `bb1` depends on the `foo_state` of `bb0` and `bb2`.
If the solver goes through `bb0->bb1` before `bb2->bb1`, then there is
an intermediate stage in the analyses where the state of `bb1` could be
divisible by 4, even though the final state of `bb1` will not be
divisible by 4 in the converged state. If the `BarAnalysis` runs on
`bb1` in this intermediate state, then it will get stuck with the
"divisible by 4" state, and the analysis will not yield the desired
results.

This PR ensures that the `BarAnalysis` will see the correct state
`foo_state`, because the `FooAnalysis` will fully run to a fixpoint
before the `BarAnalysis` is loaded, initialized, and run.

The Foo and Bar analyses are just trivial examples, but this pattern is
useful when there are analyses that can be made more effective by using
complementary analyses like integer range/divisibility analyses.

**Note for integration:**

DataFlowSolver::load now stores the concrete analysis TypeID, exposed
via DataFlowAnalysis::getTypeID(). Downstream DataFlowAnalysis
subclasses defined in anonymous namespaces must add
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ClassName) to their class
body.

Assisted-by: Codex (gpt-5.4)
2026-04-24 15:25:49 -04:00
Vincentius Janssen
0bdaf63d01
[mlir] Enhance error messages for attribute type mismatch in properties (#193758) 2026-04-23 20:37:51 +02:00
Davide Grohmann
205ff02098
[mlir][spirv] Tighten types of SPIR-V TOSA op definitions (#192623)
Tighten the SPIR-V TOSA op definitions by introducing stricter named
type constraints and aligning verifier coverage with the new type
surface.

Remove implication checks that are now enforced directly by
operand/result type constraints.

Drop the corresponding negative tests that no longer exercise those
verifier paths.

Signed-off-by: Davide Grohmann <davide.grohmann@arm.com>
2026-04-20 20:50:08 +02:00
Mehdi Amini
f3fce677f2
[MLIR][ODS] Error on optional attribute used outside optional group in assemblyFormat (#188726)
Using an optional attribute directly in assemblyFormat (e.g., `$attr
attr-dict`) without wrapping it in an optional group causes the
generated printer to call `printAttribute` with a null `Attribute` when
the attribute is absent. This leads to a crash in the alias initializer
when it calls `getAlias` on a null attribute.

Add a validation check in `OpFormatParser::verifyAttributes` that
detects this pattern and emits a diagnostic error with a helpful note
pointing users to the correct `($attr^)?` syntax.

Fixes #58064

Assisted-by: Claude Code
2026-04-13 13:23:04 +02:00
AidinT
461a1c51bf
[mlir][ods] resolve the wrong indent issue (#189277)
The `emitSummaryAndDescComments` is used to generate summary and
description for tablegen generated classes and structs such as Dialects
and Interfaces. The generated summary and description is indented
incorrectly in the output generated file. For example
`NVGPUDialect.h.inc ` looks like the following:

```cpp
namespace mlir::nvgpu {

/// The `NVGPU` dialect provides a bridge between higher-level target-agnostic
///     dialects (GPU and Vector) and the lower-level target-specific dialect
///     (LLVM IR based NVVM dialect) for NVIDIA GPUs. This allow representing PTX
///     specific operations while using MLIR high level dialects such as Memref
///     and Vector for memory and target-specific register operands, respectively.
class NVGPUDialect : public ::mlir::Dialect {
    ...
  };

} // namespace mlir::nvgpu
```

This is because the `emitSummaryAndDescComments` trims the summary and
description from both sides, rendering the re-indentation useless. This
PR resolves this bug.
2026-04-01 15:20:54 +02:00
Krzysztof Drewniak
7fce7631a0
[mlir] Refactor opaque properties to make them type-safe (#185157)
At its core, this commit changes `OpaqueProperties` (aka a void*) to
`PropertyRef`, which is a {TypeID, void*}, where the TypeID is the ID of
the storage type of the given property (which can, as is often the case
for operations, be a struct of other properties).

Long-term, this change will allow for
1) Some sort of getFooPropertyRef() on property structs, allowing
individual members to be extracted generically
2) By having a property kind that is an OwningProprtyRef, generic
parsing (in combination with a bunch of other changes) 3) Probably a
safer C/Python API because we'll be able to indicate what's supposed to
be under a given void*

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 19:49:40 -07:00
Davide Grohmann
d5f7acdbc1
[mlir][spirv] Add Cast/Rescale ops in TOSA Ext Inst Set (#189028)
This patch introduces the following operators:

spirv.Tosa.Cast
spirv.Tosa.Rescale

Also dialect and serialization round-trip tests have been added.

Signed-off-by: Davide Grohmann <davide.grohmann@arm.com>
2026-03-31 14:31:04 +02:00
Sergei Lebedev
b544ad5703
[MLIR] [Python] Added a way to extend MLIR->Python type mappings (#189368)
The idea is to use TableGen records for both custom type constraints and
attributes:

* `PythonTypeName` is for type constraints, while
* `PythonAttrType` is for attributes.

The key types differ between these two records. `PythonTypeName` is
keyed by C++ type because multiple type constraints map to the same C++
type (e.g. `I32` and `I64` both map to `::mlir::IntegerType`), so a
single entry covers all of them. `PythonAttrType` is keyed by TableGen
def name because different attributes can share the same C++ storage
type but need distinct Python types (e.g. `I32ArrayAttr` and
`StrArrayAttr` are both `::mlir::ArrayAttr`).

We could in theory reimplement `getPythonAttrName` using the same
approach, but I decided to leave it for future PRs.
2026-03-31 11:00:40 +01:00
Jackson Stogel
7ccd92e5e6
[mlir][python] Disable pytype not-yet-supported error on Buffer import (#189440)
For pyhon versions <3.12, pytype complains that:

```
error: in <module>: collections.abc.Buffer not supported yet [not-supported-yet]
  from collections.abc import Buffer as _Buffer
```

Since it seems like this code intends to support <3.12, disabling the
type error on this line.
2026-03-30 11:21:35 -07:00
Sergei Lebedev
dd9bc6603c
[MLIR] [Python] The generated op definitions now use typed parameters (#188635)
As with operand/result types this only handles standard dialects, but I think it is still useful as is.

We could consider extensibility if/when necessary.
2026-03-29 12:39:48 +01:00
Mehdi Amini
509f181f40
[MLIR][TableGen] Fix ArrayRefParameter in struct format roundtrip (#189065)
When an ArrayRefParameter (or OptionalArrayRefParameter) appears in a
non-last position within a struct() assembly format directive, the
printed
output is ambiguous: the comma-separated array elements are
indistinguishable from the struct-level commas separating key-value
pairs.

Fix this by wrapping such parameters in square brackets in both the
generated printer and parser. The printer emits '[' before and ']' after
the array value; the parser calls parseLSquare()/parseRSquare() around
the
FieldParser call. Parameters with a custom printer or parser are
unaffected
(the user controls the format in that case).

Fixes #156623

Assisted-by: Claude Code
2026-03-27 18:41:46 +00:00
Davide Grohmann
71ea39a157
[mlir][spirv] Add Gather/Scatter/Resize ops in TOSA Ext Inst Set (#188497)
This patch introduces the following operators:

spirv.Tosa.Gather
spirv.Tosa.Scatter
spirv.Tosa.Resize

Also dialect and serialization round-trip tests have been added.

Signed-off-by: Davide Grohmann <davide.grohmann@arm.com>
2026-03-27 15:13:53 +01:00
Sergei Lebedev
396d63813c
[MLIR] [Python] More improvements to type annotations (#188468)
* `mlir.ir` now exports `_OperationBase`. It is handy to use when both
`Operation` and `OpView` are accepted.
* Added type arguments where they were missing, e.g.
`list[ir.Attribute]` instead of just `list`.
* Changed `Opview.build_generic` and `OpView.parse` to return `Self`
instead of the supertype `Type`.
* Changed the bindings generator to emit a parameterized `OpResult` when
the exact type is available.
2026-03-25 14:18:29 +00:00
Robert Konicar
da5d4214bc
[MLIR][TableGen] Make optional enum parser not consume the token when it is not matched (#188008)
Previously the optional parser would consume the token even when it
failed to match a value of the enum and prevented parsers later in the
op syntax from having an attempt. This PR changes that so that the token
is consumed only when the parsing succeeds. This change is made to the
emitted `FieldParser<std::optional<T>>` for enums.

This, for example, allows having a simple list of default valued props
in the assembly format without needing decorations around them. This
mimics the behaviour that is emitted for `DefaultValuedAttribute` when
it is used with `EnumAttr`.

This PR also adds `parseOptionalString` variant with an allow-list
argument as `parseOptionalKeyword` has and adds
`parseOptionalKeywordOrString` allow-list variant which combines these
two into a single utility wrapper. These methods do not consume the
token unless it is from the allow-list.
2026-03-23 17:33:49 +01:00
Maksim Levental
c3f381ccfe
[mlir-python] Fix duplicate EnumAttr builder registration across dialects. (#187191)
When multiple dialects share td `#includes` (e.g. `affine` includes
`arith`), each dialect's `*_enum_gen.py` file registers attribute
builders under the same keys, causing "already registered" errors on the
second import; the first commit checks in such a case which currently
fails on main:

```
# | RuntimeError: Attribute builder for 'Arith_CmpFPredicateAttr' is already registered with func: <function _arith_cmpfpredicateattr at 0x78d13cbe9a80>
```

This PR implements a two-pronged fix:

1. Add `allow_existing=True` to `register_attribute_builder` (and the
underlying C++ `registerAttributeBuilder`). When set, silently skips
registration if the key already exists (first-wins semantics). This
handles `EnumInfo`-based builders which have no dialect prefix (e.g.
`AtomicRMWKindAttr`, `Arith_CmpFPredicateAttr`), which may be emitted by
every dialect whose td file includes the defining file;
2. Filter `EnumAttr` builders by `-bind-dialect` in
`EnumPythonBindingGen.cpp` and register them under dialect qualified
keys (`"dialect.AttrName"`). Update `OpPythonBindingGen.cpp` to look up
the same qualified keys for EnumAttr typed op attributes (detected via
`isSubClassOf("EnumAttr")`). Pass `-bind-dialect` from
`AddMLIRPython.cmake`.

This approach incurs no changes to `ir.py` registrations (no "builtin."
prefix), and no manual builder additions to individual dialect Python
files (unlike the previous attempt
https://github.com/llvm/llvm-project/pull/117918).

Note, this PR was "clauded" not "coded".
2026-03-19 21:02:23 -07:00
Mehdi Amini
2531b1692c
[mlir][bytecode] Use getChecked<T>() in bytecode reading to avoid crashes (#186145)
When the bytecode type callback (test-kind=2) calls iface->readType()
for every builtin type, complex types like MemRefType could crash
because the generated reading code used get<T>() which asserts on
invalid parameters, rather than getChecked<T>() which returns null
gracefully.

This change:
- Adds a getChecked<T>() free function helper in
BytecodeImplementation.h that calls T::getChecked(emitError, params)
(no-context form) when a specific override exists, otherwise falls back
to get<T>(). The with-context second branch is intentionally omitted to
avoid instantiating StorageUserBase::getChecked<Args> for types that
only inherit the base template (e.g. ArrayAttr), which would require
complete storage types unavailable in the bytecode reading TU.
- Updates BytecodeBase.td default cBuilder for
DialectAttribute/DialectType to use getChecked<> instead of get<>.
- Updates all custom cBuilder strings in BuiltinDialectBytecode.td.
- Updates the no-args codegen case in BytecodeDialectGen.cpp.
- Adds a regression test in bytecode_callback_with_custom_type.mlir.

Fixes #128308

Assisted-by: Claude Code
2026-03-17 18:44:56 +01:00
Jakub Kuderski
fef16a71d3
[mlir][ODS] Fix notorious double-space bug in op printers (#184253)
When an op's assembly format prints an attribute via
`printStrippedAttrOrType`, two independent space-emission mechanisms
would fire: the op format generator emits a space before each argument,
and the attribute's generated `print` method also emits a leading space
(`shouldEmitSpace` initialized to true). This caused double spaces like
`gpu.shuffle xor`.

The usual workaround for this was to add double backticks to consume the
leading space.

Fixed by removing the leading space from generated attr/type `print()`
methods and compensating in the print dispatcher by conditionally adding
a space between the mnemonic and `print` call when the format starts
with a name or keyword rather than punctuation.

Also remove some workarounds for the double-spacing in op formats and
fix tests that now don't have leading spaces.

Assisted-by: claude
2026-03-06 16:32:01 -05:00
Ayush Kumar Gaur
774f740e0b
[mlir] Avoid ASan ODR violation in mlir-src-sharder with LLVM dylib (#181045)
Build mlir-src-sharder via add_llvm_executable instead of add_tablegen
to avoid embedding a second copy of LLVM Support when linking against
libLLVM.so. Fixes ASan ODR violation for DisableABIBreakingChecks 

Tested with ASan + LLVM dylib configuration; tool runs without abort.
Fixes #180911
2026-03-05 11:42:47 +01:00
Adam Siemieniuk
6b59ad6e8d
[mlir][linalg] Data layout propagation test schedule (#184151)
Replaces data layout propagation test pass with equivalent transform
schedule.

The two required patterns are wrapped in new linalg transform ops
improving reusability.
2026-03-04 08:36:29 +01:00
Frank Schlimbach
a232b5b96f
[mlir][shard, mpi] Adding Shard/MPI reduce_scatter and simplification (#184189)
- introduces a simplify pass, which finds such patterns and replaces it
with the equivalent `reduce-scatter`
- promotes the test-pass `test-shard-optimizations` to a proper pass and adds
  - folding allgather+allslice into reduce_scatter
- sanitizes the `shard.reduce_scatter` op
- adds a new `mpi.reduce_scatter_block` op
- lowers `shard.reduce_scatter` to MPI
- lowers `mpi-reduce_scatter_block` to llvm

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-03 17:34:36 +01:00
Jacques Pienaar
32134a64b1
[mlirbc] Switch generator to enable write's with failures. (#182464)
Previously one had to have a matching case per entry (e.g., one could
use a printer predicate, but the assumption was one woujld never
fallback) and just always return success.
2026-02-27 07:10:49 +02:00
Vitaly Buka
f30dfe7de4
Revert "[mlir-tblgen] Remove namespace {} around OpDocGroup (#182721)" (#183458)
Reverts #182721, it's not needed after #183457.

It was a work around for #182720.

This reverts commit a0f344f69d.
2026-02-27 03:36:35 +00:00
Mehdi Amini
5a4a5db477
[MLIR] Remove deprecated setting usePropertiesForAttributes (#182327)
This was slotted for removal in LLVM 19 in the release notes of LLVM 17,
we're way past it now.

If your dialect still has:

> let usePropertiesForAttributes = 1;

Then you can just remove this line (it was the default value).
If you were setting it to 0:

> let usePropertiesForAttributes = 0;

Then you need to adopt the new behavior, please report any issue with
this migration.
2026-02-24 17:50:38 +01:00
Vitaly Buka
a0f344f69d
[mlir-tblgen] Remove namespace {} around OpDocGroup (#182721)
This is temporary workaround for Asan report #182720.
2026-02-22 04:36:58 +00:00
Fabian Schuiki
a8f2e80d5f
[MLIR][tblgen] Honor -dialect in -gen-{attrdef,op,typedef,enum}-doc (#182183)
Make all dialect documentation generators use the same set of records as
`-gen-dialect-doc`, which honors the `-dialect` tblgen option to filter
records by dialect. Add a `-keep-op-source-order` option to allow
`-gen-op-doc` to continue producing unsorted op lists if needed.

This commit factors the record collection, filtering, and sorting
performed in `emitDialectDoc` out into a separate `collectRecords`
function, returning a `DialectRecords` with the results. The emit
functions now all accept a `DialectRecords` argument instead of
collecting records themselves. Most changes are mechanical renamings and
moving code around.

This fixes a confusing issue where `gen-dialect-doc` would produce the
entire documentation for a dialect, but individual calls to
`gen-attrdef-doc` and the like would seemingly operate on a different
set of records, potentially covering multiple dialects. This all produce
the overall documentation now.
2026-02-19 11:36:05 -08:00
AidinT
f46c2c46d1
[MLIR] Convert DialectReductionPatternInterface using ODS (#180640)
This PR converts `DialectReductionPatternInterface` using ODS.

It also introduces a new Interface Method class:

`PureVirtualInterfaceMethod` which creates the method as pure virtual.
2026-02-16 20:04:38 +02:00
Christian Ulmann
54c080da2c
[MLIR][ODS] Make dialect attribute helper member functions const (NFC) (#181111)
This commit marks member functions of dialect attribute helpers as
constant. This ensures that these helpers can be used as members of
rewrite patterns, whose `matchAndRewrite` functions are marked as const
as well.
2026-02-13 07:38:06 +01:00
Henrich Lauko
6c51938067
[MLIR] Guard optional operand resolution in generated op parsers (#180796)
Skip resolveOperands for optional operands when they are absent to
avoid out-of-bounds access on the empty types vector.
2026-02-11 08:25:03 +01:00
Tim Noack
254b3b137e
[mlir][tblgen] Add PredTypeTrait/PredAttrTrait support (#169153)
This patch adds support for `PredTypeTrait` and `PredAttrTrait` in type
and attribute definitions, enabling declarative predicate-based
verification similar to how `PredOpTrait` works for operations.

  ## Motivation

In 802bf02 (from 2021), `PredTypeTrait`/`PredAttrTrait` were defined in
TableGen but not implemented in the code generator. Using them causes
mlir-tblgen to crash with an assertion failure when trying to cast
`PredTrait` to `InterfaceTrait`. This patch fixes the crash and
implements the actual verification code generation.

  ## Usage

Use `$paramName` syntax in predicates to reference type/attribute
parameters:

  ```tablegen
  def MyType : MyDialect_Type<"MyType",
      [PredTypeTrait<"value must be positive", CPred<"$value > 0">>]> {
    let parameters = (ins "unsigned":$value);
    let mnemonic = "my_type";
    let assemblyFormat = "`<` $value `>`";
  }
  ```

  This generates verification code in `verifyInvariantsImpl()`:
```cpp
  if (!(value > 0)) {
    emitError() << "failed to verify that value must be positive";
    return ::mlir::failure();
  }
  ```
2026-02-03 14:00:56 -08:00
Davide Grohmann
b36d14d619
[mlir][spirv] Add Activation operators to TOSA Extended Instruction S… (#178620)
…et (001000.1)

In details the Activation operators introduced are:
spirv.Tosa.{Clamp,Erf,Sigmoid,Tanh}, along with dialect and
serialization round-trip tests.

Signed-off-by: Davide Grohmann <davide.grohmann@arm.com>
2026-02-03 08:56:31 -05:00