Skip to content

DFCC: variables dead at the loop head are loop locals - #9524

Open
feliperodri wants to merge 3 commits into
diffblue:developfrom
feliperodri:dfcc-liveness-loop-locals
Open

feliperodri wants to merge 3 commits into
diffblue:developfrom
feliperodri:dfcc-liveness-loop-locals

Conversation

@feliperodri

@feliperodri feliperodri commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

#9185 made only variables declared inside a loop count as loop locals, fixing the unsoundness in #9175. That is sound, but front-ends that declare every local at the start of a function lose all loop locals. Kani declares each MIR local at function entry, for example. Every temporary a loop writes must then be havoced and listed in the loop's assigns clause, which the user cannot name. Since #9185, 20 of Kani's loop-contract regression tests fail with Check that var_N is assignable, plus a dead-object failure where the clause is inferred.

This PR keeps #9185's guarantee and recovers those loop locals with a criterion that is sound by construction.

Change

A variable declared outside a loop is now also a loop local if all of the following hold:

  1. Its address is never taken in the function (it is not dirty), so no pointer can reach it.
  2. No instruction outside the loop uses it, other than its DECL/DEAD and assignments to CPROVER instrumentation variables. These are the __CPROVER_dead_object updates front-ends use to model lifetimes.
  3. It does not occur in the contract clauses of any loop of the function. Clauses are evaluated at points (head, latch, base case) that are not modelled as instructions.
  4. It is dead at the loop head. Every path from the head overwrites the whole variable before reading it. Writes to a part of the variable (x.f = e) do not count as overwriting it.

Then the loop never reads a value the variable had before an iteration, so havocing it is unnecessary, and nothing after the loop reads what the loop assigns to it. #9175's t is read before it is written in each iteration, so it stays non-local and is havoced.

Condition 1 keeps the criterion syntactic. An earlier revision of this PR also admitted address-taken variables, with alias and escape analysis, and review kept finding pointer-provenance gaps in it. Requiring the address not to be taken removes that whole class: pointer chains, pointers loaded from fields, call results, integer-to-pointer casts, memory builtins, escaped holders. Kani needs nothing more: its address-taken temporaries (loop-invariant closures and the like) are added to explicit clauses on the Kani side, in model-checking/kani#5209.

Two smaller changes:

  • Consistent inference: assigns-clause inference uses the loop locals of the original function, computed before inlining, so that the inferred clause and the instrumentation agree.
  • Havoc pragma: the havoc of the write set (*__havoc_target := nondet) is no longer pointer-checked. It isn't a program access, and target validity is already checked by ptr NULL or writable up to size when targets enter the write set. Without this, havocing a variable whose lifetime ended in the previous iteration reported a spurious "dereference failure: dead object". An invalid target, e.g. __CPROVER_assigns(*p) with p dangling, still fails with ptr NULL or writable up to size.

Why not restore #8489's heuristic

#8489's rule ("not read or written outside the loop") is unsound beyond #9175. The new regression tests include 19 programs whose assertions or invariants fail at run time, and CBMC before #9185 reports VERIFICATION SUCCESSFUL on 15 of them. The failing value is read:

  • directly, or in the loop guard,
  • after only partial writes,
  • through a pointer or a pointer-to-pointer,
  • by a callee,
  • through a field of a local or global struct,
  • through a pointer saved before the loop.

All of these now fail as expected.

Tests

24 tests in regression/contracts-dfcc/loop_locals_* (including #9185's two):

  • 19 programs whose assertions or invariants fail at run time, all reported as failures.
  • loop_locals_decl_outside_dead_at_head: a variable that becomes a loop local.
  • loop_locals_address_taken_not_loop_local: an address-taken variable that doesn't.
  • loop_locals_decl_outside_read_after_loop, loop_locals_address_outlives_loop and loop_locals_decl_outside_read_in_guard: variables whose values are observed after the loop, through a pointer that outlives the loop, or in the loop guard, so they must be in the assigns clause.

Results:

  • CBMC contracts suites (contracts-CORE, contracts-dfcc-{1..4}-CORE, contracts-dfcc-THOROUGH, contracts-non-dfcc-CORE, contracts-THOROUGH) pass.
  • Full ctest (145 suites): the only failures are four suites that need gdb or cvc5, which are not installed on the test machine.
  • Kani main with this CBMC, plus the Kani-side change: expected/loop-contract 92/92, full expected 562/562, and the kani suite has no failures beyond two quantifier tests that also fail with release CBMC 6.11.0 on the same machine.

Checklist

  • Each commit message has a non-empty body, explaining why the change was made.
  • Methods or procedures I have added are documented, following the guidelines provided in CODING_STANDARD.md.
  • The feature or user visible behaviour I have added or modified has been documented in the User Guide in doc/cprover-manual/
  • Regression or unit tests are included, or existing tests cover the modified code (in this case I have detailed which ones those are in the commit message).
  • My commit message includes data points confirming performance improvements (if claimed).
  • My PR is restricted to a single feature or bugfix.
  • White-space or formatting changes outside the feature-related changed lines are in commits of their own.

@feliperodri feliperodri added Code Contracts Function and loop contracts soundness Soundness bug? Review and add "aws" if it is, or remove "soundness" if it isn't. labels Nov 19, 2026
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.72727% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.22%. Comparing base (f04da2e) to head (0c7bd94).
⚠️ Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
...ntracts/dynamic-frames/dfcc_infer_loop_assigns.cpp 98.31% 2 Missing ⚠️
...trument/contracts/dynamic-frames/dfcc_cfg_info.cpp 90.90% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #9524      +/-   ##
===========================================
+ Coverage    81.21%   81.22%   +0.01%     
===========================================
  Files         1725     1725              
  Lines       191614   191734     +120     
  Branches        73       73              
===========================================
+ Hits        155622   155740     +118     
- Misses       35992    35994       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical alias-analysis gaps miss transitive pointer reads and escapes, allowing variables with previous-iteration values to be incorrectly omitted from loop havoc.

2 open issues
What changed in this PR

This PR extends DFCC loop-local detection to recover temporaries declared at function entry, as used by Kani, while preserving the protection against previous-iteration value leakage introduced by #9185.

Changes:

  • Adds liveness, pointer-reachability, and escape analysis for outside-declared loop locals.
  • Aligns assigns inference with instrumentation and disables pointer checks on generated havoc writes.
  • Documents loop-local criteria and adds ten regression scenarios.
File Description
src/​goto-instrument/​contracts/​dynamic-frames/​dfcc_spec_functions.cpp Disables pointer checks on generated havoc assignments.
src/​goto-instrument/​contracts/​dynamic-frames/​dfcc_infer_loop_assigns.h Updates the loop-local API documentation.
src/​goto-instrument/​contracts/​dynamic-frames/​dfcc_infer_loop_assigns.cpp Adds loop-local analysis and preserves classifications across inlining.
src/​goto-instrument/​contracts/​dynamic-frames/​dfcc_cfg_info.cpp Adjusts write-set tracking for outside-declared locals.
src/​goto-instrument/​contracts/​doc/​user/​contracts-assigns.md Documents loop-local criteria with an example.
regression/​contracts-dfcc/​loop_locals_decl_outside_read_in_guard/​test.desc Requires assigns-check failure for a guard-read variable.
regression/​contracts-dfcc/​loop_locals_decl_outside_read_in_guard/​main.c Exercises a previous-iteration read in the loop guard.
regression/​contracts-dfcc/​loop_locals_decl_outside_read_after_loop/​test.desc Requires assigns-check failure for a post-loop read.
regression/​contracts-dfcc/​loop_locals_decl_outside_read_after_loop/​main.c Exercises a variable read after the loop.
regression/​contracts-dfcc/​loop_locals_decl_outside_partial_write/​test.desc Requires assertion failure after partial writes.
regression/​contracts-dfcc/​loop_locals_decl_outside_partial_write/​main.c Exercises retained struct-field values across iterations.
regression/​contracts-dfcc/​loop_locals_decl_outside_dead_at_head/​test.desc Requires successful verification for a dead-at-head local.
regression/​contracts-dfcc/​loop_locals_decl_outside_dead_at_head/​main.c Exercises an outside-declared temporary overwritten before use.
regression/​contracts-dfcc/​loop_locals_address_taken_read_through_pointer/​test.desc Requires failure for an indirect previous-value read.
regression/​contracts-dfcc/​loop_locals_address_taken_read_through_pointer/​main.c Exercises reads through a local pointer.
regression/​contracts-dfcc/​loop_locals_address_taken_read_by_callee/​test.desc Requires failure for a callee’s previous-value read.
regression/​contracts-dfcc/​loop_locals_address_taken_read_by_callee/​main.c Passes a candidate’s address to a reading callee.
regression/​contracts-dfcc/​loop_locals_address_taken_local_pointer/​test.desc Requires successful verification with a local pointer.
regression/​contracts-dfcc/​loop_locals_address_taken_local_pointer/​main.c Exercises a pointer read after a whole-variable overwrite.
regression/​contracts-dfcc/​loop_locals_address_outlives_loop/​test.desc Requires assigns-check failure for a post-loop pointer read.
regression/​contracts-dfcc/​loop_locals_address_outlives_loop/​main.c Exercises an address retained beyond the loop.
regression/​contracts-dfcc/​loop_locals_address_in_struct_field/​test.desc Requires failure for a read through a stored struct pointer.
regression/​contracts-dfcc/​loop_locals_address_in_struct_field/​main.c Exercises address propagation through a struct field.
regression/​contracts-dfcc/​loop_locals_address_escapes_to_global/​test.desc Requires failure for a read through an escaped address.
regression/​contracts-dfcc/​loop_locals_address_escapes_to_global/​main.c Exercises address escape through a callee into a global.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Incomplete pointer-alias handling can leave variables unhavoced and hide assertion failures, while removed tracking for nested-loop assignments can cause spurious assigns-inclusion failures.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Preserve outer-loop tracking for inner-loop writes

src/​goto-instrument/​contracts/​dynamic-frames/​dfcc_cfg_info.cpp:451

This also removes locals that gen_tracked_set tracks because a contracted inner loop assigns them. If t is declared before an outer loop, reset at each outer iteration, and updated by an inner loop, inference can omit it from the outer assigns clause while retaining it in the inner clause; removing its tracking then causes the assigns-inclusion check to fail even for direct writes. Preserve the tracking required by inner loops and register these outside-declared locals when creating the outer loop's write set, rather than relying only on DECL instructions.

2 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical gaps in implicit-read, pointer-alias, and contract-head read tracking can incorrectly leave loop-carried state unhavoced, hiding assertion failures.

4 open issues
2 resolved since last review

Review effort: Balanced

Since diffblue#9185, only variables declared inside a loop are loop locals. This
is sound, but front-ends that declare all locals at the start of a
function, such as Kani for Rust MIR, lose all loop locals: every
temporary that a loop writes must then be havoced and be in the loop's
assigns clause, which the user cannot name, so loops with an explicit
assigns clause fail with `Check that var_N is assignable`.

A variable declared outside a loop is now also a loop local if:
- its address is not taken (it is not dirty), so no pointer can reach it,
- no instruction outside the loop uses it, other than its DECL and DEAD
  and the assignments to CPROVER instrumentation variables (the
  `__CPROVER_dead_object` updates that model the lifetime of variables),
- it does not occur in the contract clauses of any loop of the function,
- and it is dead at the loop head: every path from the head overwrites
  the whole variable before reading it (writes to a part of it do not
  count). Liveness is computed by a small backward analysis.
Then the loop never reads a value it had before an iteration, so it need
not be havoced, and nothing after the loop reads the values the loop
assigns to it.

Requiring that the address of the variable is not taken keeps the
criterion syntactic: any reasoning about pointers that may reach the
variable (pointer chains, pointers loaded from memory or returned by
calls, integer-to-pointer casts, memory builtins, addresses that escape)
is unnecessary. Such a loop local is not tracked in the loop's write set,
since it has no DECL in the loop.

Assigns clause inference uses the loop locals of the original function,
computed before inlining, so that the inferred clauses and the
instrumentation classify variables the same way.

The removed heuristic of diffblue#8489 (no reads or writes outside the loop)
accepted unsound cases, which the new regression tests cover: CBMC before
diffblue#9185 reports VERIFICATION SUCCESSFUL on 15 of them, which have failing
assertions.
The havoc of a loop's write set gives each target an arbitrary value. It
is not an access of the program, and the validity of the targets is
checked when they are added to the write set (`ptr NULL or writable up to
size`). Yet the havoc assignment was pointer-checked, which reports a
dereference of a dead object when a target is a variable whose lifetime
ended in the previous iteration, e.g. a temporary that front-ends such as
Kani mark dead at the end of each iteration via `__CPROVER_dead_object`.
Disable pointer checks on these assignments.

A loop with an invalid assigns target (e.g. a dangling pointer
dereference) still fails with `ptr NULL or writable up to size`.
@feliperodri
feliperodri force-pushed the dfcc-liveness-loop-locals branch from d2af0f7 to 0f26e2b Compare November 19, 2026 20:37
@feliperodri

Copy link
Copy Markdown
Collaborator Author

I rewrote this PR to make the criterion sound by construction. Review kept finding pointer-provenance gaps in the alias and escape analysis that let address-taken variables become loop locals, so that analysis is gone: a variable declared before a loop is now a loop local only if its address is never taken (plus the liveness and use conditions in the description). The history is now three commits (the rule with its tests, the havoc pragma, the docs), and the source change is about 330 lines instead of about 1,100. Every program from the review threads is a regression test, and all of them fail as expected.

@kroening

Copy link
Copy Markdown
Collaborator

The long list of conditions for loop local variables in src/goto-instrument/contracts/doc/user/contracts-assigns.md does bug me a bit. Would it make sense for there to be a contract clause, say __CPROVER_loop_local(....)?

The loop assigns documentation used the notion of a loop local without
defining it. Describe which variables are loop locals, including those
declared before a loop that are dead at its head, with an example.
@feliperodri
feliperodri force-pushed the dfcc-liveness-loop-locals branch from 0f26e2b to 0c7bd94 Compare November 20, 2026 03:50
@feliperodri

feliperodri commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

The long list of conditions for loop local variables in src/goto-instrument/contracts/doc/user/contracts-assigns.md does bug me a bit. Would it make sense for there to be a contract clause, say __CPROVER_loop_local(....)?

Thanks, @kroening. I agree the list read badly. It's really one property: a variable declared before the loop can be treated as if it were declared at the start of the loop body when that wouldn't change what the program does. I've reworded the section (0c7bd94) to say that first, and to present the conditions as the conservative check CBMC uses for it.

I'd rather not add __CPROVER_loop_local, though. The variables this PR is about are compiler temporaries with no source name, so users can't write the clause, for the same reason they can't list those variables in __CPROVER_assigns. A front end like Kani could emit it, but then CBMC has two options. It can trust the clause, and a wrong annotation brings #9175 back. Or it can check the clause, and the check is these same conditions, so we'd add an interface without removing any analysis. For hand-written C, declaring the variable inside the loop body already says it is local to the loop, and those variables were loop locals before this PR.

The inference only ever moves a variable from "havoced and checked against the assigns clause" to neither, and only when it can't carry a value across iterations or out of the loop. Every other variable behaves the way it has since #9185.

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

Code Contracts Function and loop contracts soundness Soundness bug? Review and add "aws" if it is, or remove "soundness" if it isn't.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants