clang 23.0.0git
LifetimeSafety.h
Go to the documentation of this file.
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 main entry point and orchestrator for the C++ Lifetime
10// Safety Analysis. It coordinates the entire analysis pipeline: fact
11// generation, loan propagation, live origins analysis, and enforcement of
12// lifetime safety policy.
13//
14// The analysis is based on the concepts of "origins" and "loans" to track
15// pointer lifetimes and detect issues like use-after-free and dangling
16// pointers. See the RFC for more details:
17// https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
18//
19//===----------------------------------------------------------------------===//
20#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
21#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
22
29
30namespace clang::lifetimes {
31
32/// Enum to track the confidence level of a potential error.
33enum class Confidence : uint8_t {
35 Maybe, // Reported as a potential error (-Wlifetime-safety-strict)
36 Definite // Reported as a definite error (-Wlifetime-safety-permissive)
37};
38
39/// Enum to track functions visible across or within TU.
40enum class SuggestionScope {
41 CrossTU, // For suggestions on declarations visible across Translation Units.
42 IntraTU // For suggestions on definitions local to a Translation Unit.
43};
44
45/// Abstract interface for operations requiring Sema access.
46///
47/// This class exists to break a circular dependency: the LifetimeSafety
48/// analysis target cannot directly depend on clangSema (which would create the
49/// cycle: clangSema -> clangAnalysis -> clangAnalysisLifetimeSafety ->
50/// clangSema).
51///
52/// Instead, this interface is implemented in AnalysisBasedWarnings.cpp (part of
53/// clangSema), allowing the analysis to report diagnostics and modify the AST
54/// through Sema without introducing a circular dependency.
56public:
58 virtual ~LifetimeSafetySemaHelper() = default;
59
60 virtual void reportUseAfterFree(const Expr *IssueExpr, const Expr *UseExpr,
61 SourceLocation FreeLoc,
63
64 virtual void reportUseAfterReturn(const Expr *IssueExpr,
65 const Expr *ReturnExpr,
66 SourceLocation ExpiryLoc,
68
69 virtual void reportDanglingField(const Expr *IssueExpr,
70 const FieldDecl *Field,
71 SourceLocation ExpiryLoc) {}
72
73 // Suggests lifetime bound annotations for function paramters.
75 const ParmVarDecl *ParmToAnnotate,
76 const Expr *EscapeExpr) {}
77
78 // Reports misuse of [[clang::noescape]] when parameter escapes through return
79 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
80 const Expr *EscapeExpr) {}
81 // Reports misuse of [[clang::noescape]] when parameter escapes through field
82 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
83 const FieldDecl *EscapeField) {}
84
85 // Suggests lifetime bound annotations for implicit this.
87 const CXXMethodDecl *MD,
88 const Expr *EscapeExpr) {}
89
90 // Adds inferred lifetime bound attribute for implicit this to its
91 // TypeSourceInfo.
93};
94
95/// The main entry point for the analysis.
97 LifetimeSafetySemaHelper *SemaHelper,
98 LifetimeSafetyStats &Stats, bool CollectStats);
99
100namespace internal {
101
102void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM,
103 LifetimeSafetyStats &Stats);
104
105/// An object to hold the factories for immutable collections, ensuring
106/// that all created states share the same underlying memory management.
108 OriginLoanMap::Factory OriginMapFactory{/*canonicalize=*/false};
109 LoanSet::Factory LoanSetFactory{/*canonicalize=*/false};
110 LivenessMap::Factory LivenessMapFactory{/*canonicalize=*/false};
111};
112
113/// Running the lifetime safety analysis and querying its results. It
114/// encapsulates the various dataflow analyses.
116public:
118 LifetimeSafetySemaHelper *SemaHelper);
119
120 void run();
121
122 /// \note These are provided only for testing purposes.
124 return *LoanPropagation;
125 }
126 LiveOriginsAnalysis &getLiveOrigins() const { return *LiveOrigins; }
127 FactManager &getFactManager() { return *FactMgr; }
128
129private:
131 LifetimeSafetySemaHelper *SemaHelper;
132 LifetimeFactory Factory;
133 std::unique_ptr<FactManager> FactMgr;
134 std::unique_ptr<LiveOriginsAnalysis> LiveOrigins;
135 std::unique_ptr<LoanPropagationAnalysis> LoanPropagation;
136};
137} // namespace internal
138} // namespace clang::lifetimes
139
140#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3160
Represents a parameter to a function.
Definition Decl.h:1790
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
Abstract interface for operations requiring Sema access.
virtual void reportUseAfterFree(const Expr *IssueExpr, const Expr *UseExpr, SourceLocation FreeLoc, Confidence Confidence)
virtual void suggestLifetimeboundToImplicitThis(SuggestionScope Scope, const CXXMethodDecl *MD, const Expr *EscapeExpr)
virtual void reportDanglingField(const Expr *IssueExpr, const FieldDecl *Field, SourceLocation ExpiryLoc)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const FieldDecl *EscapeField)
virtual void suggestLifetimeboundToParmVar(SuggestionScope Scope, const ParmVarDecl *ParmToAnnotate, const Expr *EscapeExpr)
virtual void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr, SourceLocation ExpiryLoc, Confidence Confidence)
virtual void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const Expr *EscapeExpr)
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper)
LoanPropagationAnalysis & getLoanPropagation() const
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
SuggestionScope
Enum to track functions visible across or within TU.
Confidence
Enum to track the confidence level of a potential error.
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
An object to hold the factories for immutable collections, ensuring that all created states share the...