Skip to content

selfhost: finish the MLIR port and delete src/flow - #1072

Merged
godofecht merged 8 commits into
mainfrom
selfhost/mlir-finish
Sep 30, 2026
Merged

godofecht merged 8 commits into
mainfrom
selfhost/mlir-finish

Conversation

@godofecht

Copy link
Copy Markdown
Contributor

Finishes the MLIR port and deletes the Python compiler. src/flow is gone.

Builds on #1070 (slices 4 to 6) and includes #1064 (remaining Python commands). Design record: docs/design/mlir-in-flow.md.

Emitter coverage

Against the Python generator at bb23f19f, run --lenient over every .flow file in the repository:

Mode Python emits MLIR flowc text-equal after normalization
64-bit 1270 1270
--mlir-gpu (programs with @gpu) 14 14
--wasm32 (32-bit size_t) 1270 1270

flowc also lowers 3 programs Python failed on. parity_mlir.sh keeps this as goldens (21 fixtures with text and run output, GPU and wasm32 fixtures, 1252 corpus digests) and still compares live against any Python revision with --python <rev>.

Added to mlirgen.flow: generic monomorphization, fork/choose, range sums, test blocks, string interpolation, vectors, tensors (struct fields, arguments, tensor_add, tensor_matmul), AoSoA, while true rotation, dual numbers through operator structs, unsized arrays (#1069), 128-bit and wide literals, parallel for as scf.parallel, and the wasm32 ABI (FLOWC_MLIR_SIZE_T=32). FLOWC_LENIENT=1 matches Python's --lenient.

Commands without Python

tests/mlir_commands/run.sh checks 72 cases against goldens recorded from the Python stack at bb23f19f, with python and python3 stubbed to exit 127: flow mlir (with --optimize pipelines), mlir-run, jit, ml, test-mlir, test-matmul, compile-audio --mlir, --mlir-gpu, --emit-spirv, and --print-pass-pipeline. The optimizer pipelines, lowering and SPIR-V are compiler/scripts/mlir_optimize.sh, mlir_lower.sh and mlir_spirv.sh. The JIT is emit, lower, link and run. flow_to_mlir.sh has no Python fallback. The GPU and Metal runtimes stay C and Objective-C.

Deleted

  • src/flow: parser, type checker, monomorphizer, module resolver, transpiler, JIT runner, the mlir_* modules and the DSL modules (30 files on this branch).
  • 111 pytest files that imported it, tests/fuzz Python harness, pyproject.toml (its pytest settings are in pytest.ini).
  • Across the branch, tracked Python goes from 278 files to 64 and from about 67,000 lines to 6,930. python_ratchet baseline updated.

The canonical version moved from src/flow/version.py to VERSION. doc_coverage reads keywords, attributes and backends from the Flow sources.

Replacements for the deleted tests

  • tests/fuzz/run.sh: crash pins, generated nesting 20000 deep, seeded mutation of the corpus through flowc. It found a stack overflow on deep nesting; FLOWC_PARSE_MAX_DEPTH in parser.flow makes that a parse error.
  • tests/conformance/run.sh: the Stable corpus through flowc.
  • tests/cgen/tc_reject_*: arity, unbound call, void return.

Open

The Python type checker had diagnostics flowc lacks. flowc accepts these programs, and every C build has since #1027. They are listed in docs/design/mlir-in-flow.md#what-the-deletion-left-open. Visible effects:

  • tests/conformance/run.sh fails on Stable negatives 01 and 02.
  • 9 expect-error doc examples compile; they sit in the doc-example ledger.

Gates

Run on macOS with python and python3 stubbed to exit 127 (none was called):

  • pass: bootstrap_from_c.sh --verify, self_host_full.sh, roundtrip.sh, parse_coverage.sh --check, fmt_check.sh --check, tests/cgen/run.sh, ./flow test-lang, corpus_parity.sh --check, check_run_without_python.sh
  • pass: parity_mlir.sh, parity_dap, parity_dynamics_dsl, parity_effects, parity_field_dsl, parity_flow_blocks, parity_lowering, parity_project_test, parity_proofs, parity_targets
  • pass: tests/mlir_commands/run.sh (72/72), tests/fuzz/run.sh, the tool gates (check, c_to_hdr, tools, fir, pywheel, gpu, gpu crossing, flow_run, pkg commands), doc links, doc coverage, doc examples ledger, sync_version, python_ratchet
  • parity_shader_dsl.sh: only the Metal step fails (no Metal toolchain on this machine)
  • tests/conformance/run.sh: 9 pass, negatives 01 and 02 fail (see Open)
  • pytest tests/ -m "not slow" on the 17 remaining files: 103 passed, 5 skipped

Bootstrap C regenerated in its own commit; bootstrap_from_c.sh --verify passes.

Rebuilt on main from selfhost/mlir-finish (#1072) after #1071. The
scripts/tools programs follow the strict type check, and the tc_reject
cgen goldens expect the ported checker's diagnostics. The design note on
what the deletion left open now lists the three checks flowc --strict
still accepts. The bootstrap C is regenerated in the next commit.
The MLIR command goldens were recorded with LLVM 22.1.7. Ubuntu's LLVM 18
writes different IR and fails the bufferization pipeline, and clang 18
cannot read the IR 22 emits. The action now installs LLVM 22 with
llvm.sh plus mlir-22-tools and libmlir-22-dev, and puts
/usr/lib/llvm-22/bin first on PATH for the rest of the job.
llvm.sh also installs lldb-22, whose python3-lldb-22 dependency does not
resolve on the runner. Install only clang-22, llvm-22, mlir-22-tools and
libmlir-22-dev.
Ubuntu's clang links PIE by default, and llc wrote a non-PIC object from
the MLIR path, so every flow mlir-run, jit, ml and audio link failed on
Linux (R_X86_64_32 against .rodata). llc now uses -relocation-model=pic,
which is macOS's default already. lld-22 provides wasm-ld for the
wasm32 target.
…es, mask host assembly

src/ is deleted, so the lint job loses Ruff and Mypy (and setup-python)
and security loses Bandit; pip-audit stays. flowc-parity-gates runs
parity_typecheck.sh --check and typecheck_rules.sh. test-matmul prints
the host's assembly, which differs between macOS arm64 and Linux x86_64,
so the golden keeps the Assembly line and masks the listing. A failed
MLIR or audio link now prints the compiler's error.
GNU ld takes symbols from an archive only for references it has already
seen, and audio_miniaudio.c calls the SPSC ring in lib/runtime/audio_spsc.flow.
With the archive first, every compile-audio link failed on Linux. The macOS
linker does not depend on the order.
lib/stdlib/audio/gpu.flow calls flow_audio_metal_available and the gain
and convolution entry points. audio_gpu_metal.m defines C stubs for them
outside __APPLE__, but the driver added the file only on Darwin, so
compile-audio of a GPU program failed to link on Linux.
@godofecht
godofecht merged commit 3bea8c4 into main Sep 30, 2026
34 checks passed
godofecht added a commit that referenced this pull request Sep 30, 2026
Rebuilt on main from port/last-python (#1076) after #1072. The new
scripts/tools programs pass the strict type check; record_demos keeps
its cached root in a ptr<u8> static, since module statics cannot be
strings.
godofecht added a commit that referenced this pull request Oct 1, 2026
…1093)

* test: mlir_vs_c.sh, the MLIR backend against the C backend

Builds every tracked program with a main through `flow compile` and
`flow compile --backend=mlir`, runs both with a timeout, and compares exit
code and stdout. The C backend is the reference; programs it does not
build are counted apart. Failures are clustered by their first diagnostic.
Builds have a timeout too (--build-timeout, default 300 s): one example
used to emit 100 MB of MLIR that llc never finished.

The floor is the emitter as #1072 left it: 629 of the 1130 programs the C
backend builds run the same through MLIR (1465 programs with main).

* fix: MLIR emitter bugs copied from the Python generator

The emitter no longer copies the retired Python generator's bugs for text
parity. The contract is now MLIR that verifies and runs with the C
backend's output (compiler/scripts/mlir_vs_c.sh).

Issues:
- #1059: a forward declaration emits nothing beside its definition, and a
  declared-only function is a `func.func private` declaration. Overloads
  get the C backend's mangled symbols (name_T1_T2) and calls pick the
  overload the argument types fit.
- #1060: len() of a span reads its length field; len() of a fixed array,
  a dynamic array and a string is lowered too. A span parameter with an
  extent is the {ptr, len} struct its body reads.
- #1061: in @gpu kernels, -x is 0 - x with a materialized zero, !x flips a
  bool or tests an integer against zero, and elif is a nested scf.if.
- #1062: lambdas capture only the enclosing function's locals; consts,
  statics, functions and builtins (println included) resolve by name.
  Slices and elif conditions are searched for captures. `let f = |x| ...`
  gets the lambda's function type, so calls through it are typed.
- #1063: consts whose value is not a literal (float expressions, other
  consts, struct literals) are evaluated at each use instead of being
  zero. A record update names its struct. An unknown type name or a
  capability-typed value is refused instead of becoming memref<16xi8>.

Behaviour the C backend defines and the emitter now follows:
- println/print: %s for strings, %lld/%llu for 64-bit, %u for u32, %f
  for floats, space-separated arguments; string literals holding `%`.
- Integer literals above the i32 range are i64 (u64 above i64); float
  literals are f64, written so MLIR reads them (1e9 no longer fails).
- A bool widens with extui. Branch conditions of any scalar type test
  != 0. A returned value is cast to the return type.
- String `+` (numbers and bools formatted as C does), string `==` by
  content, string match patterns, pointer arithmetic scaled by the
  pointee.
- Nested and literal fields of struct patterns are checked, not ignored;
  a match falls through to llvm.unreachable only when every arm returns.
- `a * b + c` is one math.fma, as clang contracts it, so floating point
  results agree to the last bit.
- Runtime checks under FLOWC_CHECKS=1 (flow_to_mlir.sh default): integer
  division by zero, shift range, and reads of sized arrays and spans
  abort with `flow: <what>`, as the C backend's do.
- defer runs on break and continue out of nested blocks; elif conditions
  see the locals as before the if; statics fold negative and constant
  initializers; `[v; N]` takes any constant N and fills with a loop;
  short array literals zero the rest; arrays over 64 KiB use the heap.
- libc and <math.h> calls without a declaration are declared with their
  C signatures; a Flow function named like one (sin in math.flow) yields
  to libc as the C backend's header does. Other undeclared callees are
  declared as C would implicitly.
- @cInclude/@cImport are accepted; @cembed C is written beside the MLIR
  (FLOWC_CEMBED_OUT) and linked by `flow compile --backend=mlir`.
- C string escapes (octal, hex, \e) are decoded into MLIR strings.
- Removed: Python's string interpolation (the C backend prints the
  literal), the module-wide array-name cache, the arguments evaluated last
  to first for struct-returning callees.

parity_mlir.sh gains --record (goldens from flowc) and links with the
clang next to mlir-translate. Goldens re-recorded: every fixture's text
changes with the string escapes and literals; run output changes are the
fixes above (consts_calls: 64-bit literal; defer_addr: defer on break;
imports_statics and print_logic: string println; spans_data: a folded
float const). New fixture gpu_ops covers #1061.

* fix: MLIR intrinsics and pointer loops the C backend handles

- sizeof<T>() (monomorphized to sizeof_T) is the size of T as i64, from
  the offset of element 1 of a T array at null.
- flow_panic(msg), the trap a flow invariant lowers to, writes the message
  to stderr and exits 1; i32_to_f32, declared or not, is a conversion.
- `str` is the string type, as in the C backend.
- A lambda capturing a loop index stores it as i64 (index has no LLVM
  storage type).
- The linalg.generic rewrite of `out[i] = a[i] op b[i]` over pointers is
  gone: its unrealized casts from !llvm.ptr to memref never lowered. The
  loop lowers as any other.

corpus.txt re-recorded: 17 programs change text (the pointer loops and
the new lowerings), one more is accepted.

* fix: fused multiply-add as llvm.intr.fma; re-record MLIR command goldens

math.fma needs the math-to-llvm conversion, which the pass pipelines of
`flow jit`, `ml` and the optimizer do not all run; llvm.intr.fma lowers in
every pipeline. The parity_mlir fixture text changes accordingly.

tests/mlir_commands goldens re-recorded from flowc for the cases the
emitter fixes changed: the MLIR, LLVM IR and optimizer text of the
fixtures, jit_spans (its folded float const now prints 3.000000) and
audio_offline (the last digit now matches the C build: R=0.116318).

* fix: MLIR arrays returned by value, array ctor zeroing, expect, NaN compares

- An array returned by value is copied to the heap (memref.copy into a
  memref.alloc), since the callee's storage is an alloca; a sized array
  local held as an !llvm.array is copied with memcpy into the heap memref
  of the return type.
- Assigning to a sized array local copies into its storage (memcpy), as a
  C array assignment does, instead of rebinding the name.
- array<T>(n) zeroes its elements, as the C backend's calloc.
- `expect c` writes `expect failed (line N)` to stderr and exits 1 when c
  is false; it was evaluated and ignored.
- Float `!=`, and the truth test of a float, are unordered (une): NaN != NaN
  holds, as in C.
- i128 operands combine as i128 (they were narrowed to i64).
- A float literal fits an f32 overload as well as an f64 one.

corpus.txt and spans_data.mlir re-recorded (spans_data builds arrays with
array<f32>(8), which now zero-fills).

* fix: MLIR ui layout blocks, uninitialized array locals

- A `ui_row(args) { body }` layout block calls ui_row_begin and ui_row_end
  around its body, with the implicit `_ui_state` (a module global, null at
  start) or the pointer or array its first argument names, as the C
  backend lowers it. ui_layout_bind(p) sets `_ui_state`. The body alone
  used to be emitted.
- `let buf: array<u8, N>` with no initializer is a memref of the array
  type. It was spelled memref<Nxu8>, which is no MLIR type.

data.mlir and corpus.txt re-recorded for the uninitialized array.

* fix: MLIR array literals longer than their array

An array literal with more elements than the declared length stored the
extra elements past the end of the alloca, over neighbouring locals. C
drops excess initializers; the emitter now stores only the declared
length. compiler/src/mono_usage.flow has 198-element literals for
array<u8, 192>, which broke every tests/lang *_port test that imports it.

corpus.txt re-recorded: 15 programs import such literals.

* fix: MLIR allocator stubs, fields through returned pointers, arrays and functions as values

- A program's own allocator stub (`malloc(size: i32) -> i32`, a `free`
  returning a value) is its own function under __flowc_libc_<name>, as the
  C backend decides; calls no longer reach libc's malloc and free with
  its arguments. Closure environments always use libc's malloc.
- A field read on a struct pointer a call or a cast returns reads through
  the pointer (#1065 in the C backend).
- A sized array held as an !llvm.array passed to a memref parameter is
  copied into a memref before the call and back after it, so the callee
  sees and changes the caller's elements.
- A function returned from, or bound to a local of, a function type is its
  closure adapter.

corpus.txt re-recorded: 6 more programs are accepted, 6 change text.

* fix: MLIR sort and find, Dual and Tensor operators, proofs, loop bounds

The next group of causes from the MLIR-vs-C gate:

- `xs |> sort ...` and `xs |> find(t)` lower to a stable merge sort and a
  linear search with the C backend's three-way compare (strcmp, IEEE
  totalOrder, signed or unsigned order), keys, descending and unique.
- `+ - * /` and unary minus on Dual, and the Tensor operators, call the
  overloads the C backend calls. The tensor_add intrinsic applies only
  when the program does not define tensor_add. An f64 argument now
  prefers an f32 overload over a struct one.
- The proof layer is erased as for C; proof-only files emit an empty
  module, so 853 examples/verify and lib/verify files join the corpus.
- @max_iterations(N) counts iterations and aborts past the bound.
- `v in arr` over a sized array, pointer difference in elements, and a
  value function whose end is reachable returns zero.
- A field read through a mutable pointer local uses its current value
  (the tools and driver mains failed dominance).
- Rows of a nested array literal are heap copies, so returned nested
  arrays keep their values.
- Any expression statement is evaluated.

Goldens: corpus.txt digests change for the programs above and gain the
newly accepted ones. mlir_data, mlir_spans_data and llvm_spans_data are
re-recorded; their text trailed the earlier array<T>(n) zero-fill change.

* fix: MLIR multiply-add as llvm.intr.fmuladd, unsigned conversions

- A contracted a * b + c is llvm.intr.fmuladd, the intrinsic clang emits
  for the C build. LLVM then fuses or splits it the same way for both
  builds: the loop vectorizer splits it in an in-order reduction, which
  llvm.intr.fma forbade (psychstats lognormal sigma and mna_dc differed
  in the last bit).
- An unsigned integer converts to float with uitofp, and a float cast to
  an unsigned type with fptoui, as in C.
- The string table holds 16384 constants in a 1 MiB pool, so the
  compiler's own main.flow builds through MLIR.

Goldens: every fixture and command golden with a multiply-add changes
llvm.intr.fma to llvm.intr.fmuladd (arith, arrays, closures, spans_data,
structs; the mlir_, llvm_ and opt_ commands). corpus.txt digests change
for the programs that hold one.

* docs: MLIR against the C backend, fixed quirks and remaining gaps

The design page records the new contract, the gate's numbers before and
after (629 to 1002 of 1131 programs run the same), what changed, and
what the gate still reports. The copied Python quirks it listed are
removed or marked fixed.

* test: re-record MLIR corpus digests after rebasing onto main

Nine programs that main changed since the branch point (the gif encoder,
python embedding, parser forms, prefix deref) emit different MLIR.

* fix: regenerate bootstrap C after the MLIR emitter fixes

* test: record the MLIR-vs-C report and floor

On the branch rebased onto main, 1018 of the 1156 programs the C backend
builds run the same through MLIR (629 of 1130 at #1072). The floor for
Darwin is 1013, 5 under the run. The design page's table takes these
numbers.
@godofecht
godofecht deleted the selfhost/mlir-finish 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