clang 24.0.0git
DataflowAnalysisContext.cpp
Go to the documentation of this file.
1//===-- DataflowAnalysisContext.cpp -----------------------------*- 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 a DataflowAnalysisContext class that owns objects that
10// encompass the state of a program and stores context that is used during
11// dataflow analysis.
12//
13//===----------------------------------------------------------------------===//
14
16#include "clang/AST/Type.h"
22#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/DenseSet.h"
24#include "llvm/ADT/SetOperations.h"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Path.h"
29#include "llvm/Support/Process.h"
30#include "llvm/Support/raw_ostream.h"
31#include <cassert>
32#include <memory>
33#include <stack>
34#include <string>
35#include <utility>
36#include <vector>
37
38namespace clang {
39namespace dataflow {
40
41FieldSet DataflowAnalysisContext::computeModeledFields(QualType Type) {
42 // During context-sensitive analysis, a struct may be allocated in one
43 // function, but its field accessed in a function lower in the stack than
44 // the allocation. Since we only collect fields used in the function where
45 // the allocation occurs, we can't apply that filter when performing
46 // context-sensitive analysis. But, this only applies to storage locations,
47 // since field access it not allowed to fail. In contrast, field *values*
48 // don't need this allowance, since the API allows for uninitialized fields.
49 if (Opts.ContextSensitiveOpts)
50 return getObjectFields(Type);
51
52 return llvm::set_intersection(getObjectFields(Type), ModeledFields);
53}
54
56 QualType CanonicalType = Type.getCanonicalType().getUnqualifiedType();
57 std::unique_ptr<FieldSet> &Fields = CachedModeledFields[CanonicalType];
58 if (Fields == nullptr)
59 Fields = std::make_unique<FieldSet>(computeModeledFields(CanonicalType));
60 return *Fields;
61}
62
63void DataflowAnalysisContext::addModeledFields(const FieldSet &Fields) {
64 ModeledFields.set_union(Fields);
65 CachedModeledFields.clear();
66}
67
69 if (!Type.isNull() && Type->isRecordType()) {
70 llvm::DenseMap<const ValueDecl *, StorageLocation *> FieldLocs;
71 for (const FieldDecl *Field : getModeledFields(Type))
72 if (Field->getType()->isReferenceType())
73 FieldLocs.insert({Field, nullptr});
74 else
75 FieldLocs.insert({Field, &createStorageLocation(
76 Field->getType().getNonReferenceType())});
77
79 for (const auto &Entry : getSyntheticFields(Type))
80 SyntheticFields.insert(
81 {Entry.getKey(),
82 &createStorageLocation(Entry.getValue().getNonReferenceType())});
83
84 return createRecordStorageLocation(Type, std::move(FieldLocs),
85 std::move(SyntheticFields));
86 }
88}
89
90// Returns the keys for a given `StringMap`.
91// Can't use `StringSet` as the return type as it doesn't support `operator==`.
92template <typename T>
93[[maybe_unused]] static llvm::DenseSet<llvm::StringRef>
94getKeys(const llvm::StringMap<T> &Map) {
95 return llvm::DenseSet<llvm::StringRef>(llvm::from_range, Map.keys());
96}
97
101 assert(Type->isRecordType());
102 assert(containsSameFields(getModeledFields(Type), FieldLocs));
103 assert(getKeys(getSyntheticFields(Type)) == getKeys(SyntheticFields));
104
105 RecordStorageLocationCreated = true;
106 return arena().create<RecordStorageLocation>(Type, std::move(FieldLocs),
107 std::move(SyntheticFields));
108}
109
112 if (auto *Loc = DeclToLoc.lookup(&D))
113 return *Loc;
115 DeclToLoc[&D] = &Loc;
116 return Loc;
117}
118
121 const Expr &CanonE = ignoreCFGOmittedNodes(E);
122
123 if (auto *Loc = ExprToLoc.lookup(&CanonE))
124 return *Loc;
125 auto &Loc = createStorageLocation(CanonE.getType());
126 ExprToLoc[&CanonE] = &Loc;
127 return Loc;
128}
129
132 auto CanonicalPointeeType =
133 PointeeType.isNull() ? PointeeType : PointeeType.getCanonicalType();
134 auto Res = NullPointerVals.try_emplace(CanonicalPointeeType, nullptr);
135 if (Res.second) {
136 auto &PointeeLoc = createStorageLocation(CanonicalPointeeType);
137 Res.first->second = &arena().create<PointerValue>(PointeeLoc);
138 }
139 return *Res.first->second;
140}
141
143 if (Invariant == nullptr)
144 Invariant = &Constraint;
145 else
146 Invariant = &arena().makeAnd(*Invariant, Constraint);
147}
148
150 Atom Token, const Formula &Constraint) {
151 auto Res = FlowConditionConstraints.try_emplace(Token, &Constraint);
152 if (!Res.second) {
153 Res.first->second =
154 &arena().makeAnd(*Res.first->second, Constraint);
155 }
156}
157
159 Atom ForkToken = arena().makeFlowConditionToken();
160 FlowConditionDeps[ForkToken].insert(Token);
161 addFlowConditionConstraint(ForkToken, arena().makeAtomRef(Token));
162 return ForkToken;
163}
164
165Atom
167 Atom SecondToken) {
169 auto &TokenDeps = FlowConditionDeps[Token];
170 TokenDeps.insert(FirstToken);
171 TokenDeps.insert(SecondToken);
173 arena().makeOr(arena().makeAtomRef(FirstToken),
174 arena().makeAtomRef(SecondToken)));
175 return Token;
176}
177
179 llvm::SetVector<const Formula *> Constraints) {
180 return S.solve(Constraints.getArrayRef());
181}
182
184 const Formula &F) {
185 if (F.isLiteral(true))
186 return true;
187
188 // Returns true if and only if truth assignment of the flow condition implies
189 // that `F` is also true. We prove whether or not this property holds by
190 // reducing the problem to satisfiability checking. In other words, we attempt
191 // to show that assuming `F` is false makes the constraints induced by the
192 // flow condition unsatisfiable.
193 llvm::SetVector<const Formula *> Constraints;
194 Constraints.insert(&arena().makeAtomRef(Token));
195 Constraints.insert(&arena().makeNot(F));
196 addTransitiveFlowConditionConstraints(Token, Constraints);
197 return isUnsatisfiable(std::move(Constraints));
198}
199
201 const Formula &F) {
202 if (F.isLiteral(false))
203 return false;
204
205 llvm::SetVector<const Formula *> Constraints;
206 Constraints.insert(&arena().makeAtomRef(Token));
207 Constraints.insert(&F);
208 addTransitiveFlowConditionConstraints(Token, Constraints);
209 return isSatisfiable(std::move(Constraints));
210}
211
213 const Formula &Val2) {
214 llvm::SetVector<const Formula *> Constraints;
215 Constraints.insert(&arena().makeNot(arena().makeEquals(Val1, Val2)));
216 return isUnsatisfiable(std::move(Constraints));
217}
218
219llvm::DenseSet<Atom> DataflowAnalysisContext::collectDependencies(
220 llvm::DenseSet<Atom> Tokens) const {
221 // Use a worklist algorithm, with `Remaining` holding the worklist and
222 // `Tokens` tracking which atoms have already been added to the worklist.
223 std::vector<Atom> Remaining(Tokens.begin(), Tokens.end());
224 while (!Remaining.empty()) {
225 Atom CurrentToken = Remaining.back();
226 Remaining.pop_back();
227 if (auto DepsIt = FlowConditionDeps.find(CurrentToken);
228 DepsIt != FlowConditionDeps.end())
229 for (Atom A : DepsIt->second)
230 if (Tokens.insert(A).second)
231 Remaining.push_back(A);
232 }
233
234 return Tokens;
235}
236
237void DataflowAnalysisContext::addTransitiveFlowConditionConstraints(
238 Atom Token, llvm::SetVector<const Formula *> &Constraints) {
239 llvm::DenseSet<Atom> AddedTokens;
240 std::vector<Atom> Remaining = {Token};
241
242 if (Invariant)
243 Constraints.insert(Invariant);
244 // Define all the flow conditions that might be referenced in constraints.
245 while (!Remaining.empty()) {
246 auto Token = Remaining.back();
247 Remaining.pop_back();
248 if (!AddedTokens.insert(Token).second)
249 continue;
250
251 auto ConstraintsIt = FlowConditionConstraints.find(Token);
252 if (ConstraintsIt == FlowConditionConstraints.end()) {
253 // The flow condition is unconstrained. Just add the atom directly, which
254 // is equivalent to asserting it is true.
255 Constraints.insert(&arena().makeAtomRef(Token));
256 } else {
257 // Bind flow condition token via `iff` to its set of constraints:
258 // FC <=> (C1 ^ C2 ^ ...), where Ci are constraints
259 Constraints.insert(&arena().makeEquals(arena().makeAtomRef(Token),
260 *ConstraintsIt->second));
261 }
262
263 if (auto DepsIt = FlowConditionDeps.find(Token);
264 DepsIt != FlowConditionDeps.end())
265 for (Atom A : DepsIt->second)
266 Remaining.push_back(A);
267 }
268}
269
270static void getReferencedAtoms(const Formula &F,
271 llvm::DenseSet<dataflow::Atom> &Refs) {
272 // Avoid recursion to avoid stack overflows from very large formulas.
273 // The shape of the tree structure for very large formulas is such that there
274 // are at most 2 children from any node, but there may be many generations.
275 std::stack<const Formula *> WorkList;
276 WorkList.push(&F);
277
278 while (!WorkList.empty()) {
279 const Formula *Current = WorkList.top();
280 WorkList.pop();
281 switch (Current->kind()) {
282 case Formula::AtomRef:
283 Refs.insert(Current->getAtom());
284 break;
285 case Formula::Literal:
286 break;
287 case Formula::Not:
288 WorkList.push(Current->operands()[0]);
289 break;
290 case Formula::And:
291 case Formula::Or:
292 case Formula::Implies:
293 case Formula::Equal:
294 ArrayRef<const Formula *> Operands = Current->operands();
295 WorkList.push(Operands[0]);
296 WorkList.push(Operands[1]);
297 break;
298 }
299 }
300}
301
303 llvm::DenseSet<dataflow::Atom> TargetTokens) const {
305
306 // Copy `Invariant` even if it is null, to initialize the field.
307 LC.Invariant = Invariant;
308 if (Invariant != nullptr)
309 getReferencedAtoms(*Invariant, TargetTokens);
310
311 llvm::DenseSet<dataflow::Atom> Dependencies =
312 collectDependencies(std::move(TargetTokens));
313
314 for (dataflow::Atom Token : Dependencies) {
315 // Only process the token if it is constrained. Unconstrained tokens don't
316 // have dependencies.
317 const Formula *Constraints = FlowConditionConstraints.lookup(Token);
318 if (Constraints == nullptr)
319 continue;
320 LC.TokenDefs[Token] = Constraints;
321
322 if (auto DepsIt = FlowConditionDeps.find(Token);
323 DepsIt != FlowConditionDeps.end())
324 LC.TokenDeps[Token] = DepsIt->second;
325 }
326
327 return LC;
328}
329
331 Invariant = LC.Invariant;
332 FlowConditionConstraints = std::move(LC.TokenDefs);
333 // TODO: The dependencies in `LC.TokenDeps` can be reconstructed from
334 // `LC.TokenDefs`. Give the caller the option to reconstruct, rather than
335 // providing them directly, to save caller space (memory/disk).
336 FlowConditionDeps = std::move(LC.TokenDeps);
337}
338
339static void printAtomList(const llvm::SmallVector<Atom> &Atoms,
340 llvm::raw_ostream &OS) {
341 OS << "(";
342 for (size_t i = 0; i < Atoms.size(); ++i) {
343 OS << Atoms[i];
344 if (i + 1 < Atoms.size())
345 OS << ", ";
346 }
347 OS << ")\n";
348}
349
351 llvm::raw_ostream &OS) {
352 llvm::SetVector<const Formula *> Constraints;
353 Constraints.insert(&arena().makeAtomRef(Token));
354 addTransitiveFlowConditionConstraints(Token, Constraints);
355
356 OS << "Flow condition token: " << Token << "\n";
358 llvm::SetVector<const Formula *> OriginalConstraints = Constraints;
359 simplifyConstraints(Constraints, arena(), &Info);
360 if (!Constraints.empty()) {
361 OS << "Constraints:\n";
362 for (const auto *Constraint : Constraints) {
363 Constraint->print(OS);
364 OS << "\n";
365 }
366 }
367 if (!Info.TrueAtoms.empty()) {
368 OS << "True atoms: ";
369 printAtomList(Info.TrueAtoms, OS);
370 }
371 if (!Info.FalseAtoms.empty()) {
372 OS << "False atoms: ";
373 printAtomList(Info.FalseAtoms, OS);
374 }
375 if (!Info.EquivalentAtoms.empty()) {
376 OS << "Equivalent atoms:\n";
378 printAtomList(Class, OS);
379 }
380
381 OS << "\nFlow condition constraints before simplification:\n";
382 for (const auto *Constraint : OriginalConstraints) {
383 Constraint->print(OS);
384 OS << "\n";
385 }
386}
387
388const AdornedCFG *
390 // Canonicalize the key:
391 F = F->getDefinition();
392 if (F == nullptr)
393 return nullptr;
394 auto It = FunctionContexts.find(F);
395 if (It != FunctionContexts.end())
396 return &It->second;
397
399 auto ACFG = AdornedCFG::build(*F);
400 // FIXME: Handle errors.
401 assert(ACFG);
402 auto Result = FunctionContexts.insert({F, std::move(*ACFG)});
403 return &Result.first->second;
404 }
405
406 return nullptr;
407}
408
409// CLANG_DATAFLOW_LOG=- writes a textual log to stderr. CLANG_DATAFLOW_LOG=<dir>
410// writes HTML logs under <dir>, one per analyzed function.
411static std::unique_ptr<Logger> makeLoggerFromEnv() {
412 std::optional<std::string> Env =
413 llvm::sys::Process::GetEnv("CLANG_DATAFLOW_LOG");
414 if (!Env || Env->empty())
415 return nullptr;
416 if (*Env == "-")
417 return Logger::textual(llvm::errs());
418
419 llvm::StringRef Dir = *Env;
420 if (auto EC = llvm::sys::fs::create_directories(Dir))
421 llvm::errs() << "Failed to create log dir: " << EC.message() << "\n";
422 // All analysis runs within a process will log to the same directory.
423 // Share a counter so they don't all overwrite each other's 0.html.
424 // (Don't share a logger, it's not threadsafe).
425 static std::atomic<unsigned> Counter = {0};
426 auto StreamFactory =
427 [Dir(Dir.str())]() mutable -> std::unique_ptr<llvm::raw_ostream> {
429 llvm::sys::path::append(File,
430 std::to_string(Counter.fetch_add(1)) + ".html");
431 std::error_code EC;
432 auto OS = std::make_unique<llvm::raw_fd_ostream>(File, EC);
433 if (EC) {
434 llvm::errs() << "Failed to create log " << File << ": " << EC.message()
435 << "\n";
436 return std::make_unique<llvm::raw_null_ostream>();
437 }
438 return OS;
439 };
440 return Logger::html(std::move(StreamFactory));
441}
442
444 Solver &S, std::unique_ptr<Solver> &&OwnedSolver, Options Opts)
445 : S(S), OwnedSolver(std::move(OwnedSolver)), A(std::make_unique<Arena>()),
446 Opts(Opts) {
447 // If CLANG_DATAFLOW_LOG is set, synthesize a logger. This is ugly but
448 // provides a uniform method for ad-hoc debugging dataflow-based tools.
449 if (Opts.Log == nullptr) {
450 LogOwner = makeLoggerFromEnv();
451 this->Opts.Log = LogOwner ? LogOwner.get() : &Logger::null();
452 }
453}
454
455DataflowAnalysisContext::~DataflowAnalysisContext() = default;
456
457} // namespace dataflow
458} // namespace clang
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
C Language Family Type Representation.
This represents one expression.
Definition Expr.h:114
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a function declaration or definition.
Definition Decl.h:2082
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2482
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8865
QualType getCanonicalType() const
Definition TypeBase.h:8732
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isRecordType() const
Definition TypeBase.h:9044
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Holds CFG with additional information derived from it that is needed to perform dataflow analysis.
Definition AdornedCFG.h:47
static llvm::Expected< AdornedCFG > build(const FunctionDecl &Func)
Builds an AdornedCFG from a FunctionDecl.
Atom makeFlowConditionToken()
Creates a fresh flow condition and returns a token that identifies it.
Definition Arena.h:124
const Formula & makeAnd(const Formula &LHS, const Formula &RHS)
Returns a formula for the conjunction of LHS and RHS.
Definition Arena.cpp:41
std::enable_if_t< std::is_base_of< StorageLocation, T >::value, T & > create(Args &&...args)
Creates a T (some subclass of StorageLocation), forwarding args to the constructor,...
Definition Arena.h:36
const AdornedCFG * getAdornedCFG(const FunctionDecl *F)
Returns the AdornedCFG registered for F, if any.
Atom joinFlowConditions(Atom FirstToken, Atom SecondToken)
Creates a new flow condition that represents the disjunction of the flow conditions identified by Fir...
void addFlowConditionConstraint(Atom Token, const Formula &Constraint)
Adds Constraint to the flow condition identified by Token.
Atom forkFlowCondition(Atom Token)
Creates a new flow condition with the same constraints as the flow condition identified by Token and ...
bool equivalentFormulas(const Formula &Val1, const Formula &Val2)
Returns true if Val1 is equivalent to Val2.
StorageLocation & getStableStorageLocation(const ValueDecl &D)
Returns a stable storage location for D.
DataflowAnalysisContext(std::unique_ptr< Solver > S, Options Opts=Options{ std::nullopt, nullptr, BoolModelKind::SAT})
Constructs a dataflow analysis context.
bool flowConditionImplies(Atom Token, const Formula &F)
Returns true if the constraints of the flow condition identified by Token imply that F is true.
Solver::Result querySolver(llvm::SetVector< const Formula * > Constraints)
Returns the outcome of satisfiability checking on Constraints.
bool flowConditionAllows(Atom Token, const Formula &F)
Returns true if the constraints of the flow condition identified by Token still allow F to be true.
const FieldSet & getModeledFields(QualType Type)
Returns the fields of Type, limited to the set of fields modeled by this context.
PointerValue & getOrCreateNullPointerValue(QualType PointeeType)
Returns a pointer value that represents a null pointer.
void addInvariant(const Formula &Constraint)
Adds Constraint to current and future flow conditions in this context.
llvm::StringMap< QualType > getSyntheticFields(QualType Type)
Returns the names and types of the synthetic fields for the given record type.
StorageLocation & createStorageLocation(QualType Type)
Returns a new storage location appropriate for Type.
SimpleLogicalContext exportLogicalContext(llvm::DenseSet< dataflow::Atom > TargetTokens) const
Export the logical-context portions of AC, limited to the given target flow-condition tokens.
LLVM_DUMP_METHOD void dumpFlowCondition(Atom Token, llvm::raw_ostream &OS=llvm::dbgs())
void initLogicalContext(SimpleLogicalContext LC)
Initializes this context's "logical" components with LC.
RecordStorageLocation & createRecordStorageLocation(QualType Type, RecordStorageLocation::FieldToLoc FieldLocs, RecordStorageLocation::SyntheticFieldMap SyntheticFields)
Creates a RecordStorageLocation for the given type and with the given fields.
ArrayRef< const Formula * > operands() const
Definition Formula.h:82
bool isLiteral(bool b) const
Definition Formula.h:78
Atom getAtom() const
Definition Formula.h:68
@ Equal
True if LHS is false or RHS is true.
Definition Formula.h:64
@ Implies
True if either LHS or RHS is true.
Definition Formula.h:63
@ AtomRef
A reference to an atomic boolean variable.
Definition Formula.h:54
@ Literal
Constant true or false.
Definition Formula.h:56
@ Or
True if LHS and RHS are both true.
Definition Formula.h:62
@ And
True if its only operand is false.
Definition Formula.h:61
Kind kind() const
Definition Formula.h:66
static std::unique_ptr< Logger > textual(llvm::raw_ostream &)
A logger that simply writes messages to the specified ostream in real time.
Definition Logger.cpp:107
static std::unique_ptr< Logger > html(std::function< std::unique_ptr< llvm::raw_ostream >()>)
A logger that builds an HTML UI to inspect the analysis results.
Models a symbolic pointer. Specifically, any value of type T*.
Definition Value.h:170
A storage location for a record (struct, class, or union).
llvm::DenseMap< const ValueDecl *, StorageLocation * > FieldToLoc
llvm::StringMap< StorageLocation * > SyntheticFieldMap
A storage location that is not subdivided further for the purposes of abstract interpretation.
Base class for elements of the local variable store and of the heap.
static void getReferencedAtoms(const Formula &F, llvm::DenseSet< dataflow::Atom > &Refs)
Atom
Identifies an atomic boolean variable such as "V1".
Definition Formula.h:34
static void printAtomList(const llvm::SmallVector< Atom > &Atoms, llvm::raw_ostream &OS)
void simplifyConstraints(llvm::SetVector< const Formula * > &Constraints, Arena &arena, SimplifyConstraintsInfo *Info=nullptr)
Simplifies a set of constraints (implicitly connected by "and") in a way that does not change satisfi...
static std::unique_ptr< Logger > makeLoggerFromEnv()
const Expr & ignoreCFGOmittedNodes(const Expr &E)
Skip past nodes that the CFG does not emit.
Definition ASTOps.cpp:35
FieldSet getObjectFields(QualType Type)
Returns the set of all fields in the type.
Definition ASTOps.cpp:74
static llvm::DenseSet< llvm::StringRef > getKeys(const llvm::StringMap< T > &Map)
bool containsSameFields(const FieldSet &Fields, const RecordStorageLocation::FieldToLoc &FieldLocs)
Returns whether Fields and FieldLocs contain the same fields.
Definition ASTOps.cpp:80
llvm::SmallSetVector< const FieldDecl *, 4 > FieldSet
A set of FieldDecl *.
Definition ASTOps.h:42
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:558
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6259
A simple representation of essential elements of the logical context used in environments.
llvm::DenseMap< Atom, const Formula * > TokenDefs
llvm::DenseMap< Atom, llvm::DenseSet< Atom > > TokenDeps
Information on the way a set of constraints was simplified.
llvm::SmallVector< Atom > TrueAtoms
Atoms that the original constraints imply must be true.
llvm::SmallVector< llvm::SmallVector< Atom > > EquivalentAtoms
List of equivalence classes of atoms.
llvm::SmallVector< Atom > FalseAtoms
Atoms that the original constraints imply must be false.