clang 22.0.0git
LifetimeSafety.cpp
Go to the documentation of this file.
1//===- LifetimeSafety.cpp - 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 implements the main LifetimeSafetyAnalysis class, which coordinates
10// the various components (fact generation, loan propagation, live origins
11// analysis, and checking) to detect lifetime safety violations in C++ code.
12//
13//===----------------------------------------------------------------------===//
15#include "clang/AST/Decl.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/Type.h"
26#include "clang/Analysis/CFG.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/TimeProfiler.h"
31#include <memory>
32
33namespace clang::lifetimes {
34namespace internal {
35
36#ifndef NDEBUG
37static void DebugOnlyFunction(AnalysisDeclContext &AC, const CFG &Cfg,
38 FactManager &FactMgr) {
39 std::string Name;
40 if (const Decl *D = AC.getDecl()) {
41 if (const auto *ND = dyn_cast<NamedDecl>(D))
42 Name = ND->getQualifiedNameAsString();
43 };
44 DEBUG_WITH_TYPE(Name.c_str(), AC.getDecl()->dumpColor());
45 DEBUG_WITH_TYPE(Name.c_str(), Cfg.dump(AC.getASTContext().getLangOpts(),
46 /*ShowColors=*/true));
47 DEBUG_WITH_TYPE(Name.c_str(), FactMgr.dump(Cfg, AC));
48}
49#endif
50
54
56 llvm::TimeTraceScope TimeProfile("LifetimeSafetyAnalysis");
57
58 const CFG &Cfg = *AC.getCFG();
59 DEBUG_WITH_TYPE("PrintCFG", Cfg.dump(AC.getASTContext().getLangOpts(),
60 /*ShowColors=*/true));
61
62 FactMgr = std::make_unique<FactManager>(AC, Cfg);
63
64 FactsGenerator FactGen(*FactMgr, AC);
65 FactGen.run();
66
67 DEBUG_WITH_TYPE("LifetimeFacts", FactMgr->dump(Cfg, AC));
68
69 // Debug print facts for a specific function using
70 // -debug-only=EnableFilterByFunctionName,YourFunctionNameFoo
71 DEBUG_WITH_TYPE("EnableFilterByFunctionName",
72 DebugOnlyFunction(AC, Cfg, *FactMgr));
73
74 /// TODO(opt): Consider optimizing individual blocks before running the
75 /// dataflow analysis.
76 /// 1. Expression Origins: These are assigned once and read at most once,
77 /// forming simple chains. These chains can be compressed into a single
78 /// assignment.
79 /// 2. Block-Local Loans: Origins of expressions are never read by other
80 /// blocks; only Decls are visible. Therefore, loans in a block that
81 /// never reach an Origin associated with a Decl can be safely dropped by
82 /// the analysis.
83 /// 3. Collapse ExpireFacts belonging to same source location into a single
84 /// Fact.
85 LoanPropagation = std::make_unique<LoanPropagationAnalysis>(
86 Cfg, AC, *FactMgr, Factory.OriginMapFactory, Factory.LoanSetFactory);
87
88 LiveOrigins = std::make_unique<LiveOriginsAnalysis>(
89 Cfg, AC, *FactMgr, Factory.LivenessMapFactory);
90 DEBUG_WITH_TYPE("LiveOrigins",
91 LiveOrigins->dump(llvm::dbgs(), FactMgr->getTestPoints()));
92
93 runLifetimeChecker(*LoanPropagation, *LiveOrigins, *FactMgr, AC, Reporter);
94}
95
97 LifetimeSafetyStats &Stats) {
98 Stmt *FunctionBody = AC.getBody();
99 if (FunctionBody == nullptr)
100 return;
101 OM.collectMissingOrigins(*FunctionBody, Stats);
102}
103} // namespace internal
104
106 LifetimeSafetyReporter *Reporter,
107 LifetimeSafetyStats &Stats, bool CollectStats) {
108 internal::LifetimeSafetyAnalysis Analysis(AC, Reporter);
109 Analysis.run();
110 if (CollectStats)
111 collectLifetimeStats(AC, Analysis.getFactManager().getOriginMgr(), Stats);
112}
113} // namespace clang::lifetimes
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
C Language Family Type Representation.
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
AnalysisDeclContext contains the context data for the function, method or block under analysis.
ASTContext & getASTContext() const
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1218
void dump(const LangOptions &LO, bool ShowColors) const
dump - A simple pretty printer of a CFG that outputs to stderr.
Definition CFG.cpp:6240
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void dumpColor() const
Stmt - This represents one statement.
Definition Stmt.h:85
void dump(const CFG &Cfg, AnalysisDeclContext &AC) const
Definition Facts.cpp:89
Running the lifetime safety analysis and querying its results.
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetyReporter *Reporter)
Manages the creation, storage, and retrieval of origins for pointer-like variables and expressions.
Definition Origins.h:125
void collectMissingOrigins(Stmt &FunctionBody, LifetimeSafetyStats &LSStats)
Collects statistics about expressions that lack associated origins.
Definition Origins.cpp:192
static void DebugOnlyFunction(AnalysisDeclContext &AC, const CFG &Cfg, FactManager &FactMgr)
void runLifetimeChecker(const LoanPropagationAnalysis &LoanPropagation, const LiveOriginsAnalysis &LiveOrigins, const FactManager &FactMgr, AnalysisDeclContext &ADC, LifetimeSafetyReporter *Reporter)
Runs the lifetime checker, which detects use-after-free errors by examining loan expiration points an...
Definition Checker.cpp:212
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetyReporter *Reporter, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
A structure to hold the statistics related to LifetimeAnalysis.