llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Make it clearer how a loan ended up being used after it is destroyed

Open usx95 opened this issue 10 months ago • 5 comments

The idea for improvement is to highlight all the expressions/statements responsible for loan propagation of the expired loan to an origin which is used after the loan expires.

#include <iostream>
#include <string>
#include <string_view>

void foo() {
    std::string_view f;
    {
        std::string str = "small scoped string";
        std::string_view a, b, c, d, e;
        a = str;  // Ok. error: object whose reference is captured does not live long enough.
                  // TODO: add note: 'a' aliases 'str'
        b = a;
        c = a;  // TODO: add note: 'c' aliases 'a'
        d = c;  // TODO: add note: 'd' aliases 'c'
        e = d;
        f = d;  // TODO: add note: 'f' aliases 'd'
    }
    std::cout << f;
}

usx95 avatar Jan 26 '26 16:01 usx95

@llvm/issue-subscribers-clang-temporal-safety

Author: Utkarsh Saxena (usx95)

The idea for improvement is to highlight all the expressions/statements responsible for loan propagation of the expired loan to an origin which is used after the loan expires. ```cpp #include <iostream> #include <string> #include <string_view>

void foo() { std::string_view f; { std::string str = "small scoped string"; std::string_view a, b, c, d, e; a = str; // Ok. error: object whose reference is captured does not live long enough. // TODO: add note: 'a' aliases 'str' b = a; c = a; // TODO: add note: 'c' aliases 'a' d = c; // TODO: add note: 'd' aliases 'c' e = d; f = d; // TODO: add note: 'f' aliases 'd' } std::cout << f; }

</details>

llvmbot avatar Jan 26 '26 16:01 llvmbot

Hello, I am very interested in lifetime safety. I have explored the current implementation and hope to solve this problem.

To track the assignment chain without polluting the dataflow lattice, my current idea is to maintain a lightweight directed graph (mapping dest OriginID to src OriginID) within LoanPropagationAnalysis's AnalysisImpl. We can populate its edges during the transfer function whenever an OriginFlowFact is processed.

What are your thoughts on this approach? Specifically, do you think the memory and performance overhead of maintaining this side-graph during the analysis phase would be acceptable for Clang?

Thanks.

suoyuan666 avatar Mar 13 '26 15:03 suoyuan666

Thank you for your interest in Lifetime Safety! @suoyuan666

Maintaining such a graph could become complicated (e.g., this needs to consider reassignments and join points, I suspect we would end up with an immutable graph?). I wonder if there are cheaper ways to backtrack the origin flow, perhaps by doing it lazily in the LifetimeChecker only when we are about to emit a diagnostic?

Some ideas:

  • OriginFlowFact captures Expr that causes the flow (e.g., the assignment expression in a = b).
  • When LifetimeChecker detects a use-after-free where a live origin Dst holds an expired loan L, trigger a backtracking search from Dst at the point of use.
  • The search walks backward through facts in the CFG. If it encounters an OriginFlowFact(Dst, Src), it checks if Dst acquired loan L via this fact (e.g. did Src contain the loan ?)
  • If this fact is identified as the acquisition point, we can emit a diagnostic note using the expression of flow fact.
  • Continue the search recursively for Src from the point before this fact. Take care of branches (e.g. which branch to choose).
  • The search terminates once it reaches the IssueFact for L.

This approach avoids complicating the LoanPropagation lattice and only incurs the backtracking cost when generating a warning. It should handle linear assignment chains like in your example (f=d, d=c, etc.) and the one below quite well.

usx95 avatar Mar 13 '26 17:03 usx95

Thank you for your interest in Lifetime Safety! @suoyuan666

Maintaining such a graph could become complicated (e.g., this needs to consider reassignments and join points, I suspect we would end up with an immutable graph?). I wonder if there are cheaper ways to backtrack the origin flow, perhaps by doing it lazily in the LifetimeChecker only when we are about to emit a diagnostic?

Some ideas:

* `OriginFlowFact` captures `Expr` that causes the flow (e.g., the assignment expression in a = b).

* When `LifetimeChecker` detects a use-after-free where a live origin `Dst` holds an expired loan `L`, trigger a backtracking search from `Dst` at the point of use.

* The search walks backward through facts in the CFG. If it encounters an `OriginFlowFact(Dst, Src)`, it checks if `Dst` acquired loan `L` via this fact (e.g. did `Src` contain the loan ?)

* If this fact is identified as the acquisition point, we can emit a diagnostic note using the expression of flow fact.

* Continue the search recursively for `Src` from the point before this fact. Take care of branches (e.g. which branch to choose).

* The search terminates once it reaches the `IssueFact` for `L`.

This approach avoids complicating the LoanPropagation lattice and only incurs the backtracking cost when generating a warning. It should handle linear assignment chains like in your example (f=d, d=c, etc.) and the one below quite well.

Thank you for the detailed guidance! Your suggestion to use lazily backtracking search while emitting a diagnostic makes perfect sense - avoiding overhead on the normal path.

I spent a few hours hacking together a quick Proof of Concept based on your idea. By walking backward through the CFG and inspecting the OriginFlowFact, I successfully extracted the linear alias chain for the example:

$ clang++ -Wlifetime-safety test-lifetime-safety.cpp 
test-lifetime-safety.cpp:10:9: warning: object whose reference is captured does not live long enough [-Wlifetime-safety-use-after-scope]
   10 |     a = str; // Ok. error: object whose reference is captured does not live long
      |         ^~~
test-lifetime-safety.cpp:18:3: note: destroyed here
   18 |   }
      |   ^
[Debug]
test-lifetime-safety.cpp:10:9: note: destroyed here
   10 |     a = str; // Ok. error: object whose reference is captured does not live long
      |         ^
test-lifetime-safety.cpp:14:9: note: destroyed here
   14 |     c = a; // TODO: add note: 'c' aliases 'a'
      |         ^
test-lifetime-safety.cpp:15:9: note: destroyed here
   15 |     d = c; // TODO: add note: 'd' aliases 'c'
      |         ^
test-lifetime-safety.cpp:17:9: note: destroyed here
   17 |     f = d; // TODO: add note: 'f' aliases 'd'
      |         ^

test-lifetime-safety.cpp:19:16: note: later used here
   19 |   std::cout << f;
      |                ^

(Note: I didn't handle the error message specifically; instead, I directly reused diag::note_lifetime_safety_destroyed_here.)

To retrieve the CFG in issuePendingWarnings, I specifically saved AnalysisDeclContext & in LifetimeChecker. Of course, this can be optimized later; I did it this way simply for convenience.

I considered temporarily storing all CFGBlocks that detected errors, or looking up the corresponding Block ID based on the UseFact when issuePendingWarnings is triggered, and then querying it from the CFG. I'm currently using the second approach.

Next, I will test the alias chain printing locally under more complex processes (such as the multi-branch scenario you mentioned).

Once I have the branching logic solidified and the diagnostic messages cleaned up, I will submit a PR.

Thanks again for pointing me in the exact right direction!

suoyuan666 avatar Mar 14 '26 12:03 suoyuan666

Hi Utkarsh,

I've implemented reverse searching of CFG Blocks using BFS, limiting the number of Blocks searched to 32, stopping the search if a duplicate Block is found.

In other words, iterating through the Blocks in reverse, and then iterating through the Facts within each Block in reverse...

I removed the previous method of searching for CFG BlockID and replaced it with ADC.getCFGStmtMap()->getBlock(UF->getUseExpr()).

Is the performance overhead of this approach acceptable to Clang?

I've modified the warning message; below is my current output:

#include <iostream>
#include <string>
#include <string_view>

void foo(int condition) {
    std::string_view f;
    {
        std::string local_str = "haha";
        std::string_view a, b;

        if (condition > 10) {
            a = local_str; 
            f = a;
        } 
        else if (condition > 0) {
            b = local_str;
            std::string_view temp = b;
            f = temp;
        }
        else {
            f = "test"; 
        }
    } 

    std::cout << f; 
}
$  clang++ -Wlifetime-safety test-multibranch-lifetime-safety.cpp 
test-multibranch-lifetime-safety.cpp:16:17: warning: object whose reference is captured does not live long enough [-Wlifetime-safety-use-after-scope]
   16 |             b = local_str;
      |                 ^~~~~~~~~
test-multibranch-lifetime-safety.cpp:23:5: note: destroyed here
   23 |     } 
      |     ^
test-multibranch-lifetime-safety.cpp:16:17: note: variable `b` is now an alias of `local_str`
   16 |             b = local_str;
      |                 ^
test-multibranch-lifetime-safety.cpp:17:37: note: variable `temp` is now an alias of `b`
   17 |             std::string_view temp = b;
      |                                     ^
test-multibranch-lifetime-safety.cpp:18:17: note: variable `f` is now an alias of `temp`
   18 |             f = temp;
      |                 ^
test-multibranch-lifetime-safety.cpp:25:18: note: later used here
   25 |     std::cout << f; 
      |                  ^
test-multibranch-lifetime-safety.cpp:12:17: warning: object whose reference is captured does not live long enough [-Wlifetime-safety-use-after-scope]
   12 |             a = local_str; 
      |                 ^~~~~~~~~
test-multibranch-lifetime-safety.cpp:23:5: note: destroyed here
   23 |     } 
      |     ^
test-multibranch-lifetime-safety.cpp:12:17: note: variable `a` is now an alias of `local_str`
   12 |             a = local_str; 
      |                 ^
test-multibranch-lifetime-safety.cpp:13:17: note: variable `f` is now an alias of `a`
   13 |             f = a;
      |                 ^
test-multibranch-lifetime-safety.cpp:25:18: note: later used here
   25 |     std::cout << f; 
      |                  ^
2 warnings generated.

Regarding the Block search depth limit, my setting of 32 is purely based on personal preference. Perhaps 32 could be replaced with a configurable option? Perhaps I could consider using -flifetime-safety-max-cfg-blocks=N.

If everything is fine, I will prepare more local tests, then clean up the code and submit PR.


Update: I will clean up the code and submit a PR. Let's discuss the details directly in the PR.

suoyuan666 avatar Mar 19 '26 15:03 suoyuan666