From 656f228010204c342b349576a5e49f295c28cae9 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:03:19 -0800 Subject: [PATCH 1/2] Report explicit tail calls as unsupported instead of panicking The diff checks internal MIR before body conversion during transformation, proof metadata generation, and autoharness processing, including instantiation search. It reports each explicit tail call in the body at its source span and aborts with an unsupported-feature diagnostic. It adds a diagnostic regression test and a verification case where the harness never calls the function containing `become`. It also documents explicit tail calls as unsupported. Fixes #5131 --- docs/src/rust-feature-support/unstable.md | 1 + .../src/kani_middle/codegen_units.rs | 6 +++ kani-compiler/src/kani_middle/metadata.rs | 7 +++- kani-compiler/src/kani_middle/mod.rs | 40 +++++++++++++++++++ .../src/kani_middle/transform/mod.rs | 2 + tests/kani/TailCall/unreachable.rs | 23 +++++++++++ tests/ui/explicit-tail-calls/expected | 1 + tests/ui/explicit-tail-calls/main.rs | 22 ++++++++++ 8 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 tests/kani/TailCall/unreachable.rs create mode 100644 tests/ui/explicit-tail-calls/expected create mode 100644 tests/ui/explicit-tail-calls/main.rs diff --git a/docs/src/rust-feature-support/unstable.md b/docs/src/rust-feature-support/unstable.md index 8330eae49814..aa09428b941d 100644 --- a/docs/src/rust-feature-support/unstable.md +++ b/docs/src/rust-feature-support/unstable.md @@ -7,3 +7,4 @@ The following are examples of unstable features that are not supported in Kani: * Generators * C-variadics + * Explicit tail calls (`become` / `explicit_tail_calls`) diff --git a/kani-compiler/src/kani_middle/codegen_units.rs b/kani-compiler/src/kani_middle/codegen_units.rs index c609bd80d63b..04d982bcc0cf 100644 --- a/kani-compiler/src/kani_middle/codegen_units.rs +++ b/kani-compiler/src/kani_middle/codegen_units.rs @@ -916,6 +916,9 @@ fn resolve_deferred_fn_slots<'tcx>( /// it, which fails that harness instead of the run; see /// . fn invalid_simd_instantiation(tcx: TyCtxt, instance: Instance) -> Option { + // Instantiation search loads this body before `automatic_harness_partition`'s eligibility + // check. A `become` panics in `rustc_public`'s MIR conversion, so reject it here too. + crate::kani_middle::reject_explicit_tail_calls(tcx, instance); let body = instance.body()?; body.blocks.iter().find_map(|block| { let TerminatorKind::Call { func, .. } = &block.terminator.kind else { @@ -1219,6 +1222,9 @@ fn automatic_harness_partition( "{crate_name}::{}", crate::kani_middle::strip_local_crate_prefix(instance.name()) ); + // Autoharness loads every local body directly. A `become` panics in `rustc_public`'s MIR + // conversion; reject it before that load. + crate::kani_middle::reject_explicit_tail_calls(tcx, instance); let body = instance.body().unwrap(); if is_proof_harness(tcx, instance) diff --git a/kani-compiler/src/kani_middle/metadata.rs b/kani-compiler/src/kani_middle/metadata.rs index 144a85d341d4..78ec049b603f 100644 --- a/kani-compiler/src/kani_middle/metadata.rs +++ b/kani-compiler/src/kani_middle/metadata.rs @@ -7,7 +7,10 @@ use std::collections::HashMap; use std::path::Path; use crate::kani_middle::codegen_units::Harness; -use crate::kani_middle::{KaniAttributes, SourceLocation, readable_name, strip_local_crate_prefix}; +use crate::kani_middle::{ + KaniAttributes, SourceLocation, readable_name, reject_explicit_tail_calls, + strip_local_crate_prefix, +}; use kani_metadata::ContractedFunction; use kani_metadata::{ArtifactType, HarnessAttributes, HarnessKind, HarnessMetadata}; use rustc_middle::ty::TyCtxt; @@ -25,6 +28,8 @@ pub fn gen_proof_metadata(tcx: TyCtxt, instance: Instance, base_name: &Path) -> // We get the body span to include the entire function definition. // This is required for concrete playback to properly position the generated test. + // A `become` in the harness panics in `rustc_public`'s MIR conversion; reject it first. + reject_explicit_tail_calls(tcx, instance); let loc = SourceLocation::new(instance.body().unwrap().span); let file_stem = format!("{}_{mangled_name}", base_name.file_stem().unwrap().to_str().unwrap()); let model_file = base_name.with_file_name(file_stem).with_extension(ArtifactType::SymTabGoto); diff --git a/kani-compiler/src/kani_middle/mod.rs b/kani-compiler/src/kani_middle/mod.rs index a47846064220..57a7458470d6 100644 --- a/kani-compiler/src/kani_middle/mod.rs +++ b/kani-compiler/src/kani_middle/mod.rs @@ -128,6 +128,46 @@ pub fn check_crate_items(tcx: TyCtxt, ignore_asm: bool) { tcx.dcx().abort_if_errors(); } +/// Reject explicit tail calls (`become`) before `rustc_public` converts the body. +/// +/// Stable `rustc_public::mir::TerminatorKind` has no `TailCall` variant, so converting a body that +/// contains one hits `unimplemented!()` inside the toolchain and aborts the compilation, c.f. +/// . The feature is incomplete; report every +/// such terminator and abort once. Leave the call unmodeled: an ordinary `Call` would keep the +/// caller's frame live, which disagrees with `become`. +/// +/// The check reads the *internal* body — `tcx.instance_mir` on the instance's `def`, the same body +/// `rustc_public_bridge`'s `BodyBuilder` converts — because that conversion is what panics. +/// Callers invoke this immediately before `instance.body()`. +pub fn reject_explicit_tail_calls(tcx: TyCtxt, instance: Instance) { + if !instance.has_body() { + return; + } + // `BodyBuilder` loads an intrinsic's fallback body as the item. `instance_mir` rejects + // `InstanceKind::Intrinsic`. + use rustc_middle::ty::InstanceKind; + let internal_instance = rustc_internal::internal(tcx, instance); + let def = match internal_instance.def { + InstanceKind::Intrinsic(def_id) => InstanceKind::Item(def_id), + InstanceKind::Item(def_id) => InstanceKind::Item(def_id), + InstanceKind::LlvmIntrinsic(def_id) => InstanceKind::LlvmIntrinsic(def_id), + InstanceKind::Shim(kind) => InstanceKind::Shim(kind), + InstanceKind::Virtual(def_id, idx) => InstanceKind::Virtual(def_id, idx), + }; + let body = tcx.instance_mir(def); + for bb in body.basic_blocks.iter() { + let rustc_middle::mir::TerminatorKind::TailCall { fn_span, .. } = &bb.terminator().kind + else { + continue; + }; + tcx.dcx() + .struct_span_err(*fn_span, "explicit tail calls (`become`) are not supported by Kani") + .with_note("see https://github.com/model-checking/kani/issues/5131") + .emit(); + } + tcx.dcx().abort_if_errors(); +} + /// Whether `instance` is a C-variadic function whose calling convention is not the C one, e.g. /// `unsafe extern "sysv64" fn(_: ...)`. /// diff --git a/kani-compiler/src/kani_middle/transform/mod.rs b/kani-compiler/src/kani_middle/transform/mod.rs index d86ae417a7e5..c66f6aa7ce14 100644 --- a/kani-compiler/src/kani_middle/transform/mod.rs +++ b/kani-compiler/src/kani_middle/transform/mod.rs @@ -154,6 +154,8 @@ impl BodyTransformation { .cache .entry(instance) .or_insert_with(|| { + // `become` panics in `rustc_public`'s MIR conversion; reject it before loading. + crate::kani_middle::reject_explicit_tail_calls(tcx, instance); // Transform and add to the cache if there's no existing entry. let mut body = instance.body().unwrap_or_else(|| build_missing_body(tcx, instance)); diff --git a/tests/kani/TailCall/unreachable.rs b/tests/kani/TailCall/unreachable.rs new file mode 100644 index 000000000000..f139dbaff252 --- /dev/null +++ b/tests/kani/TailCall/unreachable.rs @@ -0,0 +1,23 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A `become` in a function the harness never calls does not affect verification. +//! + +#![feature(explicit_tail_calls)] +#![allow(incomplete_features)] + +#[allow(dead_code)] +fn g(x: u32) -> u32 { + x + 1 +} + +#[allow(dead_code)] +fn f(x: u32) -> u32 { + become g(x) +} + +#[kani::proof] +fn unreachable_tail_call() { + assert_eq!(1 + 1, 2); +} diff --git a/tests/ui/explicit-tail-calls/expected b/tests/ui/explicit-tail-calls/expected new file mode 100644 index 000000000000..23ab756f885f --- /dev/null +++ b/tests/ui/explicit-tail-calls/expected @@ -0,0 +1 @@ +error: explicit tail calls (`become`) are not supported by Kani diff --git a/tests/ui/explicit-tail-calls/main.rs b/tests/ui/explicit-tail-calls/main.rs new file mode 100644 index 000000000000..5851b50ec1d2 --- /dev/null +++ b/tests/ui/explicit-tail-calls/main.rs @@ -0,0 +1,22 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Explicit tail calls (`become`) are an incomplete unstable feature. Kani reports them as +//! unsupported instead of panicking inside `rustc_public`. +//! + +#![feature(explicit_tail_calls)] +#![allow(incomplete_features)] + +fn g(x: u32) -> u32 { + x + 1 +} + +fn f(x: u32) -> u32 { + become g(x) +} + +#[kani::proof] +fn tail_call() { + assert_eq!(f(1), 2); +} From fa462b8e16f395884545a4f5a10c91e3236843f5 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:55:16 -0800 Subject: [PATCH 2/2] Route body loads through a tail-call-aware helper; skip `become` in autoharness Address review on #5152: rather than calling a guard before each `instance.body()`, add helpers in `kani_middle` that check the internal MIR for `TerminatorKind::TailCall` and then convert: - `checked_body` / `checked_fn_def_body` report the unsupported diagnostic and abort. Used by `body_ref`, harness metadata, stub validation (`check_compatibility`), the stub body in `FnStubPass`, the autoharness transform, delayed-UB / points-to analysis and mutual-recursion checks. - `has_explicit_tail_call` / `body_without_tail_calls` report nothing. Used where an unsupported body should just be ignored: autoharness eligibility, instantiation search, constructor inlining, invariant mining (`--constructor-args` / `--check-invariants`) and the diagnostic-only `kani::any` cycle check. `ExternFnStubPass` now asks `FnDef::has_body` instead of converting the body just to test for one. Autoharness no longer aborts the run when one function uses `become`: it is skipped with the new `AutoHarnessSkipReason::UnsupportedTailCall` ("Explicit tail calls are not supported"), and the other functions are still verified. Tests: stubbing regressions with `become` in the original and in the replacement (both panicked in `rustc_public` before), and an autoharness run where `tail_call` is skipped and `ok_fn` is verified (the whole run aborted before). --- .../src/reference/experimental/autoharness.md | 1 + .../src/kani_middle/codegen_units.rs | 19 ++-- kani-compiler/src/kani_middle/metadata.rs | 9 +- .../src/kani_middle/mined_invariants.rs | 39 ++++---- kani-compiler/src/kani_middle/mod.rs | 92 +++++++++++++++---- .../points_to/points_to_analysis.rs | 2 +- kani-compiler/src/kani_middle/stubbing/mod.rs | 8 +- .../src/kani_middle/transform/automatic.rs | 7 +- .../transform/check_uninit/delayed_ub/mod.rs | 4 +- .../src/kani_middle/transform/contracts.rs | 12 ++- .../src/kani_middle/transform/mod.rs | 5 +- .../src/kani_middle/transform/stubs.rs | 4 +- kani-driver/src/autoharness/mod.rs | 1 + kani_metadata/src/lib.rs | 4 + .../autoharness_explicit_tail_call/config.yml | 4 + .../autoharness_explicit_tail_call/expected | 3 + .../explicit_tail_call.rs | 13 +++ .../autoharness_explicit_tail_call/run.sh | 8 ++ .../original.expected | 2 + .../explicit-tail-calls-stubbing/original.rs | 29 ++++++ .../replacement.expected | 2 + .../replacement.rs | 29 ++++++ 22 files changed, 228 insertions(+), 69 deletions(-) create mode 100644 tests/script-based-pre/autoharness_explicit_tail_call/config.yml create mode 100644 tests/script-based-pre/autoharness_explicit_tail_call/expected create mode 100644 tests/script-based-pre/autoharness_explicit_tail_call/explicit_tail_call.rs create mode 100755 tests/script-based-pre/autoharness_explicit_tail_call/run.sh create mode 100644 tests/ui/explicit-tail-calls-stubbing/original.expected create mode 100644 tests/ui/explicit-tail-calls-stubbing/original.rs create mode 100644 tests/ui/explicit-tail-calls-stubbing/replacement.expected create mode 100644 tests/ui/explicit-tail-calls-stubbing/replacement.rs diff --git a/docs/src/reference/experimental/autoharness.md b/docs/src/reference/experimental/autoharness.md index b44888e61129..5967e462cfef 100644 --- a/docs/src/reference/experimental/autoharness.md +++ b/docs/src/reference/experimental/autoharness.md @@ -218,6 +218,7 @@ Autoharness records one skip reason per skipped function: the first failed check | `Generic Function: ` | Kani could not find a supported instantiation satisfying the function's constraints. The detail provides the specific cause; see [Generic Functions](#generic-functions). | | `The function does not have a body` | There is no function body available to verify, as with a trait method without a default implementation. | | `Did not match provided filters` | The function was excluded by the include/exclude patterns. | +| `Explicit tail calls are not supported` | The function's body contains an explicit tail call (`become`), which Kani does not support. | | `Unsupported variadic calling convention` | The function is a C-variadic function whose calling convention Kani cannot model (for example, `extern "sysv64"`). | | `Missing Arbitrary implementation for argument(s) x: T, y: U` | At least one argument cannot be generated using a supported argument model. The argument names and types depend on the function. | | `Requires --bounded-arguments for argument(s) x: T` | At least one argument requires opting into bounded generation. The argument names and types depend on the function. | diff --git a/kani-compiler/src/kani_middle/codegen_units.rs b/kani-compiler/src/kani_middle/codegen_units.rs index 04d982bcc0cf..b3e05b267eec 100644 --- a/kani-compiler/src/kani_middle/codegen_units.rs +++ b/kani-compiler/src/kani_middle/codegen_units.rs @@ -916,10 +916,9 @@ fn resolve_deferred_fn_slots<'tcx>( /// it, which fails that harness instead of the run; see /// . fn invalid_simd_instantiation(tcx: TyCtxt, instance: Instance) -> Option { - // Instantiation search loads this body before `automatic_harness_partition`'s eligibility - // check. A `become` panics in `rustc_public`'s MIR conversion, so reject it here too. - crate::kani_middle::reject_explicit_tail_calls(tcx, instance); - let body = instance.body()?; + // Instantiation search runs before `automatic_harness_partition`'s eligibility check, which + // skips a function with an explicit tail call. Do not report it here. + let body = crate::kani_middle::body_without_tail_calls(tcx, instance)?; body.blocks.iter().find_map(|block| { let TerminatorKind::Call { func, .. } = &block.terminator.kind else { return None; @@ -1222,10 +1221,12 @@ fn automatic_harness_partition( "{crate_name}::{}", crate::kani_middle::strip_local_crate_prefix(instance.name()) ); - // Autoharness loads every local body directly. A `become` panics in `rustc_public`'s MIR - // conversion; reject it before that load. - crate::kani_middle::reject_explicit_tail_calls(tcx, instance); - let body = instance.body().unwrap(); + // Autoharness loads every local body. Skip a function whose body `rustc_public` cannot + // convert, rather than aborting the run for every other function. + if crate::kani_middle::has_explicit_tail_call(tcx, instance) { + return Err(AutoHarnessSkipReason::UnsupportedTailCall); + } + let body = crate::kani_middle::checked_body(tcx, instance).unwrap(); if is_proof_harness(tcx, instance) || name.contains("kani::Arbitrary") @@ -1399,7 +1400,7 @@ fn automatic_harness_partition( // Whether any generated value will come from a type's public constructor // rather than raw field synthesis, which the summary reports as "(ctor)". let is_ctor_based = args.autoharness_constructor_args - && instance.body().is_some_and(|body| { + && crate::kani_middle::checked_body(tcx, instance).is_some_and(|body| { body.arg_locals().iter().any(|arg| { crate::kani_middle::uses_ctor_generation( tcx, diff --git a/kani-compiler/src/kani_middle/metadata.rs b/kani-compiler/src/kani_middle/metadata.rs index 78ec049b603f..86c3341cd505 100644 --- a/kani-compiler/src/kani_middle/metadata.rs +++ b/kani-compiler/src/kani_middle/metadata.rs @@ -8,8 +8,7 @@ use std::path::Path; use crate::kani_middle::codegen_units::Harness; use crate::kani_middle::{ - KaniAttributes, SourceLocation, readable_name, reject_explicit_tail_calls, - strip_local_crate_prefix, + KaniAttributes, SourceLocation, checked_body, readable_name, strip_local_crate_prefix, }; use kani_metadata::ContractedFunction; use kani_metadata::{ArtifactType, HarnessAttributes, HarnessKind, HarnessMetadata}; @@ -28,9 +27,7 @@ pub fn gen_proof_metadata(tcx: TyCtxt, instance: Instance, base_name: &Path) -> // We get the body span to include the entire function definition. // This is required for concrete playback to properly position the generated test. - // A `become` in the harness panics in `rustc_public`'s MIR conversion; reject it first. - reject_explicit_tail_calls(tcx, instance); - let loc = SourceLocation::new(instance.body().unwrap().span); + let loc = SourceLocation::new(checked_body(tcx, instance).unwrap().span); let file_stem = format!("{}_{mangled_name}", base_name.file_stem().unwrap().to_str().unwrap()); let model_file = base_name.with_file_name(file_stem).with_extension(ArtifactType::SymTabGoto); @@ -137,7 +134,7 @@ pub fn gen_automatic_proof_metadata( let mangled_name = fn_to_verify.mangled_name(); // Leave the concrete playback instrumentation for now, but this feature does not actually support concrete playback. - let loc = SourceLocation::new(fn_to_verify.body().unwrap().span); + let loc = SourceLocation::new(checked_body(tcx, *fn_to_verify).unwrap().span); let sha1_result = Sha1::try_digest(mangled_name); assert!(!sha1_result.has_collision()); let file_stem = format!( diff --git a/kani-compiler/src/kani_middle/mined_invariants.rs b/kani-compiler/src/kani_middle/mined_invariants.rs index 77b85e100aff..831f7e6a67c6 100644 --- a/kani-compiler/src/kani_middle/mined_invariants.rs +++ b/kani-compiler/src/kani_middle/mined_invariants.rs @@ -190,13 +190,13 @@ fn postdominates(body: &Body, from: usize, bb: usize) -> bool { /// Extract a [MinedExpr] for `op` in `body`, where local `_1` is `&self` (or `self`). /// Returns None (bail) when the slice leaves the pure/call-free/single-assignment fragment. -fn extract_expr(body: &Body, op: &Operand, depth: usize) -> Option { +fn extract_expr(tcx: TyCtxt, body: &Body, op: &Operand, depth: usize) -> Option { if depth > 24 { return None; } match op { Operand::Constant(c) => extract_const(c), - Operand::Copy(place) | Operand::Move(place) => extract_place(body, place, depth), + Operand::Copy(place) | Operand::Move(place) => extract_place(tcx, body, place, depth), Operand::RuntimeChecks(_) => None, } } @@ -209,7 +209,7 @@ fn extract_const(c: &ConstOperand) -> Option { /// `self` is local 1; a place rooted at it with Deref/Field projections is a field path /// (an optional leading Downcast records the enum variant, for variant-guarded conjuncts). -fn extract_place(body: &Body, place: &Place, depth: usize) -> Option { +fn extract_place(tcx: TyCtxt, body: &Body, place: &Place, depth: usize) -> Option { use rustc_public::mir::ProjectionElem; if place.local == 1 { let mut path = vec![]; @@ -237,7 +237,7 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option if place.projection.len() == 1 && matches!(place.projection[0], ProjectionElem::Deref) { let base = Place { local: place.local, projection: vec![] }; if let Some(inner) = unique_ref_def(body, &base) { - return extract_place(body, &inner, depth + 1); + return extract_place(tcx, body, &inner, depth + 1); } return None; } @@ -274,19 +274,19 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option if let Some(term) = call_def { // One-level getter inlining: a call to a pure accessor of `self` whose body is // itself extractable (e.g. `self.len()` where len returns a field expression). - return extract_getter_call(body, term, depth); + return extract_getter_call(tcx, body, term, depth); } match def? { - Rvalue::Use(inner, _) => extract_expr(body, inner, depth + 1), + Rvalue::Use(inner, _) => extract_expr(tcx, body, inner, depth + 1), Rvalue::BinaryOp(bop, a, b) => Some(MinedExpr::BinOp( *bop, - Box::new(extract_expr(body, a, depth + 1)?), - Box::new(extract_expr(body, b, depth + 1)?), + Box::new(extract_expr(tcx, body, a, depth + 1)?), + Box::new(extract_expr(tcx, body, b, depth + 1)?), )), Rvalue::UnaryOp(uop, a) => { - Some(MinedExpr::UnOp(*uop, Box::new(extract_expr(body, a, depth + 1)?))) + Some(MinedExpr::UnOp(*uop, Box::new(extract_expr(tcx, body, a, depth + 1)?))) } - Rvalue::CopyForDeref(p) => extract_place(body, p, depth + 1), + Rvalue::CopyForDeref(p) => extract_place(tcx, body, p, depth + 1), _ => None, } } @@ -296,6 +296,7 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option /// unique, extractable definition. Rebase that definition onto the caller's receiver. /// Depth-limited. fn extract_getter_call( + tcx: TyCtxt, body: &Body, term: &rustc_public::mir::Terminator, depth: usize, @@ -317,7 +318,8 @@ fn extract_getter_call( let fn_ty = func.ty(body.locals()).ok()?; let TyKind::RigidTy(RigidTy::FnDef(def, fn_args)) = fn_ty.kind() else { return None }; let inst = Instance::resolve(def, &fn_args).ok()?; - let callee = inst.body()?; + // Mining is a heuristic: ignore a getter whose body cannot be loaded. + let callee = crate::kani_middle::body_without_tail_calls(tcx, inst)?; // Unique assignment to the return local, extractable in the callee's own self frame. let mut ret_def: Option = None; for block in &callee.blocks { @@ -329,14 +331,14 @@ fn extract_getter_call( return None; } ret_def = Some(match rv { - Rvalue::Use(inner, _) => extract_expr(&callee, inner, depth + 1)?, + Rvalue::Use(inner, _) => extract_expr(tcx, &callee, inner, depth + 1)?, Rvalue::BinaryOp(bop, a, b) => MinedExpr::BinOp( *bop, - Box::new(extract_expr(&callee, a, depth + 1)?), - Box::new(extract_expr(&callee, b, depth + 1)?), + Box::new(extract_expr(tcx, &callee, a, depth + 1)?), + Box::new(extract_expr(tcx, &callee, b, depth + 1)?), ), Rvalue::UnaryOp(uop, a) => { - MinedExpr::UnOp(*uop, Box::new(extract_expr(&callee, a, depth + 1)?)) + MinedExpr::UnOp(*uop, Box::new(extract_expr(tcx, &callee, a, depth + 1)?)) } _ => return None, }); @@ -437,7 +439,10 @@ pub fn mine_self_assert_conjuncts(tcx: TyCtxt, ty: Ty, kani_assert: FnDef) -> Ve let Ok(inst) = Instance::resolve(fn_def, &rustc_public::ty::GenericArgs(vec![])) else { continue; }; - let Some(body) = inst.body() else { continue }; + // Mining is a heuristic: ignore a method whose body cannot be loaded. + let Some(body) = crate::kani_middle::body_without_tail_calls(tcx, inst) else { + continue; + }; // First parameter must be self by-ref or by-value of our type. let Some(self_decl) = body.arg_locals().first() else { continue }; let self_ok = self_decl.ty == ty @@ -500,7 +505,7 @@ pub fn mine_self_assert_conjuncts(tcx: TyCtxt, ty: Ty, kani_assert: FnDef) -> Ve if !unconditional && !arm_guarded { continue; } - let Some(expr) = extract_expr(&body, &args[0], 0) else { continue }; + let Some(expr) = extract_expr(tcx, &body, &args[0], 0) else { continue }; // Arm-guarded conjuncts must carry the variant via their downcast reads; // unconditional conjuncts must not (a bare downcast read without its match // would be under-guarded). diff --git a/kani-compiler/src/kani_middle/mod.rs b/kani-compiler/src/kani_middle/mod.rs index 57a7458470d6..6093b083178e 100644 --- a/kani-compiler/src/kani_middle/mod.rs +++ b/kani-compiler/src/kani_middle/mod.rs @@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::{def::DefKind, def_id::DefId as InternalDefId, def_id::LOCAL_CRATE}; use rustc_middle::ty::TyCtxt; use rustc_public::mir::mono::{Instance, MonoItem}; -use rustc_public::mir::{Mutability, TerminatorKind}; +use rustc_public::mir::{Body, Mutability, TerminatorKind}; use rustc_public::rustc_internal; use rustc_public::ty::{ AdtDef, AdtKind, FnDef, GenericArgKind, GenericArgs, PolyFnSig, RigidTy, Span as SpanStable, @@ -128,7 +128,8 @@ pub fn check_crate_items(tcx: TyCtxt, ignore_asm: bool) { tcx.dcx().abort_if_errors(); } -/// Reject explicit tail calls (`become`) before `rustc_public` converts the body. +/// The body of `instance`, or `None` if it has none; aborts with a diagnostic if it contains an +/// explicit tail call (`become`). /// /// Stable `rustc_public::mir::TerminatorKind` has no `TailCall` variant, so converting a body that /// contains one hits `unimplemented!()` inside the toolchain and aborts the compilation, c.f. @@ -136,32 +137,83 @@ pub fn check_crate_items(tcx: TyCtxt, ignore_asm: bool) { /// such terminator and abort once. Leave the call unmodeled: an ordinary `Call` would keep the /// caller's frame live, which disagrees with `become`. /// -/// The check reads the *internal* body — `tcx.instance_mir` on the instance's `def`, the same body -/// `rustc_public_bridge`'s `BodyBuilder` converts — because that conversion is what panics. -/// Callers invoke this immediately before `instance.body()`. -pub fn reject_explicit_tail_calls(tcx: TyCtxt, instance: Instance) { - if !instance.has_body() { - return; +/// Use this instead of `instance.body()` wherever the body may belong to user code. Where an +/// unsupported body should be ignored rather than reported (heuristics, eligibility checks), use +/// [body_without_tail_calls] or [has_explicit_tail_call]. +pub fn checked_body(tcx: TyCtxt, instance: Instance) -> Option { + // `has_body` is about the item: compiler-generated shims have no item body, but + // `instance.body()` still builds one for them, and they never contain `become`. + if instance.has_body() { + report_tail_calls(tcx, tail_call_spans(tcx, internal_body_kind(tcx, instance))); + } + instance.body() +} + +/// [checked_body] for a function definition, as loaded by `FnDef::body()`. +pub fn checked_fn_def_body(tcx: TyCtxt, def: FnDef) -> Option { + if !def.has_body() { + return None; } - // `BodyBuilder` loads an intrinsic's fallback body as the item. `instance_mir` rejects - // `InstanceKind::Intrinsic`. + let def_id = rustc_internal::internal(tcx, def.def_id()); + report_tail_calls(tcx, tail_call_spans(tcx, rustc_middle::ty::InstanceKind::Item(def_id))); + def.body() +} + +/// The body of `instance`, or `None` if it has none or contains an explicit tail call. Unlike +/// [checked_body], this reports nothing. +pub fn body_without_tail_calls(tcx: TyCtxt, instance: Instance) -> Option { + if has_explicit_tail_call(tcx, instance) { + return None; + } + instance.body() +} + +/// Whether `instance` has a body containing an explicit tail call (`become`), which +/// `instance.body()` cannot convert. See [checked_body]. +pub fn has_explicit_tail_call(tcx: TyCtxt, instance: Instance) -> bool { + instance.has_body() && !tail_call_spans(tcx, internal_body_kind(tcx, instance)).is_empty() +} + +/// The internal instance whose MIR `rustc_public_bridge`'s `BodyBuilder` converts for `instance`. +/// It loads an intrinsic's fallback body as the item, and `instance_mir` rejects +/// `InstanceKind::Intrinsic`. +fn internal_body_kind<'tcx>( + tcx: TyCtxt<'tcx>, + instance: Instance, +) -> rustc_middle::ty::InstanceKind<'tcx> { use rustc_middle::ty::InstanceKind; - let internal_instance = rustc_internal::internal(tcx, instance); - let def = match internal_instance.def { + match rustc_internal::internal(tcx, instance).def { InstanceKind::Intrinsic(def_id) => InstanceKind::Item(def_id), InstanceKind::Item(def_id) => InstanceKind::Item(def_id), InstanceKind::LlvmIntrinsic(def_id) => InstanceKind::LlvmIntrinsic(def_id), InstanceKind::Shim(kind) => InstanceKind::Shim(kind), InstanceKind::Virtual(def_id, idx) => InstanceKind::Virtual(def_id, idx), - }; - let body = tcx.instance_mir(def); - for bb in body.basic_blocks.iter() { - let rustc_middle::mir::TerminatorKind::TailCall { fn_span, .. } = &bb.terminator().kind - else { - continue; - }; + } +} + +/// Spans of the explicit tail calls in the internal MIR for `def`, the body that the conversion +/// to `rustc_public` would panic on. +fn tail_call_spans<'tcx>( + tcx: TyCtxt<'tcx>, + def: rustc_middle::ty::InstanceKind<'tcx>, +) -> Vec { + tcx.instance_mir(def) + .basic_blocks + .iter() + .filter_map(|bb| match &bb.terminator().kind { + rustc_middle::mir::TerminatorKind::TailCall { fn_span, .. } => Some(*fn_span), + _ => None, + }) + .collect() +} + +fn report_tail_calls(tcx: TyCtxt, spans: Vec) { + if spans.is_empty() { + return; + } + for span in spans { tcx.dcx() - .struct_span_err(*fn_span, "explicit tail calls (`become`) are not supported by Kani") + .struct_span_err(span, "explicit tail calls (`become`) are not supported by Kani") .with_note("see https://github.com/model-checking/kani/issues/5131") .emit(); } diff --git a/kani-compiler/src/kani_middle/points_to/points_to_analysis.rs b/kani-compiler/src/kani_middle/points_to/points_to_analysis.rs index 6a8444fcac70..fbbe55c84c80 100644 --- a/kani-compiler/src/kani_middle/points_to/points_to_analysis.rs +++ b/kani-compiler/src/kani_middle/points_to/points_to_analysis.rs @@ -455,7 +455,7 @@ impl<'tcx> PointsToAnalysis<'_, 'tcx> { // Here we simply call another function, so need to retrieve internal body for it. let new_body = { let stable_instance = rustc_internal::stable(instance); - let stable_body = stable_instance.body().unwrap(); + let stable_body = crate::kani_middle::checked_body(self.tcx, stable_instance).unwrap(); stable_body.internal_mir(self.tcx) }; diff --git a/kani-compiler/src/kani_middle/stubbing/mod.rs b/kani-compiler/src/kani_middle/stubbing/mod.rs index 187c5067aa18..179cb4c5075e 100644 --- a/kani-compiler/src/kani_middle/stubbing/mod.rs +++ b/kani-compiler/src/kani_middle/stubbing/mod.rs @@ -78,8 +78,12 @@ pub fn check_compatibility(tcx: TyCtxt, old_def: FnDef, new_def: FnDef) -> Resul // TODO: Validate stubs that do not have body. // We could potentially look at the function signature to see if they match. // However, they will include region information which can make types different. - let Some(old_body) = old_def.body() else { return Ok(()) }; - let Some(new_body) = new_def.body() else { return Ok(()) }; + let Some(old_body) = crate::kani_middle::checked_fn_def_body(tcx, old_def) else { + return Ok(()); + }; + let Some(new_body) = crate::kani_middle::checked_fn_def_body(tcx, new_def) else { + return Ok(()); + }; // Check whether the arities match. if old_body.arg_locals().len() != new_body.arg_locals().len() { let msg = format!( diff --git a/kani-compiler/src/kani_middle/transform/automatic.rs b/kani-compiler/src/kani_middle/transform/automatic.rs index db4e429a7269..689afc7831f0 100644 --- a/kani-compiler/src/kani_middle/transform/automatic.rs +++ b/kani-compiler/src/kani_middle/transform/automatic.rs @@ -395,7 +395,7 @@ fn inline_with_assumed_panics( arg_locals: &[Local], ret_ty: Ty, ) -> Option { - let callee_body = callee.body()?; + let callee_body = crate::kani_middle::body_without_tail_calls(tcx, callee)?; let span = source.span(body.blocks()); let ret_lcl = body.new_local(ret_ty, span, Mutability::Mut); @@ -540,7 +540,8 @@ fn inline_with_assumed_panics( } else if depth < INLINE_MAX_DEPTH && let Some((def, fn_args)) = &fn_def && let Ok(inst) = Instance::resolve(*def, fn_args) - && let Some(inner_body) = inst.body() + && let Some(inner_body) = + crate::kani_middle::body_without_tail_calls(self.tcx, inst) && inner_body.blocks.len() <= INLINE_MAX_BLOCKS && self.worth_inlining(&inner_body) { @@ -2394,7 +2395,7 @@ impl TransformPass for AutomaticHarnessPass { let kind = instance.args().0[0].expect_ty().kind(); let (def, args) = kind.fn_def().unwrap(); let fn_to_verify = Instance::resolve(def, args).unwrap(); - let fn_to_verify_body = fn_to_verify.body().unwrap(); + let fn_to_verify_body = crate::kani_middle::checked_body(tcx, fn_to_verify).unwrap(); let mut harness_body = MutableBody::from(body); harness_body.clear_body(TerminatorKind::Return); diff --git a/kani-compiler/src/kani_middle/transform/check_uninit/delayed_ub/mod.rs b/kani-compiler/src/kani_middle/transform/check_uninit/delayed_ub/mod.rs index 76e8111987ee..ca96dabf6686 100644 --- a/kani-compiler/src/kani_middle/transform/check_uninit/delayed_ub/mod.rs +++ b/kani-compiler/src/kani_middle/transform/check_uninit/delayed_ub/mod.rs @@ -72,7 +72,7 @@ impl GlobalPass for DelayedUbPass { let targets: HashSet<_> = instances .iter() .flat_map(|instance| { - let body = instance.body().unwrap(); + let body = crate::kani_middle::checked_body(tcx, *instance).unwrap(); let mut visitor = InitialTargetVisitor::new(body.clone()); visitor.visit_body(&body); // Convert all places into the format of aliasing graph for later comparison. @@ -104,7 +104,7 @@ impl GlobalPass for DelayedUbPass { MonoItem::GlobalAsm(_) => None, }; if let Some(instance) = entry_fn { - let body = instance.body().unwrap(); + let body = crate::kani_middle::checked_body(tcx, instance).unwrap(); let results = run_points_to_analysis(&body, tcx, instance, call_graph); global_points_to_graph.join(&results); } diff --git a/kani-compiler/src/kani_middle/transform/contracts.rs b/kani-compiler/src/kani_middle/transform/contracts.rs index 59baadbab4e6..45c1e68360ee 100644 --- a/kani-compiler/src/kani_middle/transform/contracts.rs +++ b/kani-compiler/src/kani_middle/transform/contracts.rs @@ -617,7 +617,7 @@ impl FunctionWithContractPass { let any_args = GenericArgs(vec![GenericArgKind::Type(ret_ty)]); let Ok(any_instance) = Instance::resolve(kani_any, &any_args) else { return }; - let Some(path) = find_call_path(&any_instance, &instance, &mut HashSet::new()) else { + let Some(path) = find_call_path(tcx, &any_instance, &instance, &mut HashSet::new()) else { return; }; @@ -752,6 +752,7 @@ fn find_closure(tcx: TyCtxt, fn_def: FnDef, body: &Body, name: &str) -> ClosureD /// acceptable here: missing a detection reproduces today's behavior (the hang), /// while a false positive would reject a working proof. fn find_call_path( + tcx: TyCtxt, from: &Instance, target: &Instance, visited: &mut HashSet, @@ -759,7 +760,8 @@ fn find_call_path( if !visited.insert(*from) { return None; } - let body = from.body()?; + // Diagnostic-only: a body this check cannot load is reported, if reached, by codegen. + let body = crate::kani_middle::body_without_tail_calls(tcx, *from)?; for bb in body.blocks.iter() { let TerminatorKind::Call { func, .. } = &bb.terminator.kind else { continue }; @@ -773,7 +775,7 @@ fn find_call_path( return Some(vec![from.name()]); } - if let Some(mut path) = find_call_path(&callee, target, visited) { + if let Some(mut path) = find_call_path(tcx, &callee, target, visited) { path.insert(0, from.name()); return Some(path); } @@ -821,7 +823,9 @@ fn check_mutual_recursion(tcx: TyCtxt, fn_def: FnDef, body: &Body) { // Check if the callee calls back to us (one level deep). let Ok(callee_instance) = Instance::resolve(callee_def, &callee_args) else { continue }; - let Some(callee_body) = callee_instance.body() else { continue }; + let Some(callee_body) = crate::kani_middle::checked_body(tcx, callee_instance) else { + continue; + }; for callee_bb in callee_body.blocks.iter() { let TerminatorKind::Call { func: callee_func, .. } = &callee_bb.terminator.kind else { diff --git a/kani-compiler/src/kani_middle/transform/mod.rs b/kani-compiler/src/kani_middle/transform/mod.rs index c66f6aa7ce14..2e0f44e455bf 100644 --- a/kani-compiler/src/kani_middle/transform/mod.rs +++ b/kani-compiler/src/kani_middle/transform/mod.rs @@ -154,10 +154,9 @@ impl BodyTransformation { .cache .entry(instance) .or_insert_with(|| { - // `become` panics in `rustc_public`'s MIR conversion; reject it before loading. - crate::kani_middle::reject_explicit_tail_calls(tcx, instance); // Transform and add to the cache if there's no existing entry. - let mut body = instance.body().unwrap_or_else(|| build_missing_body(tcx, instance)); + let mut body = crate::kani_middle::checked_body(tcx, instance) + .unwrap_or_else(|| build_missing_body(tcx, instance)); let mut modified = false; for pass in self.stub_passes.iter_mut().chain(self.inst_passes.iter_mut()) { diff --git a/kani-compiler/src/kani_middle/transform/stubs.rs b/kani-compiler/src/kani_middle/transform/stubs.rs index d2770fe7f45e..333e30141b37 100644 --- a/kani-compiler/src/kani_middle/transform/stubs.rs +++ b/kani-compiler/src/kani_middle/transform/stubs.rs @@ -131,7 +131,7 @@ impl ExternFnStubPass { } fn has_body(def: FnDef) -> bool { - def.body().is_some() + def.has_body() } /// Validate that the body of the stub is valid for the given instantiation @@ -145,7 +145,7 @@ struct FnStubValidator<'a, 'tcx> { impl FnStubValidator<'_, '_> { fn validate(tcx: TyCtxt, stub: (FnDef, FnDef), new_instance: Instance) -> Option { if validate_stub_const(tcx, new_instance) { - let body = new_instance.body().unwrap(); + let body = crate::kani_middle::checked_body(tcx, new_instance).unwrap(); let mut validator = FnStubValidator { stub, tcx, locals: body.locals(), is_valid: true }; validator.visit_body(&body); diff --git a/kani-driver/src/autoharness/mod.rs b/kani-driver/src/autoharness/mod.rs index b1205c271898..d63c4bb7ac02 100644 --- a/kani-driver/src/autoharness/mod.rs +++ b/kani-driver/src/autoharness/mod.rs @@ -155,6 +155,7 @@ fn print_autoharness_metadata(metadata: Vec) { } AutoHarnessSkipReason::Comptime | AutoHarnessSkipReason::NoBody + | AutoHarnessSkipReason::UnsupportedTailCall | AutoHarnessSkipReason::UnsupportedVariadic | AutoHarnessSkipReason::UserFilter => { Some(vec![md.crate_name.clone(), func, reason.to_string()]) diff --git a/kani_metadata/src/lib.rs b/kani_metadata/src/lib.rs index ef884ddf9dac..e3c8e13cb1f7 100644 --- a/kani_metadata/src/lib.rs +++ b/kani_metadata/src/lib.rs @@ -108,6 +108,10 @@ pub enum AutoHarnessSkipReason { /// (The Vec<(String, String)> contains the list of (name, type) tuples for each such argument.) #[strum(serialize = "Requires --bounded-arguments for argument(s)")] RequiresBoundedArguments(Vec<(String, String)>), + /// The function's body contains an explicit tail call (`become`), which Kani does not support + /// (c.f. https://github.com/model-checking/kani/issues/5131). + #[strum(serialize = "Explicit tail calls are not supported")] + UnsupportedTailCall, /// The function is a C-variadic whose calling convention Kani cannot model, e.g. /// `unsafe extern "sysv64" fn(_: ...)`. #[strum(serialize = "Unsupported variadic calling convention")] diff --git a/tests/script-based-pre/autoharness_explicit_tail_call/config.yml b/tests/script-based-pre/autoharness_explicit_tail_call/config.yml new file mode 100644 index 000000000000..ce281b640905 --- /dev/null +++ b/tests/script-based-pre/autoharness_explicit_tail_call/config.yml @@ -0,0 +1,4 @@ +# Copyright Kani Contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT +script: run.sh +expected: expected diff --git a/tests/script-based-pre/autoharness_explicit_tail_call/expected b/tests/script-based-pre/autoharness_explicit_tail_call/expected new file mode 100644 index 000000000000..8f5ce75fc459 --- /dev/null +++ b/tests/script-based-pre/autoharness_explicit_tail_call/expected @@ -0,0 +1,3 @@ +| explicit_tail_call | tail_call | Explicit tail calls are not supported | +| explicit_tail_call | ok_fn | #[kani::proof] | Success | +Complete - 1 successfully verified functions, 0 failures, 1 total. diff --git a/tests/script-based-pre/autoharness_explicit_tail_call/explicit_tail_call.rs b/tests/script-based-pre/autoharness_explicit_tail_call/explicit_tail_call.rs new file mode 100644 index 000000000000..6d5dfa6c139e --- /dev/null +++ b/tests/script-based-pre/autoharness_explicit_tail_call/explicit_tail_call.rs @@ -0,0 +1,13 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![feature(explicit_tail_calls)] +#![allow(incomplete_features)] + +pub fn tail_call(x: u8) -> u8 { + become ok_fn(x) +} + +pub fn ok_fn(x: u8) -> u8 { + x / 2 +} diff --git a/tests/script-based-pre/autoharness_explicit_tail_call/run.sh b/tests/script-based-pre/autoharness_explicit_tail_call/run.sh new file mode 100755 index 000000000000..f11282ab18cd --- /dev/null +++ b/tests/script-based-pre/autoharness_explicit_tail_call/run.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Copyright Kani Contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT + +# A function with an explicit tail call (`become`) used to abort the whole autoharness run +# (https://github.com/model-checking/kani/issues/5131). It must now be skipped with a reason, +# while `ok_fn` in the same crate is still verified. +kani autoharness -Z autoharness --output-format=regular explicit_tail_call.rs diff --git a/tests/ui/explicit-tail-calls-stubbing/original.expected b/tests/ui/explicit-tail-calls-stubbing/original.expected new file mode 100644 index 000000000000..900554e875d8 --- /dev/null +++ b/tests/ui/explicit-tail-calls-stubbing/original.expected @@ -0,0 +1,2 @@ +error: explicit tail calls (`become`) are not supported by Kani +original.rs:18:12 diff --git a/tests/ui/explicit-tail-calls-stubbing/original.rs b/tests/ui/explicit-tail-calls-stubbing/original.rs new file mode 100644 index 000000000000..3276d8cc9ffc --- /dev/null +++ b/tests/ui/explicit-tail-calls-stubbing/original.rs @@ -0,0 +1,29 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// kani-flags: -Z stubbing +// +//! Stub validation loads the original function's body. A `become` there is reported as +//! unsupported instead of panicking inside `rustc_public`. +//! + +#![feature(explicit_tail_calls)] +#![allow(incomplete_features)] + +fn g(x: u32) -> u32 { + x + 1 +} + +fn original(x: u32) -> u32 { + become g(x) +} + +fn replacement(x: u32) -> u32 { + x + 1 +} + +#[kani::proof] +#[kani::stub(original, replacement)] +fn check_stubbed_original() { + assert_eq!(original(1), 2); +} diff --git a/tests/ui/explicit-tail-calls-stubbing/replacement.expected b/tests/ui/explicit-tail-calls-stubbing/replacement.expected new file mode 100644 index 000000000000..2484a2958401 --- /dev/null +++ b/tests/ui/explicit-tail-calls-stubbing/replacement.expected @@ -0,0 +1,2 @@ +error: explicit tail calls (`become`) are not supported by Kani +replacement.rs:22:12 diff --git a/tests/ui/explicit-tail-calls-stubbing/replacement.rs b/tests/ui/explicit-tail-calls-stubbing/replacement.rs new file mode 100644 index 000000000000..dc82eea53edd --- /dev/null +++ b/tests/ui/explicit-tail-calls-stubbing/replacement.rs @@ -0,0 +1,29 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// kani-flags: -Z stubbing +// +//! Stub validation and the stub pass load the replacement function's body. A `become` there is +//! reported as unsupported instead of panicking inside `rustc_public`. +//! + +#![feature(explicit_tail_calls)] +#![allow(incomplete_features)] + +fn g(x: u32) -> u32 { + x + 1 +} + +fn original(x: u32) -> u32 { + x + 1 +} + +fn replacement(x: u32) -> u32 { + become g(x) +} + +#[kani::proof] +#[kani::stub(original, replacement)] +fn check_stubbed_replacement() { + assert_eq!(original(1), 2); +}