Skip to content

Commit 3076794

Browse files
usx95vbvictor
andauthored
[LifetimeSafety] Introduce intra-procedural analysis in Clang (#142313)
This patch introduces the initial implementation of the intra-procedural, flow-sensitive lifetime analysis for Clang, as proposed in the recent RFC: https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291 The primary goal of this initial submission is to establish the core dataflow framework and gather feedback on the overall design, fact representation, and testing strategy. The focus is on the dataflow mechanism itself rather than exhaustively covering all C++ AST edge cases, which will be addressed in subsequent patches. #### Key Components * **Conceptual Model:** Introduces the fundamental concepts of `Loan`, `Origin`, and `Path` to model memory borrows and the lifetime of pointers. * **Fact Generation:** A frontend pass traverses the Clang CFG to generate a representation of lifetime-relevant events, such as pointer assignments, taking an address, and variables going out of scope. * **Testing:** `llvm-lit` tests validate the analysis by checking the generated facts. ### Next Steps *(Not covered in this PR but planned for subsequent patches)* The following functionality is planned for the upcoming patches to build upon this foundation and make the analysis usable in practice: * **Dataflow Lattice:** A dataflow lattice used to map each pointer's symbolic `Origin` to the set of `Loans` it may contain at any given program point. * **Fixed-Point Analysis:** A worklist-based, flow-sensitive analysis that propagates the lattice state across the CFG to a fixed point. * **Placeholder Loans:** Introduce placeholder loans to represent the lifetimes of function parameters, forming the basis for analysis involving function calls. * **Annotation and Opaque Call Handling:** Use placeholder loans to correctly model **function calls**, both by respecting `[[clang::lifetimebound]]` annotations and by conservatively handling opaque/un-annotated functions. * **Error Reporting:** Implement the final analysis phase that consumes the dataflow results to generate user-facing diagnostics. This will likely require liveness analysis to identify live origins holding expired loans. * **Strict vs. Permissive Modes:** Add the logic to support both high-confidence (permissive) and more comprehensive (strict) warning levels. * **Expanded C++ Coverage:** Broaden support for common patterns, including the lifetimes of temporary objects and pointers within aggregate types (structs/containers). * Performance benchmarking * Capping number of iterations or number of times a CFGBlock is processed. --------- Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
1 parent 7920dff commit 3076794

File tree

7 files changed

+749
-0
lines changed

7 files changed

+749
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//===- LifetimeSafety.h - C++ Lifetime Safety Analysis -*----------- C++-*-===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
//
9+
// This file defines the entry point for a dataflow-based static analysis
10+
// that checks for C++ lifetime violations.
11+
//
12+
// The analysis is based on the concepts of "origins" and "loans" to track
13+
// pointer lifetimes and detect issues like use-after-free and dangling
14+
// pointers. See the RFC for more details:
15+
// https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
16+
//
17+
//===----------------------------------------------------------------------===//
18+
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
19+
#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
20+
#include "clang/AST/DeclBase.h"
21+
#include "clang/Analysis/AnalysisDeclContext.h"
22+
#include "clang/Analysis/CFG.h"
23+
namespace clang {
24+
25+
void runLifetimeSafetyAnalysis(const DeclContext &DC, const CFG &Cfg,
26+
AnalysisDeclContext &AC);
27+
28+
} // namespace clang
29+
30+
#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,9 @@ def Dangling : DiagGroup<"dangling", [DanglingAssignment,
532532
DanglingInitializerList,
533533
DanglingGsl,
534534
ReturnStackAddress]>;
535+
536+
def LifetimeSafety : DiagGroup<"experimental-lifetime-safety">;
537+
535538
def DistributedObjectModifiers : DiagGroup<"distributed-object-modifiers">;
536539
def DllexportExplicitInstantiationDecl : DiagGroup<"dllexport-explicit-instantiation-decl">;
537540
def ExcessInitializers : DiagGroup<"excess-initializers">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10627,6 +10627,10 @@ def warn_dangling_reference_captured_by_unknown : Warning<
1062710627
"object whose reference is captured will be destroyed at the end of "
1062810628
"the full-expression">, InGroup<DanglingCapture>;
1062910629

10630+
def warn_experimental_lifetime_safety_dummy_warning : Warning<
10631+
"todo: remove this warning after we have atleast one warning based on the lifetime analysis">,
10632+
InGroup<LifetimeSafety>, DefaultIgnore;
10633+
1063010634
// For non-floating point, expressions of the form x == x or x != x
1063110635
// should result in a warning, since these always evaluate to a constant.
1063210636
// Array comparisons have similar warnings

clang/lib/Analysis/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ add_clang_library(clangAnalysis
2121
FixitUtil.cpp
2222
IntervalPartition.cpp
2323
IssueHash.cpp
24+
LifetimeSafety.cpp
2425
LiveVariables.cpp
2526
MacroExpansionContext.cpp
2627
ObjCNoReturn.cpp

0 commit comments

Comments
 (0)