Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/reference/experimental/autoharness.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ Autoharness records one skip reason per skipped function: the first failed check
| `Generic Function: <detail>` | 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. |
Expand Down
1 change: 1 addition & 0 deletions docs/src/rust-feature-support/unstable.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
13 changes: 10 additions & 3 deletions kani-compiler/src/kani_middle/codegen_units.rs
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,9 @@ fn resolve_deferred_fn_slots<'tcx>(
/// it, which fails that harness instead of the run; see
/// <https://github.com/model-checking/kani/issues/4926>.
fn invalid_simd_instantiation(tcx: TyCtxt, instance: Instance) -> Option<String> {
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;
Expand Down Expand Up @@ -1219,7 +1221,12 @@ fn automatic_harness_partition(
"{crate_name}::{}",
crate::kani_middle::strip_local_crate_prefix(instance.name())
);
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")
Expand Down Expand Up @@ -1393,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,
Expand Down
8 changes: 5 additions & 3 deletions kani-compiler/src/kani_middle/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ 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, checked_body, readable_name, strip_local_crate_prefix,
};
use kani_metadata::ContractedFunction;
use kani_metadata::{ArtifactType, HarnessAttributes, HarnessKind, HarnessMetadata};
use rustc_middle::ty::TyCtxt;
Expand All @@ -25,7 +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.
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);

Expand Down Expand Up @@ -132,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!(
Expand Down
39 changes: 22 additions & 17 deletions kani-compiler/src/kani_middle/mined_invariants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MinedExpr> {
fn extract_expr(tcx: TyCtxt, body: &Body, op: &Operand, depth: usize) -> Option<MinedExpr> {
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,
}
}
Expand All @@ -209,7 +209,7 @@ fn extract_const(c: &ConstOperand) -> Option<MinedExpr> {

/// `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<MinedExpr> {
fn extract_place(tcx: TyCtxt, body: &Body, place: &Place, depth: usize) -> Option<MinedExpr> {
use rustc_public::mir::ProjectionElem;
if place.local == 1 {
let mut path = vec![];
Expand Down Expand Up @@ -237,7 +237,7 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option<MinedExpr>
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;
}
Expand Down Expand Up @@ -274,19 +274,19 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option<MinedExpr>
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,
}
}
Expand All @@ -296,6 +296,7 @@ fn extract_place(body: &Body, place: &Place, depth: usize) -> Option<MinedExpr>
/// 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,
Expand All @@ -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<MinedExpr> = None;
for block in &callee.blocks {
Expand All @@ -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,
});
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down
94 changes: 93 additions & 1 deletion kani-compiler/src/kani_middle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -128,6 +128,98 @@ pub fn check_crate_items(tcx: TyCtxt, ignore_asm: bool) {
tcx.dcx().abort_if_errors();
}

/// 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.
/// <https://github.com/model-checking/kani/issues/5131>. 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`.
///
/// 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<Body> {
// `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<Body> {
if !def.has_body() {
return None;
}
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<Body> {
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;
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),
}
}

/// 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<rustc_span::Span> {
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<rustc_span::Span>) {
if spans.is_empty() {
return;
}
for span in spans {
tcx.dcx()
.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();
}
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(_: ...)`.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
};

Expand Down
8 changes: 6 additions & 2 deletions kani-compiler/src/kani_middle/stubbing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
7 changes: 4 additions & 3 deletions kani-compiler/src/kani_middle/transform/automatic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ fn inline_with_assumed_panics(
arg_locals: &[Local],
ret_ty: Ty,
) -> Option<Local> {
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);

Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
Expand Down
Loading
Loading