Skip to content

selfhost: flowc MLIR emitter for spans, closures, effects, forward declarations, @gpu and the GPU dialect - #1070

Merged
godofecht merged 11 commits into
mainfrom
selfhost/mlir-emit-3
Sep 29, 2026
Merged

godofecht merged 11 commits into
mainfrom
selfhost/mlir-emit-3

Conversation

@godofecht

Copy link
Copy Markdown
Contributor

Builds on #1041 (branch selfhost/mlir-emit-2, not merged yet): its commits are the first seven here, and this PR's own work starts at 0f5becc9. Once #1041 merges, this branch rebases onto main. Plan: docs/design/mlir-in-flow.md.

What changes

The Flow MLIR emitter (compiler/src/mlirgen.flow, FLOWC_EMIT=mlir) covers the rest of slice 4, slices 5 and 6, attributes, and the GPU dialect text of slice 10, each step text-equal to the Python generator.

  • Data: spans as Python's !llvm.struct<(!llvm.ptr, i64)> (parameters, locals, .len, indexing and stores, slices of pointers, memrefs and spans, borrows at call sites), &[T] and [T; N], [v; N] written out N times, array literals as memref values, array<T>(n), the vector<4xT> rewrite of single-store memref loops, list patterns, and consts Python folds (cast-wrapped, negated, integer expressions; zero otherwise). A call to an undeclared name is func.call @name ... -> i32 as Python writes it.
  • Record update Name { ..base, f: v }: new in the Stage-A parser, marked by a parse-only AST_RECORD_UPDATE that the typecheck and MLIR emitter pass over and cgen and jsgen refuse with a located message.
  • Lambdas and closures (mlir_closure_parity.py, mlir_nested_closure_parity.py): the fat {code, env} closure, lifted @lambda_N functions with sorted free-name captures in a malloc'd environment, calls through closure locals and parameters, __flow_callback_ adapters for named functions, function names as values.
  • Effects: dispatch functions over a current-handler vtable, capability methods, @_flow_effects_init, handle install and restore, effect calls resolved to the handling capability. Other method calls lower with the receiver first. Variadic externs and the printf and scanf families are llvm.func varargs; overloads are all emitted.
  • Forward declarations (as Python's empty bodies) and [dependencies] package imports through flow_packages/.
  • Attributes: @gpu kernels and mode guards (@hot, @jit, @only(...), ...) leave the host module as in Python. FLOWC_MLIR_GPU=1 (Python's --mlir-gpu) emits gpu.module @flow_kernels. @cInclude, @cEmbed and @cImport stay refused: Python rejects the first two in all 38 corpus programs, and the third reads C headers.
  • Type aliases and units lower as their base type and f64.
  • parity_mlir.sh: fixtures spans_data, closures, effects, record_update, gpu_kernels with goldens; gpu_* fixtures are also checked in GPU mode, and --python compares every accepted program with an @gpu kernel in GPU mode too. The normalizer starts value names over at each gpu.func, since the GPU generator numbers each kernel from %1. Corpus digests re-recorded (948 programs).
  • The MLIR output buffer is 32 MiB (Python writes [v; N] out N times).
  • Bootstrap C regenerated last, in its own commit, by self-emit to a fixed point (selfhost: retire the Python C host; flowc is the only C compiler #1027 is not merged).

Parity

Against the Python generator at 84806b0d, every .flow under examples/, tests/, lib/, benchmarks/ and compiler/fixtures/, macOS, Homebrew LLVM 22.

After Accepted Text equal Run same Timing/address output Builds on neither path Text/run failures tests/lang (of 183)
#1041, run again 794 794 353 21 420 0 81
1. Spans, list patterns, arrays, folded consts 829 828 367 21 440 0 91
2. Lambdas and closures 844 843 372 21 450 0 93
3. Effects, C varargs, overloads, method calls 920 919 397 21 501 0 106
4. Forward declarations, package imports 947 946 398 21 527 0 125
5. @gpu kernels and mode guards 955 953 404 21 528 0 125
Record update 956 954 405 21 528 0 125
GPU dialect 957 955 406 21 528 0 125
Type aliases and units 968 966 413 21 532 0 126

Accepted programs beyond the text-equal ones fail in Python itself (a parser crash, and an @gpu kernel using a vec type Python cannot parse). No program builds on one path only. The run columns come from one run of the final text-equal set through both MLIR paths, counted over each commit's recorded corpus and fixtures. GPU mode: 5 of 5 corpus programs whose kernels Python lowers are text-equal; Python fails on the other 3 and flowc refuses them.

Of the refusal groups this work targeted, none of effect or capability (51), forward declaration (27) or function, span or fixed-array type (27) is left as a refusal reason; programs from those groups that still refuse stop on something else (a typecheck error, a tensor type). Of the 36 unresolved imports, 1 now resolves; Python fails on the other 35 as well (17 modules or packages missing from the checkout, 18 proof-layer programs). Of the 47 @gpu/C-interop refusals, the 8 that Python builds are @gpu, and 7 are now text-equal (the eighth has a generic function); the other 39 fail in Python.

Largest refusals left

Leaving aside proof programs (902, which Python rejects) and files flowc cannot parse (169): C-interop attributes (38, Python rejects all), unresolved imports (35, Python fails on all), Tensor-shaped struct fields (18) and Tensor arguments to struct-returning calls (8), span borrows Python rejects (15), tensor/vector/memref type names (14), typecheck failures (13), names the emitter cannot place (12), generic functions (12), while true loops Python rotates (11), expression statement forms (8) and parallel for (7).

Verification (local, macOS)

  • Bootstrap fixed point; bootstrap_from_c.sh --verify, self_host_full.sh, roundtrip.sh, parse_coverage.sh --check, fmt_check.sh --check, corpus_parity.sh --check pass.
  • parity_mlir (golden: 18 of 18 fixtures text and run, 1 GPU-mode fixture, 948 corpus programs), parity_lowering, parity_effects, parity_proofs, parity_field_dsl, parity_dynamics_dsl, parity_flow_blocks pass. parity_shader_dsl passes except its Metal compile step (no Metal toolchain on this Mac).
  • flow run --backend=mlir builds and runs effects.flow, closures.flow, spans_data.flow and record_update.flow with python and python3 replaced by failing stubs.

Python behaviour copied, and issues opened

The emitter reproduces these for text parity; the doc lists them, and the real bugs are filed so both generators can change together:

Also copied without an issue: [v; N] needs a literal N, the vector rewrite casts bounds as i32 and always says "f32" in its comment, array<u8>(n) spells memref<?xu8>, nested arrays become memref<4xmemref<3xi32>>, and a void lambda returns llvm.mlir.undef : (). Arithmetic on structs with float members (dual numbers) is refused because the emitter does not reproduce Python's float ops on struct types.

…rals, folded consts

Spans lower as Python's !llvm.struct<(!llvm.ptr, i64)>: parameters,
locals, .len, indexing, stores, slices of pointers, memrefs and spans,
and borrows at call sites. [T; N] is array<T, N>. [v; N] is written out
N times as Python's parser does. An array literal used as a value is a
stack memref, array<T>(n) is memref.alloc, and a single-statement
elementwise loop over local f32/i32 memrefs takes Python's vector<4xT>
rewrite. List patterns bind and compare elements. Consts take Python's
second path: cast-wrapped and negated literals, folded integer
expressions, and zero for anything else. A call to an undeclared name
is func.call @name returning i32, as Python emits it. The MLIR output
buffer is 32 MiB.

Accepted 829 of the corpus, 828 text-equal to Python at 84806b0, 0
text failures.
Function types lower to Python's fat closure !llvm.struct<(!llvm.ptr,
!llvm.ptr)>. A lambda is lifted to func.func private @lambda_N(%env, ...)
ahead of the declarations; its captures are its free names in sorted
order, copied into a malloc'd environment, and read back through it.
Calls through closure locals and parameters extract the code and env
pointers. A named function passed where a closure is expected goes
through a __flow_callback_ adapter, and a function name used as a value
is func.constant plus a cast to !llvm.ptr. Also: i64 literals up to
2^63-1, return void, and array and struct consts Python zero-fills.

Accepted 844 of the corpus, 843 text-equal to Python at 84806b0, 0
text failures.
…alls

Effects lower as Python's generate_effect: a current-handler global and a
NULL-checked dispatch function per operation. Capabilities emit their
methods as <Cap>_<method> functions and one zeroed vtable per handled
effect, which @_flow_effects_init fills and main calls first. handle
blocks install and restore the vtables, and an effect call inside one
calls the handling capability directly. Other method calls lower as a
call with the receiver first, as Python desugars them.

Variadic externs and the printf/scanf family are llvm.func declarations
called through llvm.call with a vararg callee type. Overloads are all
emitted, with calls resolving to the last, and calls pass the arguments
they have against the parameter types. Unknown type names and capability
parameters take Python's memref<16xi8>.

Accepted 920 of the corpus, 919 text-equal to Python at 84806b0, 0
text failures.
A forward declaration is emitted the way Python emits it, as a function
with an empty body beside the definition, which calls then resolve to.
An absolute import whose first part is a [dependencies] key in flow.toml
resolves under flow_packages/<key>/src, then flow_packages/<key>, as
Python's resolver does. The remaining unresolved imports are programs
Python cannot build either: packages missing from the checkout and
proof-layer claim imports.

Accepted 947 of the corpus, 946 text-equal to Python at 84806b0, 0
text failures.
An @gpu function is left out of the module, as Python's generate_module
splits GPU kernels off (they reach MLIR only under --mlir-gpu). Mode
guards follow transpiler._function_allowed with the modes the MLIR
backend runs under (compile, mlir): @hot, @jit, @interp and @c drop a
function, @compile and @MLIR keep it, @only and @guard keep it when they
name an active mode. @Cinclude, @cembed and @cImport stay refused: Python
rejects the first two, and the third reads C headers.

Accepted 955 of the corpus, 953 text-equal to Python at 84806b0, 0
text failures.
The Stage-A parser reads Python's record-update form into an
AST_STRUCT_LIT whose c holds the base, marked by a new parse-only
AST_RECORD_UPDATE node. The typecheck and the MLIR emitter pass over the
marker; cgen and jsgen refuse it with a located message as for any other
parse-only form. The emitter follows generate_record_update: copy the
base and insert each listed field, converted to its declared type. A
base whose type names no struct (an unannotated let, a pointer) is the
whole value, as in Python.

Corpus digests of the programs that import compiler/src/ast.flow change
with it. Accepted 956 of the corpus, 954 text-equal to Python at
84806b0, 0 text failures.
With FLOWC_MLIR_GPU=1, the counterpart of Python's --mlir-gpu, the @gpu
kernels the host module leaves out become gpu.module @flow_kernels, as
mlir_gpu_codegen.py writes it: gpu.func per kernel with the SPIR-V entry
point ABI, the gpu_* id intrinsics as gpu.block_id/block_dim/thread_id,
memref loads and stores, scf.if and scf.for with loop-carried locals,
and gpu.barrier.

The GPU generator numbers each kernel's values from %1, so the
normalizer starts value names over at each gpu.func. parity_mlir.sh
compares gpu_* fixtures in GPU mode too, and in --python mode every
accepted program with an @gpu kernel. 5 of 5 such corpus programs Python
builds match; the other 3 fail in Python as well.
A type alias lowers as its base type and a unit as f64, as Python's
_resolve_type_alias resolves TypeAliasDecl and DistinctTypeDecl (UnitDecl)
in flow_type_to_mlir. Name-based checks (unsigned, struct lookup) still
see the alias name, as Python's do.

Accepted 968 of the corpus, 966 text-equal to Python at 84806b0, 0
text failures.
…nd GPU

Records what the emitter now covers, the Python behaviours it copies
(filed as #1059 to #1063), and the parity numbers per step against
Python at 84806b0. Updates the emitter and gate headers to match.
MLIR corpus rerecorded with --write-golden 84806b0 (1040 programs, 18
fixtures); the parse coverage floor rises to 2480.
@godofecht
godofecht merged commit f102d88 into main Sep 29, 2026
33 checks passed
@godofecht
godofecht deleted the selfhost/mlir-emit-3 branch October 1, 2026 12:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant