Skip to content

selfhost: flowc MLIR emitter for match, merges, defer, imports, statics and memref arrays - #1041

Merged
godofecht merged 7 commits into
mainfrom
selfhost/mlir-emit-2
Sep 29, 2026
Merged

godofecht merged 7 commits into
mainfrom
selfhost/mlir-emit-2

Conversation

@godofecht

Copy link
Copy Markdown
Contributor

Builds on #1020 (merged): the next slices of docs/design/mlir-in-flow.md, so FLOWC_EMIT=mlir and flow run --backend=mlir cover far more of the corpus with no Python.

What changes

  • Statement forms (compiler/src/mlirgen.flow): match (literal, negative literal, bool, string, _, binding, struct, enum variant, guarded or-patterns, default, with the llvm.unreachable join from mlir_match_termination.py), enums as the tagged struct Python synthesizes, defer (block exit, break, and return with its value computed first), address-of on locals, consts, statics, fields and elements, let with no annotation (Python's auto, lowered to memref<16xi8>) and let with no initializer.
  • SSA merges: a local outside an alloca is merged where control flow joins, as Python does it: scf.if yields, cf block arguments on if/elif/match joins, loop-carried block arguments on while and cf for, scf.for iter_args, and the carried values on break and continue.
  • Modules (compiler/src/mlir_bundle.flow, new): the declaration order of module_resolver.py (legacy string, relative and dotted imports, flow.toml [paths], the stdlib fallbacks, depth first with a module's imports before its own declarations). The expanded modules are joined in that order, typechecked dependencies first, and parsed once; imports, export a, b lists and an imported main are dropped. FLOWC_EMIT=mlir takes this path for any program with an import. The driver passes FLOWC_ROOT.
  • Module statics: top-level let mut scalars, strings, pointers, structs and fixed arrays as llvm.mlir.globals with LLVM-dialect initializers; accessors returning a static or its address are inlined (MLIR generator should inline trivial return-by-reference accessor functions at IR gen time #474).
  • Data, part of slice 4: uninitialized fixed arrays as memref.alloca, memref.load/memref.store, array<T> as memref<?xT> for parameters and results, memref-to-pointer decay, arrays of structs, array fields built inline in struct literals, and Python's linalg.generic for out[i] = a[i] op b[i] over pointers. Other single-store pointer loops now lower normally instead of being refused.
  • String + gets Python's placeholder comment. Programs with erased proof-layer nodes are refused (the typecheck erased them, so they were accepted by mistake after the merge), as are Tensor-shaped struct fields, Tensor arguments to struct-returning calls and the sprintf family, where Python does its own thing.
  • parity_mlir.sh: six new fixtures with goldens (match_enums, merges, defer_addr, imports_statics plus its module mlir_dep, data), corpus digests re-recorded from 84806b0d, and the Python reference gets the bootstrap C and this checkout's lib and packages, which its resolver and flow-block expansion need.
  • Bootstrap C regenerated last, in its own commit (fixed point).

Parity

Against the Python generator (its MLIR code is unchanged since eec7463f), every .flow under examples/, tests/, lib/, benchmarks/ and compiler/fixtures/, macOS, Homebrew LLVM 22. Slice numbers follow the design doc.

After Accepted Text equal to Python Run same Timing/address output Builds on neither path Run fail tests/lang
Slice 1 (#1020) 291 290 184 16 90 0 16 of 166
Slice 2 (statement forms) 364 364 225 16 123 0 23 of 168
Slice 3 (modules) 645 640 302 18 320 0 79 of 168
Part of slice 4 (data), final 794 794 356 21 417 0 81 of 168

The slice 3 commit had four text mismatches (a memref passed as a pointer, and the sprintf family); the next commit fixes them, and the final state has 0 text and 0 run failures. One more accepted program crashes the Python parser and is not counted. Most programs that build on neither path use let x = e, which Python types memref<16xi8>, or need the Flow runtime or a C header.

parity_mlir.sh golden mode: 13 of 13 fixtures (text and run), 781 corpus programs, with python and python3 stubbed out. flow run --backend=mlir on imports_statics.flow, match_enums.flow and defer_addr.flow builds and runs with Python stubbed out.

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 and corpus_parity.sh --check pass.
  • parity_mlir, parity_lowering, parity_effects, parity_proofs, parity_field_dsl, parity_dynamics_dsl, parity_flow_blocks pass. parity_shader_dsl passes except the Metal compile step: this Mac has xcrun but no Metal toolchain.

Found along the way

The emitter now reproduces these Python MLIR behaviours rather than fixing them; the doc lists them:

  • let x = e types x as memref<16xi8>, so arithmetic on it does not verify.
  • The elif conditions of a cf if read the then-arm's bindings, which fails dominance when the then-arm assigned the local.
  • A static initialized with -1 starts at 0.
  • The !llvm.array tag of a local is cached under its name for the rest of the module, so a later ptr of the same name in another function is indexed as that array.
  • linalg.generic goes through builtin.unrealized_conversion_cast, which mlir-translate cannot lower.

The Python host cannot build compiler/src/main.flow when any module uses getcwd (unistd.h clashes with the write extern in proof_doc.flow), so the bootstrap was regenerated through flowc, and mlir_bundle.flow reads PWD instead.

I could not add imports_statics.flow to the no-Python --backend=mlir CI step: a local hook blocks edits to workflow files. The golden gate in CI already covers it.

What is next

Slice 4's remaining parts (spans and slices, list patterns, array<T>(n), record update), string and cast-wrapped consts, then slice 5 (lambdas and closures). Leaving aside proof programs (855, which Python rejects too) and files flowc cannot parse (169), the largest refusals left are effects and capabilities (51), @gpu, mode-guard and C-interop attributes (47), imports that do not resolve the Python way (36), span and function types (27) and forward declarations (27).

…lized lets

Slice 2 of docs/design/mlir-in-flow.md. The emitter now lowers match
(literal, wildcard, binding, struct, enum variant and guarded or-pattern
arms, default), enums as the tagged structs Python synthesizes, defer
(including the return ordering), address-of on locals, consts, fields and
elements, lets without an annotation (Python's memref<16xi8> auto type)
and lets without an initializer. Locals held as SSA values are merged at
joins the way the Python generator does it: scf.if yields, cf block
arguments on if, match and loop exits, loop-carried block arguments and
scf.for iter_args, and carried values on break and continue.
Slice 3 of docs/design/mlir-in-flow.md. compiler/src/mlir_bundle.flow
walks the imports the way src/flow/module_resolver.py does (legacy string,
relative and dotted paths, flow.toml [paths], the stdlib fallbacks,
depth-first with each module's imports before its own declarations),
joins the expanded modules in that order, typechecks them dependencies
first and parses them once; the emitter drops imports, export lists and
an imported main, as the resolver does. FLOWC_EMIT=mlir takes this path
for any program with an import, and for FLOWC_BUNDLE=1; the driver
passes FLOWC_ROOT for the packages and stdlib fallbacks.

Also: top-level let mut statics (scalar, string, pointer, struct and
array globals with LLVM-dialect initializers), accessors that return a
static or its address, Python's placeholder for string +, the module-wide
!llvm.array tag cache by variable name, 1 KiB float text for huge
literals. Programs with erased proof-layer nodes, structs holding a
Tensor-shaped field, and Tensor arguments to struct-returning calls are
refused, since Python either rejects them or copies them its own way.
parity_mlir.sh gives the Python reference the bootstrap C and this
checkout's lib and packages.
Slice 4 of docs/design/mlir-in-flow.md, the parts that match Python today:
uninitialized fixed arrays as memref.alloca (spelled with the element's
own type name, as Python does), memref.load and memref.store with the
index_cast Python writes, unsized array<T> as memref<?xT> for parameters
and results, a memref decaying to a pointer, array fields of a struct
literal built inline with insertvalue, and the element type of a memref
local when Python reads it. The one-statement pointer loop
out[i] = a[i] op b[i] over 0 to N becomes Python's linalg.generic; every
other single-store pointer loop now lowers normally instead of being
refused. The sprintf, snprintf, fprintf and scanf externs, which Python
always turns into llvm.func varargs, are refused.
…data

Six new fixtures (match_enums, merges, defer_addr, imports_statics with
its module mlir_dep, and data) and the corpus digests, recorded from the
Python generator at 84806b0: 13 fixtures and 781 corpus programs. The
design doc records what slices 2 and 3 and part of slice 4 cover, the
Python behaviours the emitter copies rather than fixes, and the numbers
per slice.
getcwd pulled unistd.h into the C the Python host builds for flowc, where
proof_doc.flow's write extern clashes with it, and roundtrip.sh failed.
#1025 changed stdlib (ga_hash wraps as u32), which changed the MLIR of 35
corpus programs that import it. Rerecorded with --write-golden 84806b0:
789 programs.
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