Repository navigation
Fix MLIR.jl on Julia 1.13: use MLIR_jll.mlir_c directly + small bugfixes - #88
Conversation
Julia 1.13 tightened the `@ccall` macro to require the library form
be a bare identifier, `Symbol`, or literal `String`. The previous form
`@ccall (MLIR_C_PATH[]).xxx(...)` (with `MLIR_C_PATH::ScopedValue{String}`,
introduced in JuliaLLVM#71) now errors at parse time with
"TypeError: in ccall library name, expected Symbol, got a value of type Expr"
and prevents the package from loading.
Reproducer (no MLIR.jl needed):
const LIBC = Ref{String}("libc.so.6")
@CCall (LIBC[]).getpid()::Int32 # OK on 1.12; errors on 1.13+
Switch the auto-generated `@ccall` library binding from the now-removed
`MLIR_C_PATH` indirection to `MLIR_jll.mlir_c` directly. `mlir_c` is a
JLLWrappers-managed bare-identifier global whose path is initialized at
JLL load time and whose form `@ccall mlir_c.fn(...)` is accepted across
every supported Julia version.
This drops the `LocalPreferences.toml`-based `MLIR_C_PATH` override and
the (unused) per-task `ScopedValue` override. Users who want a custom
libMLIR-C can override `MLIR_jll`'s artifact via Overrides.toml or
`Pkg.develop(MLIR_jll)` — the standard JLL-override path.
Per-task `MLIR_VERSION` override remains a `ScopedValue` and is
unaffected — that's the more useful capability and continues to work.
Changes:
- bindings/wrap.toml: `library_name` = "MLIR_C_PATH[]" -> "mlir_c"
- src/MLIR.jl: drop `MLIR_C_PATH`, import `mlir_c` from MLIR_jll
- src/API/API.jl: per-version submodules import `mlir_c` instead of `MLIR_C_PATH`
- src/API/{14..21}/libMLIR_h.jl: equivalent to running `make-api.jl` after
the wrap.toml change — `MLIR_C_PATH[]` -> `mlir_c` throughout.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`Region.jl:65`, `Operation.jl:291`, and `Operation.jl:304` all call
`mark_donate(obj)` (single-arg) and pass the return value as the donated
object to a libMLIR C-API call (e.g. `mlirRegionAppendOwnedBlock(region,
mark_donate(block))`).
Before this change `debug.jl` only defined the 2-arg `mark_donate(new_owner, obj)`,
which calls `mark_dispose(obj)` — and `mark_dispose` returns `nothing`. So:
- On any call site, `Region.jl:65` etc. would fail with a MethodError
because the 1-arg form was undefined.
- If the 1-arg form had existed (or been added) returning `nothing`, the
consuming C API call would convert `nothing` -> C_NULL and either fail
its own validation or crash.
Add the missing 1-arg `mark_donate(obj)` overload and change both
overloads to return `obj` after the dispose tracking. This matches the
underlying semantics ("hand ownership over but the handle remains
syntactically usable for one more call").
Reproducer:
using MLIR.IR
activate(Context())
blk = Block() # constructs a Block
push!(Region(), blk) # -> MethodError before this fix
# -> succeeds after
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`operandsegmentsizes` and `resultsegmentsizes` in src/Dialects/Dialects.jl construct `NamedAttribute(...)` but the parent `MLIR.IR.NamedAttribute` name was never brought into scope, so any call to either function fails with `UndefVarError: NamedAttribute not defined in MLIR.Dialects`. This surfaces immediately for any dialect op whose builder needs `operand_segment_sizes` (e.g. `llvm.intr.assume` constructed via `IR.create_operation` with an explicit `operand_segment_sizes` attr). Add the missing `using ..MLIR.IR: NamedAttribute`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…-process; multi-MLIR-version support Replaces `Reactant.MLIR.IR` / `Reactant.MLIR.Dialects` with vanilla `MLIR.jl` (1.0.x main, dev'd against gbaraldi/MLIR.jl#fix-julia-1.13-ccall pending JuliaLLVM/MLIR.jl#88). Drops the `mlir-opt` / `mlir-translate` shell-out: pipelines now run in-process via `MLIR.IR.PassManager` and LLVM-IR translation via `mlirTranslateModuleToLLVMIR` + LLVM C API. clang remains the final-codegen step for `-O2 -shared -fPIC` + libomp link. The walker emits the same upstream MLIR dialects (no Reactant- or EnzymeXLA-specific ops); per-MLIR-version dialect-syntax differences are handled by `MLIR.MLIR_VERSION[]`-conditional emission in the walker and a version-aware textual-pipeline builder (`_wrap_pass` nests passes anchored at func::FuncOp under `func.func(...)`, `_pass_available` filters passes not yet registered through libMLIR-C on the current version). Concrete version-conditional fixes (verified against MLIR 18 on Julia 1.12 and MLIR 20 on Julia 1.13): - `vector.multi_reduction.reduction_dims` — `[N : i64]` (I64ArrayAttr) on MLIR 18, `array<i64: N>` (DenseI64ArrayAttr) on MLIR 19+. - `memref.atomic_rmw kind` enum integer codes — reordered between MLIR 18 and 20, `xori` removed in 20; per-version table + the walker still routes `:xor` through the generic CAS path. - `memref.assume_alignment` result form — MLIR 18 is result-less, MLIR 21+ returns the memref; emit accordingly and bind downstream Value. - `vector.step` — native op on MLIR 19+; on MLIR 18 emit `arith.constant dense<[0..N-1]>` via textual parse (typed `DenseElementsAttribute(::Vector{Int64})` overload builds a TensorType shape that can't retarget at a VectorType). - `vector.insert_strided_slice` kwarg — both MLIR 18 and 20 bindings use `res=`, not `result=` (pre-existing walker typo, surfaced now that the pipeline gets further on MLIR 20). Pass pipeline order on MLIR 19+: 1. `convert-math-to-llvm` — math ops with LLVM intrinsics (incl. `math.rsqrt` → `1.0 / llvm.intr.sqrt`). MUST run before libm, otherwise libm emits a `rsqrtf` call to a function that doesn't exist in standard libm, dlopen fails at launch. 2. `convert-math-to-libm` — picks up the remainder (e.g. `math.tanh` on MLIR 20 has no LLVM intrinsic registered). Scalarizes vector forms via `vector.extract` per lane + scalar libm call. 3. `func.func(lower-vector-multi-reduction)` — decomposes `vector.multi_reduction` into `vector.reduction` + assembly that `convert-vector-to-llvm` can match. Skipped on MLIR 18 (not registered through libMLIR-C). 4. `convert-vector-to-scf` → `convert-vector-to-llvm` — must precede `convert-openmp-to-llvm` (which rewrites region argument types to `!llvm.array<...>`, after which residual vector ops can't be matched), AND must follow `convert-math-to-libm` (to lower the `vector.extract/insert` ops the libm scalarization emits). 5. omp → llvm → cf → memref → arith → func → cf → ub → reconcile-unrealized-casts. Other changes: - `compile_module_to_so(mod, mlir_ctx; ...)`: launches now take the `IR.Module` directly, skipping the textual round-trip (which doesn't round-trip cleanly through MLIR 18's printer/parser for ops like `vector.multi_reduction`). - `fresh_context()`: creates a `Context` with all upstream dialects pre-registered via `mlirRegisterAllDialects` + `mlirRegisterAllLLVMTranslations` + `load_all_available_dialects` (matches what Reactant's `ReactantContext` did, minus the EnzymeXLA dialects). - `@with_context` / `@with_module` / `@with_block` reimplemented as activate/deactivate try/finally wrappers (MLIR.jl exposes the primitives but not the macro trio). - `MLIR_jll` compat set to `"18, 19, 20"`: omits v21 which the resolver picks unusably on Julia 1.13 (Pkg ignores its `libLLVM_jll = "21.1.2-21"` compat against stdlib libLLVM_jll; JLLWrappers then returns `is_available() == false` at runtime). Test status: - Julia 1.13 + MLIR_jll v20.1.8: 232/232 tests pass. - Julia 1.12 + MLIR_jll v18.1.7: ~218/232 pass, 14 errored / 1 fail — same as pre-swap baseline. Remaining gaps are MLIR-18-specific (lower-vector-multi-reduction not registered through libMLIR-C, `math.tanh` LLVMTranslationDialectInterface missing) and self-heal on Julia 1.13+. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…-process; multi-MLIR-version support Replaces `Reactant.MLIR.IR` / `Reactant.MLIR.Dialects` with vanilla `MLIR.jl` (1.0.x main, dev'd against gbaraldi/MLIR.jl#fix-julia-1.13-ccall pending JuliaLLVM/MLIR.jl#88). Drops the `mlir-opt` / `mlir-translate` shell-out: pipelines now run in-process via `MLIR.IR.PassManager` and LLVM-IR translation via `mlirTranslateModuleToLLVMIR` + LLVM C API. clang remains the final-codegen step for `-O2 -shared -fPIC` + libomp link. The walker emits the same upstream MLIR dialects (no Reactant- or EnzymeXLA-specific ops); per-MLIR-version dialect-syntax differences are handled by `MLIR.MLIR_VERSION[]`-conditional emission in the walker and a version-aware textual-pipeline builder (`_wrap_pass` nests passes anchored at func::FuncOp under `func.func(...)`, `_pass_available` filters passes not yet registered through libMLIR-C on the current version). Concrete version-conditional fixes (verified against MLIR 18 on Julia 1.12 and MLIR 20 on Julia 1.13): - `vector.multi_reduction.reduction_dims` — `[N : i64]` (I64ArrayAttr) on MLIR 18, `array<i64: N>` (DenseI64ArrayAttr) on MLIR 19+. - `memref.atomic_rmw kind` enum integer codes — reordered between MLIR 18 and 20, `xori` removed in 20; per-version table + the walker still routes `:xor` through the generic CAS path. - `memref.assume_alignment` result form — MLIR 18 is result-less, MLIR 21+ returns the memref; emit accordingly and bind downstream Value. - `vector.step` — native op on MLIR 19+; on MLIR 18 emit `arith.constant dense<[0..N-1]>` via textual parse (typed `DenseElementsAttribute(::Vector{Int64})` overload builds a TensorType shape that can't retarget at a VectorType). - `vector.insert_strided_slice` kwarg — both MLIR 18 and 20 bindings use `res=`, not `result=` (pre-existing walker typo, surfaced now that the pipeline gets further on MLIR 20). Pass pipeline order on MLIR 19+: 1. `convert-math-to-llvm` — math ops with LLVM intrinsics (incl. `math.rsqrt` → `1.0 / llvm.intr.sqrt`). MUST run before libm, otherwise libm emits a `rsqrtf` call to a function that doesn't exist in standard libm, dlopen fails at launch. 2. `convert-math-to-libm` — picks up the remainder (e.g. `math.tanh` on MLIR 20 has no LLVM intrinsic registered). Scalarizes vector forms via `vector.extract` per lane + scalar libm call. 3. `func.func(lower-vector-multi-reduction)` — decomposes `vector.multi_reduction` into `vector.reduction` + assembly that `convert-vector-to-llvm` can match. Skipped on MLIR 18 (not registered through libMLIR-C). 4. `convert-vector-to-scf` → `convert-vector-to-llvm` — must precede `convert-openmp-to-llvm` (which rewrites region argument types to `!llvm.array<...>`, after which residual vector ops can't be matched), AND must follow `convert-math-to-libm` (to lower the `vector.extract/insert` ops the libm scalarization emits). 5. omp → llvm → cf → memref → arith → func → cf → ub → reconcile-unrealized-casts. Other changes: - `compile_module_to_so(mod, mlir_ctx; ...)`: launches now take the `IR.Module` directly, skipping the textual round-trip (which doesn't round-trip cleanly through MLIR 18's printer/parser for ops like `vector.multi_reduction`). - `fresh_context()`: creates a `Context` with all upstream dialects pre-registered via `mlirRegisterAllDialects` + `mlirRegisterAllLLVMTranslations` + `load_all_available_dialects` (matches what Reactant's `ReactantContext` did, minus the EnzymeXLA dialects). - `@with_context` / `@with_module` / `@with_block` reimplemented as activate/deactivate try/finally wrappers (MLIR.jl exposes the primitives but not the macro trio). - `MLIR_jll` compat set to `"18, 19, 20"`: omits v21 which the resolver picks unusably on Julia 1.13 (Pkg ignores its `libLLVM_jll = "21.1.2-21"` compat against stdlib libLLVM_jll; JLLWrappers then returns `is_available() == false` at runtime). Test status: - Julia 1.13 + MLIR_jll v20.1.8: 232/232 tests pass. - Julia 1.12 + MLIR_jll v18.1.7: ~218/232 pass, 14 errored / 1 fail — same as pre-swap baseline. Remaining gaps are MLIR-18-specific (lower-vector-multi-reduction not registered through libMLIR-C, `math.tanh` LLVMTranslationDialectInterface missing) and self-heal on Julia 1.13+. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
mofeing
left a comment
There was a problem hiding this comment.
- Replacement: Users who want a custom libMLIR-C.so can override MLIR_jll's artifact via Overrides.toml or Pkg.develop(MLIR_jll) — the standard JLL-override path that already works for every other JLL-backed library.
If preserving the MLIR_C_PATH ScopedValue is desired, the alternative is a dlsym-cached function-pointer form (
@ccall \$(_dlsym(:fn))(args)::ret)emitted by the generator — happy to do that instead if preferred, but it's a bigger generator change for a feature that isn't exercised by tests or docs.
As we discussed at JuliaCon, this is a blocker for MLIR.jl users because most probably, each Julia package that wants to use MLIR.jl will need their own libMLIR build.
I'm accepting it because (1) the ScopedValue approach we use is bad practice here, (2) this package is not yet stable and AFAIK have no users, and (3) it's broken for Julia 1.13, but we should definitely move to a function-pointer form or sth similar.
I have a WIP branch that I started during JuliaCon but didn't find the time this last month. @gbaraldi will ask for your review hopefully soon.
tldr: merging because what we currently have no longer works, but keep in mind that this will also be refactored for sth that fits better to everyone.
Summary
Three independent fixes, the first of which is required to load MLIR.jl on Julia 1.13:
MLIR_jll.mlir_cdirectly as the@ccalllibrary name. Julia 1.13 tightened the@ccallmacro to reject(MLIR_C_PATH[]).fn(...)-style library forms (TypeError: in ccall library name, expected Symbol, got a value of type Expr). Drops the now-removedMLIR_C_PATHScopedValueand points@ccallstraight atMLIR_jll's JLLWrappers-managed bare-identifier global. See commit message on32ee56cfor details and reproducer.mark_donatereturns the donated object and adds a missing 1-arg overload. Without it,push!(::Region, ::Block)and severalOperation.jlinternals fail.NamedAttributeinsrc/Dialects/Dialects.jl—operandsegmentsizes/resultsegmentsizesreference it without it being in scope.Reproducers
#1 —
@ccallsyntax on Julia 1.13 (no MLIR.jl needed)Loading
MLIR.jlon Julia 1.13 fails at precompile because every auto-generated@ccall (MLIR_C_PATH[]).fn(...)site triggers this.#2 —
mark_donateMethodError#3 —
NamedAttributeUndefVarAny op builder that constructs an
operand_segment_sizesattribute viaDialects.operandsegmentsizeserrors withUndefVarError: NamedAttribute not defined in MLIR.Dialects.Behavioural change
Commit
32ee56cdrops theMLIR_C_PATHindirection:LocalPreferences.tomlMLIR_C_PATHoverride and per-taskwith(MLIR_C_PATH => …) do ... end(added in Replace version-based conditional code loading with dynamic dispatch #71).MLIR_VERSIONoverride (still aScopedValue) — that's the more useful capability and the actual reason for the dynamic-dispatch refactor in Replace version-based conditional code loading with dynamic dispatch #71.libMLIR-C.socan overrideMLIR_jll's artifact viaOverrides.tomlorPkg.develop(MLIR_jll)— the standard JLL-override path that already works for every other JLL-backed library.If preserving the
MLIR_C_PATHScopedValueis desired, the alternative is adlsym-cached function-pointer form (@ccall \$(_dlsym(:fn))(args)::ret) emitted by the generator — happy to do that instead if preferred, but it's a bigger generator change for a feature that isn't exercised by tests or docs.Files
bindings/wrap.toml:library_name = "MLIR_C_PATH[]"→library_name = "mlir_c"src/MLIR.jl: dropMLIR_C_PATH, importmlir_cfromMLIR_jllsrc/API/API.jl: per-version submodulesusing ...MLIR: mlir_csrc/API/{14..21}/libMLIR_h.jl: text-equivalent of regenerating viamake-api.jlafter thewrap.tomlchange (substitution is purelyMLIR_C_PATH[]→mlir_c). Verified the substitution is exhaustive bygrep -c "MLIR_C_PATH" src/API/*/libMLIR_h.jl→ 0.src/IR/debug.jl:mark_donate1-arg + return valuesrc/Dialects/Dialects.jl: importNamedAttributeTest plan
using MLIRprecompiles + loads on Julia 1.12 (libLLVM 18.1.7, MLIR_jll 18.1.7+4)using MLIRadvances past the@ccallprecompile error on Julia 1.13 (a separateLazyLibraryissue in MLIR_jll's JLLWrappers compat surfaces next, but is outside this PR)push!(::Region, ::Block)worksoperand_segment_sizesconstruct withoutUndefVarError🤖 Generated with Claude Code