Skip to content

LLBC: translate MIR without rustc's optimizations, so Aeneas accepts generic code - #5045

Open
feliperodri wants to merge 6 commits into
model-checking:mainfrom
feliperodri:llbc-pre-opt-mir
Open

feliperodri wants to merge 6 commits into
model-checking:mainfrom
feliperodri:llbc-pre-opt-mir

Conversation

@feliperodri

Copy link
Copy Markdown
Member

Kani's LLBC backend (-Zlean) exists to hand Rust to Charon's consumers, mainly Aeneas, which turns LLBC into a Lean model. Today Aeneas rejects the backend's output for even small generic code, so a proof that holds for every T can't go through Kani's front end. This PR makes it go through for a first example. It changes only the LLBC path: the CBMC backend's MIR and flags are untouched, since one backend runs per invocation.

Why it failed. The backend translated MIR after rustc's default optimizations, where moves become copies. In a generic push<T>(s: Slots<T>, x: T), the LLBC said Option::Some { _0: copy x }, which Aeneas's ownership model rejects for a T that isn't Copy. Calls and drops inside generic functions were also typed with the caller's monomorphized body, so inside both_none<T, U> the LLBC dropped an Option<i32>: a generic function pointing at its callees for one particular type (visible in the option test's diff).

What changes:

  • LLBC runs compile at -Zmir-opt-level=0 with -Zmir-preserve-ub, as Charon itself does. The backend then translates the constructs that MIR keeps at that level: runtime-check operands, borrow-checker-only statements, and () constants.
  • Function pointers for calls and drops are translated from the callee and its generic arguments, typed with the generic body, instead of requiring a monomorphic instance. A trait method called on a generic type still needs trait references, which the backend doesn't translate; it now reports that instead of crashing.
  • The first commit is two smaller fixes found on the way: the crate now records Charon's options (Aeneas rejected every Kani file for lacking --preset=aeneas), and place types come from the generic body being translated.

Verified. With the matching Aeneas release (the one pinned to Kani's Charon version), a generic container's new/push/pop now go through Aeneas, and the Lean proof of its type invariant for every T, written against upstream Charon's output, goes through unchanged on the model generated from Kani's output. The experiment, with a walkthrough: https://github.com/feliperodri/kani/tree/charon-type-invariant/experiments/charon-type-invariant. Locally: kani-llbc-regression.sh (24 tests, including the new generic_move, which fails without this change), fmt, cargo clippy --workspace --tests -- -D warnings and the --features llbc clippy, plus the CBMC kani suite (624 passed; only push_slow, which runs out of memory under my 6 GB CBMC cap).

Where to look:

  • 22 LLBC expected files change. I regenerated each one for the same functions it already checked; the differences are what the lower optimization level produces (explicit temporaries and moves, drop flags, _ => match arms), plus the generic drops above.
  • -Zmir-opt-level=0 keeps drop elaboration, so Lean models carry drop flags. Reading promoted MIR, as Charon does by default, would give cleaner models, but rustc has already discarded it by the end of analysis, so that needs a query override. I left it for a follow-up.
  • Not addressed here: trait method calls on generic types, and anything beyond this subset of generic code.

…generic body

Aeneas rejects a crate whose recorded options do not include
--preset=aeneas, and the crate recorded Charon's defaults. Record the
options Kani translates with.

Function bodies are translated from the generic MIR, but place,
rvalue and discriminant types were computed from the monomorphized
instance's body, and place types ignored projections. Inside a generic
function a tuple was typed with the instance's types, which Aeneas
rejects, and a match on a field behind a reference saw the reference
type. Compute them from the locals of the body being translated.
Aeneas, the main consumer of the LLBC backend's output, models ownership.
At rustc's default MIR optimization level, moves become copies (a generic
function's 'Option::Some { _0: copy x }' for 'x: T') and Aeneas fails on
the result. Compile LLBC runs the way Charon does, at -Zmir-opt-level=0
with -Zmir-preserve-ub; the CProver backend keeps rustc's defaults. Only
the LLBC backend's runs change: the backend is chosen per invocation.

MIR at that level keeps constructs that optimizations removed: runtime
check operands, borrow-checker statements (PlaceMention, FakeRead,
AscribeUserType) and zero-sized constants such as (). Translate them as
Charon does.

It also keeps calls and drops whose callee's arguments mention the
caller's generic parameters. Translate function pointers from the callee
and its generic arguments instead of requiring a monomorphic instance,
and type call operands with the generic body: they were typed with the
monomorphized instance's body, so inside a generic function a call or
drop pointed at the callee for one particular type. A trait method
called on a generic type still needs trait references, and now reports
that instead of crashing.

Also fix a regression from typing places with their projections: a
place's projections start from its local's type.

With this, a generic container's push/pop pass Aeneas, and a Lean proof
of its type invariant for every T goes through unchanged on the model
generated from Kani's output.
@feliperodri
feliperodri requested review from a team as code owners October 22, 2026 19:42
@github-actions github-actions Bot added Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Oct 22, 2026
@feliperodri
feliperodri requested a balanced review from Copilot October 22, 2026 20:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Dependency MIR settings and zero-sized struct constant translation leave correctness issues unresolved.

2 open issues
What changed in this PR

This PR updates Kani’s LLBC backend to preserve generic ownership semantics for Aeneas, while leaving CBMC compilation settings unchanged.

Changes:

  • Disable MIR optimizations for LLBC and translate constructs retained at that optimization level.
  • Use generic body types for places, calls, and drops, and record Charon options and runtime-check settings.
  • Add a generic-move regression and refresh LLBC expectations.
File Description
tests/​llbc/​unops/​expected Update unary-operation temporaries.
tests/​llbc/​tuple/​expected Include explicit unit return.
tests/​llbc/​traitimpl/​expected Include explicit unit return.
tests/​llbc/​switch_int/​expected Include explicit unit return.
tests/​llbc/​struct/​expected Preserve struct moves through temporaries.
tests/​llbc/​shifts/​expected Update shift-operation temporaries.
tests/​llbc/​regions/​expected Expand lifetime-related body expectations.
tests/​llbc/​projection/​expected Update projections, moves, and temporary lifetimes.
tests/​llbc/​option/​expected Expect generic drop types and explicit temporaries.
tests/​llbc/​int_literals/​expected Include explicit unit return.
tests/​llbc/​inherent_local/​expected Include explicit unit return.
tests/​llbc/​inherent_core/​expected Update inherent-call temporaries and declarations.
tests/​llbc/​impl_paths/​expected Expand generic method body expectations.
tests/​llbc/​generic/​expected Update match structure and arithmetic temporaries.
tests/​llbc/​generic_move/​test.rs Add generic ownership regression.
tests/​llbc/​generic_move/​expected Require generic moves and drop types.
tests/​llbc/​enum/​expected Preserve enum moves through temporaries.
tests/​llbc/​div_rem/​expected Update division and remainder temporaries.
tests/​llbc/​bool_char/​expected Update comparison temporaries.
tests/​llbc/​basic1/​expected Update conditional temporary handling.
tests/​llbc/​basic0/​expected Update comparison temporary handling.
tests/​llbc/​arith_wrapping/​expected Update wrapping-arithmetic temporaries.
tests/​llbc/​arith_unchecked/​expected Update unchecked-arithmetic temporaries.
tests/​llbc/​arith_checked/​expected Update checked-arithmetic temporaries.
kani-compiler/​src/​kani_compiler.rs Configure LLBC-specific MIR settings.
kani-compiler/​src/​codegen_aeneas_llbc/​mir_to_ullbc/​mod.rs Preserve generic types and translate retained MIR constructs.
kani-compiler/​src/​codegen_aeneas_llbc/​compiler_interface.rs Record Charon options and runtime-check settings.

Review effort: Balanced

Comment thread kani-compiler/src/kani_compiler.rs Resolved
--backend=llbc only reaches the local crate, so for cargo kani -Zlean the
dependencies kept rustc's default MIR optimizations. The backend
translates their bodies from their metadata, so a generic function in a
dependency still had its moves turned into copies. Pass -Zmir-opt-level=0
and -Zmir-preserve-ub to every crate of a Lean run. Add a cargo-kani LLBC
suite, run by kani-llbc-regression.sh, with a dependency's generic
function.
A zero-sized struct can have fields (struct Z { unit: () }), and the
aggregate constant for it had none, which is ill-typed. Build the value
of a zero-sized tuple or struct from a zero-sized constant for each
field, and keep reporting other zero-sized types as not supported.
Comment on lines 1613 to 1614
let place_ty = place.ty(&self.body_locals).unwrap();
let drop_glue = Instance::resolve_drop_in_place(place_ty);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing drops from the generic body crashes when the dropped place is a bare type parameter: resolve_drop_in_place can't build drop glue for T, so fn first<T>(a: T, _b: T) -> T { a }, called from a harness with -Zlean, now hits internal compiler error: failed to resolve instance for std::ptr::drop_glue::<T>. The merge-base compiled it, though with the wrong drop_glue<'_, NC> type. The new tests only drop Slot<T> and Option<T>, which still resolve. Could you build the drop pointer from the drop_glue lang item and the generic [place_ty], the way generic calls are handled, and add a test that drops a T?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in a6648cf: a drop of a type that mentions a type parameter now points at the generic drop_glue::<T> declaration with [place_ty], as generic calls do. Concrete types still use resolve_drop_in_place, so the existing outputs don't change. tests/llbc/generic_drop drops a bare T and hits the ICE without the fix.

`resolve_drop_in_place` can't build drop glue for a type that mentions the
caller's type parameters, such as a bare `T`, so dropping one in a generic
function caused an internal compiler error. Point such drops at the generic
`core::ptr::drop_glue::<T>` declaration instead, as generic calls do.
Concrete types still use `resolve_drop_in_place`, so existing outputs don't
change. `tests/llbc/generic_drop` drops a bare `T`.

Signed-off-by: Felipe R. Monteiro <felisous@amazon.com>
The expected output joined the `wrapping_add` declaration and
`pub opaque type ()` into one block, so it only matched when the printer
emitted them in that order. nightly-2026-10-23, which main uses, prints
`()` first. Make them two blocks so that either order matches.

Signed-off-by: Felipe R. Monteiro <felisous@amazon.com>
acearyanarun pushed a commit to acearyanarun/kani that referenced this pull request Nov 17, 2026
The automatic toolchain upgrade has been stuck since nightly-2026-10-24
(model-checking#5061). This brings the toolchain to nightly-2026-11-11, in four
commits:

1. **nightly-2026-10-24.** rust-lang/rust#164744 removed
`Attribute::span`, `get_normal_item` and `TyCtxt::get_attrs_by_path`;
Kani's `kanitool::*` attributes are unparsed tool attributes, so
`attrs_by_path` and `attr_span` read them directly.
rust-lang/rust#162395 made `ceil`, `floor`, `trunc`, `round`,
`round_ties_even`, `sqrt`, `powf`, `powi` and `fma` generic, with
fallback bodies; the one for `powi` calls `__powisf2`/`__powidf2`, which
CBMC does not model, so Kani keeps its CBMC models for f32 and f64
(`uses_kani_model`, shared by codegen and reachability).
2. **nightly-2026-11-11.** Tool attributes are now `Attribute::Tool` and
lost `meta_item_list`/`is_word`; `AbiAlign` and `GenericArgsRef` were
removed; `rustc_abi::Float::X87F80` is reported as unsupported, like
`f16b`; and a new clippy lint. Two less obvious ones:
- Cargo now reports only the hashed rlib of each Kani library
(`libstd-<hash>.rlib`), while the driver links `libstd.rlib` by name, so
every test failed to find `std`. `build-kani` renames Kani's rlibs to
`lib<crate>.rlib` in the sysroot (renamed, not copied, so rustc never
sees two candidates).
- Calling a closure through a function pointer argument can now take a
pointer to a capture-free closure, which the uninit checker rejected as
unsupported (`uninit/delayed-ub` lost its expected failure). Zero-sized
closures and function items have no bytes to track.
3. **A model of the `derive(Debug)` helpers.** rust-lang/rust#164726
made `derive(Debug)` pass all names as one space-separated string, which
`Formatter::debug_struct_fields_finish` and
`Formatter::debug_c_like_enum_write_str` split with `memchr`. Its
word-at-a-time loop depends on pointer alignment, and verifying any
derived `Debug` became orders of magnitude slower:

   | Nightly | rust-lang/rust#164726 | `cargo-kani/iss2857` |
   |---|---|---|
   | 2026-10-24 | no | 46s |
   | 2026-10-29 | no | 44s |
   | 2026-10-30 | yes | > 15 min (stopped) |
   | 2026-11-11 | yes | > 58 min, 9 GB (stopped) |
   | 2026-11-11, this PR | yes | 53s |

Kani now replaces those two helpers (the
`debug_struct_field{1..5}_finish` helpers forward to the first) with
models that split the same string with a byte loop and format through
the same public builders. `docs/src/soundness.md` lists them as
assumptions.

4. **LLBC: zero-sized constants.** MIR now assigns `()` to the return
place after the last call of a unit function (`_0 = ()`) as a zero-sized
constant, which the LLBC backend did not translate (`todo!()`). It now
builds zero-sized tuples and structs field by field, as in model-checking#5045; each
LLBC expected output gains that one line.

### Testing

- `kani-regression.sh` passes on nightly-2026-11-11 (run in a container
with CBMC 6.11.0), apart from `script-based-pre/compiler_defaults`
(needs `jq`) and `script-based-pre/cbmc_truncated_results` (depends on
the memory limit), which fail only in that container.
`kani-llbc-regression.sh` passes (the LLBC build and clippy with `-D
warnings`, 20 expected tests and the cargo suite), and `kani-fmt.sh
--check` and workspace clippy pass.
- `library/kani/src/fmt_model_tests.rs` compares the models with the
real `derive(Debug)` output natively (named, tuple and unit structs,
more than five fields, nesting, `{:#?}`, widths, C-like enums with raw
and non-ASCII names). Checking exact formatter output inside Kani takes
over nine minutes per harness, with or without the models, so this is a
native test; `tests/kani/FmtDerive` checks that Kani verifies formatting
of each shape through the models (84s).
- `cargo-kani/iss2857` is the performance regression test.

Resolves model-checking#5061

By submitting this pull request, I confirm that my contribution is made
under the terms of the Apache 2.0 and MIT licenses.

---------

Signed-off-by: Felipe R. Monteiro <felisous@amazon.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Z-CompilerBenchCI Tag a PR to run benchmark CI Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants