2021-12-29 11:31:02 +00:00
|
|
|
//===-- DataflowEnvironment.cpp ---------------------------------*- C++ -*-===//
|
|
|
|
//
|
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file defines an Environment class that is used by dataflow analyses
|
|
|
|
// that run over Control-Flow Graphs (CFGs) to keep track of the state of the
|
|
|
|
// program at given program points.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
|
|
|
|
#include "clang/AST/Decl.h"
|
2022-01-11 12:15:53 +00:00
|
|
|
#include "clang/AST/DeclCXX.h"
|
2024-04-11 08:20:35 +02:00
|
|
|
#include "clang/AST/RecursiveASTVisitor.h"
|
2021-12-29 11:31:02 +00:00
|
|
|
#include "clang/AST/Type.h"
|
2024-04-16 14:46:05 -04:00
|
|
|
#include "clang/Analysis/FlowSensitive/ASTOps.h"
|
2021-12-29 11:31:02 +00:00
|
|
|
#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
|
|
|
|
#include "clang/Analysis/FlowSensitive/Value.h"
|
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/DenseSet.h"
|
2023-07-11 12:48:30 +02:00
|
|
|
#include "llvm/ADT/MapVector.h"
|
2022-08-16 18:27:41 +02:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2024-04-19 09:39:52 +02:00
|
|
|
#include "llvm/ADT/ScopeExit.h"
|
2022-01-04 13:47:14 +00:00
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
2022-02-23 13:38:51 +00:00
|
|
|
#include <cassert>
|
2021-12-29 11:31:02 +00:00
|
|
|
#include <utility>
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
#define DEBUG_TYPE "dataflow"
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
namespace clang {
|
|
|
|
namespace dataflow {
|
|
|
|
|
2022-02-24 20:02:00 +00:00
|
|
|
// FIXME: convert these to parameters of the analysis or environment. Current
|
|
|
|
// settings have been experimentaly validated, but only for a particular
|
|
|
|
// analysis.
|
|
|
|
static constexpr int MaxCompositeValueDepth = 3;
|
|
|
|
static constexpr int MaxCompositeValueSize = 1000;
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
/// Returns a map consisting of key-value entries that are present in both maps.
|
2023-11-22 16:34:24 +01:00
|
|
|
static llvm::DenseMap<const ValueDecl *, StorageLocation *> intersectDeclToLoc(
|
|
|
|
const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc1,
|
|
|
|
const llvm::DenseMap<const ValueDecl *, StorageLocation *> &DeclToLoc2) {
|
|
|
|
llvm::DenseMap<const ValueDecl *, StorageLocation *> Result;
|
|
|
|
for (auto &Entry : DeclToLoc1) {
|
|
|
|
auto It = DeclToLoc2.find(Entry.first);
|
|
|
|
if (It != DeclToLoc2.end() && Entry.second == It->second)
|
2021-12-29 11:31:02 +00:00
|
|
|
Result.insert({Entry.first, Entry.second});
|
|
|
|
}
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
[clang][nullability] Don't discard expression state before end of full-expression. (#82611)
In https://github.com/llvm/llvm-project/pull/72985, I made a change to
discard
expression state (`ExprToLoc` and `ExprToVal`) at the beginning of each
basic
block. I did so with the claim that "we never need to access entries
from these
maps outside of the current basic block", noting that there are
exceptions to
this claim when control flow happens inside a full-expression (the
operands of
`&&`, `||`, and the conditional operator live in different basic blocks
than the
operator itself) but that we already have a mechanism for retrieving the
values
of these operands from the environment for the block they are computed
in.
It turns out, however, that the operands of these operators aren't the
only
expressions whose values can be accessed from a different basic block;
when
control flow happens within a full-expression, that control flow can be
"interposed" between an expression and its parent. Here is an example:
```cxx
void f(int*, int);
bool cond();
void target() {
int i = 0;
f(&i, cond() ? 1 : 0);
}
```
([godbolt](https://godbolt.org/z/hrbj1Mj3o))
In the CFG[^1] , note how the expression for `&i` is computed in block
B4,
but the parent of this expression (the `CallExpr`) is located in block
B1.
The the argument expression `&i` and the `CallExpr` are essentially
"torn apart"
into different basic blocks by the conditional operator in the second
argument.
In other words, the edge between the `CallExpr` and its argument `&i`
straddles
the boundary between two blocks.
I used to think that this scenario -- where an edge between an
expression and
one of its children straddles a block boundary -- could only happen
between the
expression that triggers the control flow (`&&`, `||`, or the
conditional
operator) and its children, but the example above shows that other
expressions
can be affected as well; the control flow is still triggered by `&&`,
`||` or
the conditional operator, but the expressions affected lie outside these
operators.
Discarding expression state too soon is harmful. For example, an
analysis that
checks the arguments of the `CallExpr` above would not be able to
retrieve a
value for the `&i` argument.
This patch therefore ensures that we don't discard expression state
before the
end of a full-expression. In other cases -- when the evaluation of a
full-expression is complete -- we still want to discard expression state
for the
reasons explained in https://github.com/llvm/llvm-project/pull/72985
(avoid
performing joins on boolean values that are no longer needed, which
unnecessarily extends the flow condition; improve debuggability by
removing
clutter from the expression state).
The impact on performance from this change is about a 1% slowdown in the
Crubit nullability check benchmarks:
```
name old cpu/op new cpu/op delta
BM_PointerAnalysisCopyPointer 71.9µs ± 1% 71.9µs ± 2% ~ (p=0.987 n=15+20)
BM_PointerAnalysisIntLoop 190µs ± 1% 192µs ± 2% +1.06% (p=0.000 n=14+16)
BM_PointerAnalysisPointerLoop 325µs ± 5% 324µs ± 4% ~ (p=0.496 n=18+20)
BM_PointerAnalysisBranch 193µs ± 0% 192µs ± 4% ~ (p=0.488 n=14+18)
BM_PointerAnalysisLoopAndBranch 521µs ± 1% 525µs ± 3% +0.94% (p=0.017 n=18+19)
BM_PointerAnalysisTwoLoops 337µs ± 1% 341µs ± 3% +1.19% (p=0.004 n=17+19)
BM_PointerAnalysisJoinFilePath 1.62ms ± 2% 1.64ms ± 3% +0.92% (p=0.021 n=20+20)
BM_PointerAnalysisCallInLoop 1.14ms ± 1% 1.15ms ± 4% ~ (p=0.135 n=16+18)
```
[^1]:
```
[B5 (ENTRY)]
Succs (1): B4
[B1]
1: [B4.9] ? [B2.1] : [B3.1]
2: [B4.4]([B4.6], [B1.1])
Preds (2): B2 B3
Succs (1): B0
[B2]
1: 1
Preds (1): B4
Succs (1): B1
[B3]
1: 0
Preds (1): B4
Succs (1): B1
[B4]
1: 0
2: int i = 0;
3: f
4: [B4.3] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int *, int))
5: i
6: &[B4.5]
7: cond
8: [B4.7] (ImplicitCastExpr, FunctionToPointerDecay, _Bool (*)(void))
9: [B4.8]()
T: [B4.9] ? ... : ...
Preds (1): B5
Succs (2): B2 B3
[B0 (EXIT)]
Preds (1): B1
```
2024-03-07 13:31:23 +01:00
|
|
|
// Performs a join on either `ExprToLoc` or `ExprToVal`.
|
|
|
|
// The maps must be consistent in the sense that any entries for the same
|
|
|
|
// expression must map to the same location / value. This is the case if we are
|
|
|
|
// performing a join for control flow within a full-expression (which is the
|
|
|
|
// only case when this function should be used).
|
|
|
|
template <typename MapT> MapT joinExprMaps(const MapT &Map1, const MapT &Map2) {
|
|
|
|
MapT Result = Map1;
|
|
|
|
|
|
|
|
for (const auto &Entry : Map2) {
|
|
|
|
[[maybe_unused]] auto [It, Inserted] = Result.insert(Entry);
|
|
|
|
// If there was an existing entry, its value should be the same as for the
|
|
|
|
// entry we were trying to insert.
|
|
|
|
assert(It->second == Entry.second);
|
|
|
|
}
|
|
|
|
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2023-09-01 12:53:58 +00:00
|
|
|
// Whether to consider equivalent two values with an unknown relation.
|
|
|
|
//
|
|
|
|
// FIXME: this function is a hack enabling unsoundness to support
|
|
|
|
// convergence. Once we have widening support for the reference/pointer and
|
|
|
|
// struct built-in models, this should be unconditionally `false` (and inlined
|
|
|
|
// as such at its call sites).
|
|
|
|
static bool equateUnknownValues(Value::Kind K) {
|
|
|
|
switch (K) {
|
|
|
|
case Value::Kind::Integer:
|
|
|
|
case Value::Kind::Pointer:
|
|
|
|
return true;
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-03 00:36:58 +00:00
|
|
|
static bool compareDistinctValues(QualType Type, Value &Val1,
|
|
|
|
const Environment &Env1, Value &Val2,
|
|
|
|
const Environment &Env2,
|
|
|
|
Environment::ValueModel &Model) {
|
|
|
|
// Note: Potentially costly, but, for booleans, we could check whether both
|
|
|
|
// can be proven equivalent in their respective environments.
|
|
|
|
|
|
|
|
// FIXME: move the reference/pointers logic from `areEquivalentValues` to here
|
|
|
|
// and implement separate, join/widen specific handling for
|
|
|
|
// reference/pointers.
|
|
|
|
switch (Model.compare(Type, Val1, Env1, Val2, Env2)) {
|
|
|
|
case ComparisonResult::Same:
|
|
|
|
return true;
|
|
|
|
case ComparisonResult::Different:
|
|
|
|
return false;
|
|
|
|
case ComparisonResult::Unknown:
|
2023-09-01 12:53:58 +00:00
|
|
|
return equateUnknownValues(Val1.getKind());
|
2022-11-03 00:36:58 +00:00
|
|
|
}
|
|
|
|
llvm_unreachable("All cases covered in switch");
|
|
|
|
}
|
|
|
|
|
2024-02-06 15:38:56 -05:00
|
|
|
/// Attempts to join distinct values `Val1` and `Val2` in `Env1` and `Env2`,
|
|
|
|
/// respectively, of the same type `Type`. Joining generally produces a single
|
2022-03-28 15:38:17 +00:00
|
|
|
/// value that (soundly) approximates the two inputs, although the actual
|
|
|
|
/// meaning depends on `Model`.
|
2024-02-06 15:38:56 -05:00
|
|
|
static Value *joinDistinctValues(QualType Type, Value &Val1,
|
|
|
|
const Environment &Env1, Value &Val2,
|
|
|
|
const Environment &Env2,
|
|
|
|
Environment &JoinedEnv,
|
|
|
|
Environment::ValueModel &Model) {
|
2022-03-28 15:38:17 +00:00
|
|
|
// Join distinct boolean values preserving information about the constraints
|
2022-04-25 15:23:42 +00:00
|
|
|
// in the respective path conditions.
|
2023-01-13 18:33:52 +00:00
|
|
|
if (isa<BoolValue>(&Val1) && isa<BoolValue>(&Val2)) {
|
|
|
|
// FIXME: Checking both values should be unnecessary, since they should have
|
|
|
|
// a consistent shape. However, right now we can end up with BoolValue's in
|
|
|
|
// integer-typed variables due to our incorrect handling of
|
|
|
|
// boolean-to-integer casts (we just propagate the BoolValue to the result
|
|
|
|
// of the cast). So, a join can encounter an integer in one branch but a
|
|
|
|
// bool in the other.
|
|
|
|
// For example:
|
|
|
|
// ```
|
2022-12-29 14:40:40 +08:00
|
|
|
// std::optional<bool> o;
|
|
|
|
// int x;
|
2023-01-13 18:33:52 +00:00
|
|
|
// if (o.has_value())
|
2022-12-29 14:40:40 +08:00
|
|
|
// x = o.value();
|
2023-01-13 18:33:52 +00:00
|
|
|
// ```
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
auto &Expr1 = cast<BoolValue>(Val1).formula();
|
|
|
|
auto &Expr2 = cast<BoolValue>(Val2).formula();
|
2024-02-06 15:38:56 -05:00
|
|
|
auto &A = JoinedEnv.arena();
|
|
|
|
auto &JoinedVal = A.makeAtomRef(A.makeAtom());
|
|
|
|
JoinedEnv.assume(
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
A.makeOr(A.makeAnd(A.makeAtomRef(Env1.getFlowConditionToken()),
|
2024-02-06 15:38:56 -05:00
|
|
|
A.makeEquals(JoinedVal, Expr1)),
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
A.makeAnd(A.makeAtomRef(Env2.getFlowConditionToken()),
|
2024-02-06 15:38:56 -05:00
|
|
|
A.makeEquals(JoinedVal, Expr2))));
|
|
|
|
return &A.makeBoolValue(JoinedVal);
|
2022-03-28 15:38:17 +00:00
|
|
|
}
|
|
|
|
|
2024-04-19 09:39:52 +02:00
|
|
|
Value *JoinedVal = JoinedEnv.createValue(Type);
|
2024-02-06 15:38:56 -05:00
|
|
|
if (JoinedVal)
|
|
|
|
Model.join(Type, Val1, Env1, Val2, Env2, *JoinedVal, JoinedEnv);
|
2022-03-28 15:38:17 +00:00
|
|
|
|
2024-02-06 15:38:56 -05:00
|
|
|
return JoinedVal;
|
2022-03-28 15:38:17 +00:00
|
|
|
}
|
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
static WidenResult widenDistinctValues(QualType Type, Value &Prev,
|
|
|
|
const Environment &PrevEnv,
|
|
|
|
Value &Current, Environment &CurrentEnv,
|
|
|
|
Environment::ValueModel &Model) {
|
2022-11-03 00:36:58 +00:00
|
|
|
// Boolean-model widening.
|
2023-11-27 14:55:49 +01:00
|
|
|
if (auto *PrevBool = dyn_cast<BoolValue>(&Prev)) {
|
2022-11-03 00:36:58 +00:00
|
|
|
if (isa<TopBoolValue>(Prev))
|
2024-04-04 08:39:51 -04:00
|
|
|
// Safe to return `Prev` here, because Top is never dependent on the
|
|
|
|
// environment.
|
|
|
|
return {&Prev, LatticeEffect::Unchanged};
|
2023-11-27 14:55:49 +01:00
|
|
|
|
|
|
|
// We may need to widen to Top, but before we do so, check whether both
|
|
|
|
// values are implied to be either true or false in the current environment.
|
|
|
|
// In that case, we can simply return a literal instead.
|
|
|
|
auto &CurBool = cast<BoolValue>(Current);
|
|
|
|
bool TruePrev = PrevEnv.proves(PrevBool->formula());
|
|
|
|
bool TrueCur = CurrentEnv.proves(CurBool.formula());
|
|
|
|
if (TruePrev && TrueCur)
|
2024-04-04 08:39:51 -04:00
|
|
|
return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged};
|
2023-11-27 14:55:49 +01:00
|
|
|
if (!TruePrev && !TrueCur &&
|
|
|
|
PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool->formula())) &&
|
|
|
|
CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula())))
|
2024-04-04 08:39:51 -04:00
|
|
|
return {&CurrentEnv.getBoolLiteralValue(false), LatticeEffect::Unchanged};
|
2023-11-27 14:55:49 +01:00
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
return {&CurrentEnv.makeTopBoolValue(), LatticeEffect::Changed};
|
2022-11-03 00:36:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME: Add other built-in model widening.
|
|
|
|
|
|
|
|
// Custom-model widening.
|
2024-04-04 08:39:51 -04:00
|
|
|
if (auto Result = Model.widen(Type, Prev, PrevEnv, Current, CurrentEnv))
|
|
|
|
return *Result;
|
2022-11-03 00:36:58 +00:00
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
return {&Current, equateUnknownValues(Prev.getKind())
|
|
|
|
? LatticeEffect::Unchanged
|
|
|
|
: LatticeEffect::Changed};
|
2022-11-03 00:36:58 +00:00
|
|
|
}
|
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
// Returns whether the values in `Map1` and `Map2` compare equal for those
|
|
|
|
// keys that `Map1` and `Map2` have in common.
|
|
|
|
template <typename Key>
|
|
|
|
bool compareKeyToValueMaps(const llvm::MapVector<Key, Value *> &Map1,
|
|
|
|
const llvm::MapVector<Key, Value *> &Map2,
|
|
|
|
const Environment &Env1, const Environment &Env2,
|
|
|
|
Environment::ValueModel &Model) {
|
|
|
|
for (auto &Entry : Map1) {
|
|
|
|
Key K = Entry.first;
|
|
|
|
assert(K != nullptr);
|
|
|
|
|
|
|
|
Value *Val = Entry.second;
|
|
|
|
assert(Val != nullptr);
|
|
|
|
|
|
|
|
auto It = Map2.find(K);
|
|
|
|
if (It == Map2.end())
|
|
|
|
continue;
|
|
|
|
assert(It->second != nullptr);
|
|
|
|
|
|
|
|
if (!areEquivalentValues(*Val, *It->second) &&
|
|
|
|
!compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
|
|
|
|
Model))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-11-22 16:34:24 +01:00
|
|
|
// Perform a join on two `LocToVal` maps.
|
|
|
|
static llvm::MapVector<const StorageLocation *, Value *>
|
|
|
|
joinLocToVal(const llvm::MapVector<const StorageLocation *, Value *> &LocToVal,
|
|
|
|
const llvm::MapVector<const StorageLocation *, Value *> &LocToVal2,
|
|
|
|
const Environment &Env1, const Environment &Env2,
|
|
|
|
Environment &JoinedEnv, Environment::ValueModel &Model) {
|
|
|
|
llvm::MapVector<const StorageLocation *, Value *> Result;
|
|
|
|
for (auto &Entry : LocToVal) {
|
|
|
|
const StorageLocation *Loc = Entry.first;
|
|
|
|
assert(Loc != nullptr);
|
2023-08-28 11:50:03 +00:00
|
|
|
|
|
|
|
Value *Val = Entry.second;
|
|
|
|
assert(Val != nullptr);
|
|
|
|
|
2023-11-22 16:34:24 +01:00
|
|
|
auto It = LocToVal2.find(Loc);
|
|
|
|
if (It == LocToVal2.end())
|
2023-08-28 11:50:03 +00:00
|
|
|
continue;
|
|
|
|
assert(It->second != nullptr);
|
|
|
|
|
2024-04-22 09:35:29 +02:00
|
|
|
if (areEquivalentValues(*Val, *It->second)) {
|
|
|
|
Result.insert({Loc, Val});
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Value *JoinedVal = joinDistinctValues(
|
|
|
|
Loc->getType(), *Val, Env1, *It->second, Env2, JoinedEnv, Model)) {
|
2024-02-06 15:38:56 -05:00
|
|
|
Result.insert({Loc, JoinedVal});
|
2023-08-28 11:50:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-22 16:34:24 +01:00
|
|
|
return Result;
|
2023-08-28 11:50:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either
|
|
|
|
// `const StorageLocation *` or `const Expr *`.
|
|
|
|
template <typename Key>
|
|
|
|
llvm::MapVector<Key, Value *>
|
|
|
|
widenKeyToValueMap(const llvm::MapVector<Key, Value *> &CurMap,
|
|
|
|
const llvm::MapVector<Key, Value *> &PrevMap,
|
|
|
|
Environment &CurEnv, const Environment &PrevEnv,
|
2024-04-04 08:39:51 -04:00
|
|
|
Environment::ValueModel &Model, LatticeEffect &Effect) {
|
2023-08-28 11:50:03 +00:00
|
|
|
llvm::MapVector<Key, Value *> WidenedMap;
|
|
|
|
for (auto &Entry : CurMap) {
|
|
|
|
Key K = Entry.first;
|
|
|
|
assert(K != nullptr);
|
|
|
|
|
|
|
|
Value *Val = Entry.second;
|
|
|
|
assert(Val != nullptr);
|
|
|
|
|
|
|
|
auto PrevIt = PrevMap.find(K);
|
|
|
|
if (PrevIt == PrevMap.end())
|
|
|
|
continue;
|
|
|
|
assert(PrevIt->second != nullptr);
|
|
|
|
|
|
|
|
if (areEquivalentValues(*Val, *PrevIt->second)) {
|
|
|
|
WidenedMap.insert({K, Val});
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
auto [WidenedVal, ValEffect] = widenDistinctValues(
|
|
|
|
K->getType(), *PrevIt->second, PrevEnv, *Val, CurEnv, Model);
|
|
|
|
WidenedMap.insert({K, WidenedVal});
|
|
|
|
if (ValEffect == LatticeEffect::Changed)
|
|
|
|
Effect = LatticeEffect::Changed;
|
2023-08-28 11:50:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return WidenedMap;
|
|
|
|
}
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
namespace {
|
|
|
|
|
|
|
|
// Visitor that builds a map from record prvalues to result objects.
|
|
|
|
// This traverses the body of the function to be analyzed; for each result
|
|
|
|
// object that it encounters, it propagates the storage location of the result
|
|
|
|
// object to all record prvalues that can initialize it.
|
|
|
|
class ResultObjectVisitor : public RecursiveASTVisitor<ResultObjectVisitor> {
|
|
|
|
public:
|
|
|
|
// `ResultObjectMap` will be filled with a map from record prvalues to result
|
|
|
|
// object. If the function being analyzed returns a record by value,
|
|
|
|
// `LocForRecordReturnVal` is the location to which this record should be
|
|
|
|
// written; otherwise, it is null.
|
|
|
|
explicit ResultObjectVisitor(
|
|
|
|
llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap,
|
|
|
|
RecordStorageLocation *LocForRecordReturnVal,
|
|
|
|
DataflowAnalysisContext &DACtx)
|
|
|
|
: ResultObjectMap(ResultObjectMap),
|
|
|
|
LocForRecordReturnVal(LocForRecordReturnVal), DACtx(DACtx) {}
|
|
|
|
|
|
|
|
bool shouldVisitImplicitCode() { return true; }
|
|
|
|
|
|
|
|
bool shouldVisitLambdaBody() const { return false; }
|
|
|
|
|
|
|
|
// Traverse all member and base initializers of `Ctor`. This function is not
|
|
|
|
// called by `RecursiveASTVisitor`; it should be called manually if we are
|
|
|
|
// analyzing a constructor. `ThisPointeeLoc` is the storage location that
|
|
|
|
// `this` points to.
|
|
|
|
void TraverseConstructorInits(const CXXConstructorDecl *Ctor,
|
|
|
|
RecordStorageLocation *ThisPointeeLoc) {
|
|
|
|
assert(ThisPointeeLoc != nullptr);
|
|
|
|
for (const CXXCtorInitializer *Init : Ctor->inits()) {
|
|
|
|
Expr *InitExpr = Init->getInit();
|
|
|
|
if (FieldDecl *Field = Init->getMember();
|
|
|
|
Field != nullptr && Field->getType()->isRecordType()) {
|
|
|
|
PropagateResultObject(InitExpr, cast<RecordStorageLocation>(
|
|
|
|
ThisPointeeLoc->getChild(*Field)));
|
|
|
|
} else if (Init->getBaseClass()) {
|
|
|
|
PropagateResultObject(InitExpr, ThisPointeeLoc);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure that any result objects within `InitExpr` (e.g. temporaries)
|
|
|
|
// are also propagated to the prvalues that initialize them.
|
|
|
|
TraverseStmt(InitExpr);
|
|
|
|
|
|
|
|
// If this is a `CXXDefaultInitExpr`, also propagate any result objects
|
|
|
|
// within the default expression.
|
|
|
|
if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(InitExpr))
|
|
|
|
TraverseStmt(DefaultInit->getExpr());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TraverseBindingDecl(BindingDecl *BD) {
|
|
|
|
// `RecursiveASTVisitor` doesn't traverse holding variables for
|
|
|
|
// `BindingDecl`s by itself, so we need to tell it to.
|
|
|
|
if (VarDecl *HoldingVar = BD->getHoldingVar())
|
|
|
|
TraverseDecl(HoldingVar);
|
|
|
|
return RecursiveASTVisitor<ResultObjectVisitor>::TraverseBindingDecl(BD);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool VisitVarDecl(VarDecl *VD) {
|
|
|
|
if (VD->getType()->isRecordType() && VD->hasInit())
|
|
|
|
PropagateResultObject(
|
|
|
|
VD->getInit(),
|
|
|
|
&cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*VD)));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE) {
|
|
|
|
if (MTE->getType()->isRecordType())
|
|
|
|
PropagateResultObject(
|
|
|
|
MTE->getSubExpr(),
|
|
|
|
&cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*MTE)));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool VisitReturnStmt(ReturnStmt *Return) {
|
|
|
|
Expr *RetValue = Return->getRetValue();
|
|
|
|
if (RetValue != nullptr && RetValue->getType()->isRecordType() &&
|
|
|
|
RetValue->isPRValue())
|
|
|
|
PropagateResultObject(RetValue, LocForRecordReturnVal);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool VisitExpr(Expr *E) {
|
|
|
|
// Clang's AST can have record-type prvalues without a result object -- for
|
|
|
|
// example as full-expressions contained in a compound statement or as
|
|
|
|
// arguments of call expressions. We notice this if we get here and a
|
|
|
|
// storage location has not yet been associated with `E`. In this case,
|
|
|
|
// treat this as if it was a `MaterializeTemporaryExpr`.
|
|
|
|
if (E->isPRValue() && E->getType()->isRecordType() &&
|
|
|
|
!ResultObjectMap.contains(E))
|
|
|
|
PropagateResultObject(
|
|
|
|
E, &cast<RecordStorageLocation>(DACtx.getStableStorageLocation(*E)));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-04-19 09:06:13 +02:00
|
|
|
void
|
|
|
|
PropagateResultObjectToRecordInitList(const RecordInitListHelper &InitList,
|
|
|
|
RecordStorageLocation *Loc) {
|
|
|
|
for (auto [Base, Init] : InitList.base_inits()) {
|
|
|
|
assert(Base->getType().getCanonicalType() ==
|
|
|
|
Init->getType().getCanonicalType());
|
|
|
|
|
|
|
|
// Storage location for the base class is the same as that of the
|
|
|
|
// derived class because we "flatten" the object hierarchy and put all
|
|
|
|
// fields in `RecordStorageLocation` of the derived class.
|
|
|
|
PropagateResultObject(Init, Loc);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (auto [Field, Init] : InitList.field_inits()) {
|
|
|
|
// Fields of non-record type are handled in
|
|
|
|
// `TransferVisitor::VisitInitListExpr()`.
|
|
|
|
if (Field->getType()->isRecordType())
|
2024-04-19 10:12:57 +02:00
|
|
|
PropagateResultObject(
|
|
|
|
Init, cast<RecordStorageLocation>(Loc->getChild(*Field)));
|
2024-04-19 09:06:13 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
// Assigns `Loc` as the result object location of `E`, then propagates the
|
|
|
|
// location to all lower-level prvalues that initialize the same object as
|
|
|
|
// `E` (or one of its base classes or member variables).
|
|
|
|
void PropagateResultObject(Expr *E, RecordStorageLocation *Loc) {
|
|
|
|
if (!E->isPRValue() || !E->getType()->isRecordType()) {
|
|
|
|
assert(false);
|
|
|
|
// Ensure we don't propagate the result object if we hit this in a
|
|
|
|
// release build.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
ResultObjectMap[E] = Loc;
|
|
|
|
|
|
|
|
// The following AST node kinds are "original initializers": They are the
|
|
|
|
// lowest-level AST node that initializes a given object, and nothing
|
|
|
|
// below them can initialize the same object (or part of it).
|
2024-04-18 09:23:03 +02:00
|
|
|
if (isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || isa<LambdaExpr>(E) ||
|
|
|
|
isa<CXXDefaultArgExpr>(E) || isa<CXXDefaultInitExpr>(E) ||
|
|
|
|
isa<CXXStdInitializerListExpr>(E) ||
|
|
|
|
// We treat `BuiltinBitCastExpr` as an "original initializer" too as
|
|
|
|
// it may not even be casting from a record type -- and even if it is,
|
|
|
|
// the two objects are in general of unrelated type.
|
|
|
|
isa<BuiltinBitCastExpr>(E)) {
|
2024-04-11 08:20:35 +02:00
|
|
|
return;
|
|
|
|
}
|
2024-04-18 09:23:03 +02:00
|
|
|
if (auto *Op = dyn_cast<BinaryOperator>(E);
|
|
|
|
Op && Op->getOpcode() == BO_Cmp) {
|
|
|
|
// Builtin `<=>` returns a `std::strong_ordering` object.
|
2024-04-18 09:21:10 +02:00
|
|
|
return;
|
|
|
|
}
|
2024-04-18 09:23:03 +02:00
|
|
|
|
|
|
|
if (auto *InitList = dyn_cast<InitListExpr>(E)) {
|
2024-04-11 08:20:35 +02:00
|
|
|
if (!InitList->isSemanticForm())
|
|
|
|
return;
|
|
|
|
if (InitList->isTransparent()) {
|
|
|
|
PropagateResultObject(InitList->getInit(0), Loc);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-04-19 09:06:13 +02:00
|
|
|
PropagateResultObjectToRecordInitList(RecordInitListHelper(InitList),
|
|
|
|
Loc);
|
|
|
|
return;
|
|
|
|
}
|
2024-04-11 08:20:35 +02:00
|
|
|
|
2024-04-19 09:06:13 +02:00
|
|
|
if (auto *ParenInitList = dyn_cast<CXXParenListInitExpr>(E)) {
|
|
|
|
PropagateResultObjectToRecordInitList(RecordInitListHelper(ParenInitList),
|
|
|
|
Loc);
|
2024-04-11 08:20:35 +02:00
|
|
|
return;
|
|
|
|
}
|
2024-04-18 09:23:03 +02:00
|
|
|
|
|
|
|
if (auto *Op = dyn_cast<BinaryOperator>(E); Op && Op->isCommaOp()) {
|
|
|
|
PropagateResultObject(Op->getRHS(), Loc);
|
2024-04-11 08:20:35 +02:00
|
|
|
return;
|
|
|
|
}
|
2024-04-18 09:23:03 +02:00
|
|
|
|
|
|
|
if (auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) {
|
|
|
|
PropagateResultObject(Cond->getTrueExpr(), Loc);
|
|
|
|
PropagateResultObject(Cond->getFalseExpr(), Loc);
|
|
|
|
return;
|
2024-04-11 08:20:35 +02:00
|
|
|
}
|
2024-04-18 09:23:03 +02:00
|
|
|
|
|
|
|
if (auto *SE = dyn_cast<StmtExpr>(E)) {
|
|
|
|
PropagateResultObject(cast<Expr>(SE->getSubStmt()->body_back()), Loc);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// All other expression nodes that propagate a record prvalue should have
|
|
|
|
// exactly one child.
|
|
|
|
SmallVector<Stmt *, 1> Children(E->child_begin(), E->child_end());
|
|
|
|
LLVM_DEBUG({
|
|
|
|
if (Children.size() != 1)
|
|
|
|
E->dump();
|
|
|
|
});
|
|
|
|
assert(Children.size() == 1);
|
|
|
|
for (Stmt *S : Children)
|
|
|
|
PropagateResultObject(cast<Expr>(S), Loc);
|
2024-04-11 08:20:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
llvm::DenseMap<const Expr *, RecordStorageLocation *> &ResultObjectMap;
|
|
|
|
RecordStorageLocation *LocForRecordReturnVal;
|
|
|
|
DataflowAnalysisContext &DACtx;
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace
|
|
|
|
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
Environment::Environment(DataflowAnalysisContext &DACtx)
|
|
|
|
: DACtx(&DACtx),
|
|
|
|
FlowConditionToken(DACtx.arena().makeFlowConditionToken()) {}
|
|
|
|
|
|
|
|
Environment::Environment(DataflowAnalysisContext &DACtx,
|
|
|
|
const DeclContext &DeclCtx)
|
|
|
|
: Environment(DACtx) {
|
|
|
|
CallStack.push_back(&DeclCtx);
|
|
|
|
}
|
|
|
|
|
|
|
|
void Environment::initialize() {
|
|
|
|
const DeclContext *DeclCtx = getDeclCtx();
|
|
|
|
if (DeclCtx == nullptr)
|
|
|
|
return;
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
const auto *FuncDecl = dyn_cast<FunctionDecl>(DeclCtx);
|
|
|
|
if (FuncDecl == nullptr)
|
|
|
|
return;
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(FuncDecl->doesThisDeclarationHaveABody());
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
initFieldsGlobalsAndFuncs(FuncDecl);
|
|
|
|
|
|
|
|
for (const auto *ParamDecl : FuncDecl->parameters()) {
|
|
|
|
assert(ParamDecl != nullptr);
|
|
|
|
setStorageLocation(*ParamDecl, createObject(*ParamDecl, nullptr));
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
}
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
if (FuncDecl->getReturnType()->isRecordType())
|
|
|
|
LocForRecordReturnVal = &cast<RecordStorageLocation>(
|
|
|
|
createStorageLocation(FuncDecl->getReturnType()));
|
|
|
|
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclCtx)) {
|
|
|
|
auto *Parent = MethodDecl->getParent();
|
|
|
|
assert(Parent != nullptr);
|
|
|
|
|
|
|
|
if (Parent->isLambda()) {
|
2024-03-26 12:05:40 -05:00
|
|
|
for (const auto &Capture : Parent->captures()) {
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
if (Capture.capturesVariable()) {
|
|
|
|
const auto *VarDecl = Capture.getCapturedVar();
|
|
|
|
assert(VarDecl != nullptr);
|
|
|
|
setStorageLocation(*VarDecl, createObject(*VarDecl, nullptr));
|
|
|
|
} else if (Capture.capturesThis()) {
|
|
|
|
const auto *SurroundingMethodDecl =
|
|
|
|
cast<CXXMethodDecl>(DeclCtx->getNonClosureAncestor());
|
|
|
|
QualType ThisPointeeType =
|
|
|
|
SurroundingMethodDecl->getFunctionObjectParameterType();
|
|
|
|
setThisPointeeStorageLocation(
|
2024-01-24 08:06:32 +01:00
|
|
|
cast<RecordStorageLocation>(createObject(ThisPointeeType)));
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if (MethodDecl->isImplicitObjectMemberFunction()) {
|
|
|
|
QualType ThisPointeeType = MethodDecl->getFunctionObjectParameterType();
|
2024-03-08 08:19:02 +01:00
|
|
|
auto &ThisLoc =
|
|
|
|
cast<RecordStorageLocation>(createStorageLocation(ThisPointeeType));
|
|
|
|
setThisPointeeStorageLocation(ThisLoc);
|
|
|
|
// Initialize fields of `*this` with values, but only if we're not
|
|
|
|
// analyzing a constructor; after all, it's the constructor's job to do
|
|
|
|
// this (and we want to be able to test that).
|
|
|
|
if (!isa<CXXConstructorDecl>(MethodDecl))
|
|
|
|
initializeFieldsWithValues(ThisLoc);
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
}
|
|
|
|
}
|
2024-04-11 08:20:35 +02:00
|
|
|
|
|
|
|
// We do this below the handling of `CXXMethodDecl` above so that we can
|
|
|
|
// be sure that the storage location for `this` has been set.
|
|
|
|
ResultObjectMap = std::make_shared<PrValueToResultObject>(
|
|
|
|
buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
|
|
|
|
LocForRecordReturnVal));
|
[clang][dataflow] Add synthetic fields to `RecordStorageLocation` (#73860)
Synthetic fields are intended to model the internal state of a class
(e.g. the value stored in a `std::optional`) without having to depend on
that class's implementation details.
Today, this is typically done with properties on `RecordValue`s, but
these have several drawbacks:
* Care must be taken to call `refreshRecordValue()` before modifying a
property so that the modified property values aren’t seen by other
environments that may have access to the same `RecordValue`.
* Properties aren’t associated with a storage location. If an analysis
needs to associate a location with the value stored in a property (e.g.
to model the reference returned by `std::optional::value()`), it needs
to manually add an indirection using a `PointerValue`. (See for example
the way this is done in UncheckedOptionalAccessModel.cpp, specifically
in `maybeInitializeOptionalValueMember()`.)
* Properties don’t participate in the builtin compare, join, and widen
operations. If an analysis needs to apply these operations to
properties, it needs to override the corresponding methods of
`ValueModel`.
* Longer-term, we plan to eliminate `RecordValue`, as by-value
operations on records aren’t really “a thing” in C++ (see
https://discourse.llvm.org/t/70086#changed-structvalue-api-14). This
would obviously eliminate the ability to set properties on
`RecordValue`s.
To demonstrate the advantages of synthetic fields, this patch converts
UncheckedOptionalAccessModel.cpp to synthetic fields. This greatly
simplifies the implementation of the check.
This PR is pretty big; to make it easier to review, I have broken it
down into a stack of three commits, each of which contains a set of
logically related changes. I considered submitting each of these as a
separate PR, but the commits only really make sense when taken together.
To review, I suggest first looking at the changes in
UncheckedOptionalAccessModel.cpp. This gives a flavor for how the
various API changes work together in the context of an analysis. Then,
review the rest of the changes.
2023-12-04 09:29:22 +01:00
|
|
|
}
|
|
|
|
|
2023-01-06 13:34:12 +00:00
|
|
|
// FIXME: Add support for resetting globals after function calls to enable
|
|
|
|
// the implementation of sound analyses.
|
2023-04-18 04:49:38 +00:00
|
|
|
void Environment::initFieldsGlobalsAndFuncs(const FunctionDecl *FuncDecl) {
|
[clang][dataflow] Tighten checking for existence of a function body. (#78163)
In various places, we would previously call `FunctionDecl::hasBody()`
(which
checks whether any redeclaration of the function has a body, not
necessarily the
one on which `hasBody()` is being called).
This is bug-prone, as a recent bug in Crubit's nullability checker has
shown
([fix](https://github.com/google/crubit/commit/4b01ed0f14d953cda20f92d62256e7365d206b2e),
[fix for the
fix](https://github.com/google/crubit/commit/e0c5d8ddd7d647da483c2ae198ff91d131c12055)).
Instead, we now use `FunctionDecl::doesThisDeclarationHaveABody()`
which, as the
name implies, checks whether the specific redeclaration it is being
called on
has a body.
Alternatively, I considered being more lenient and "canonicalizing" to
the
`FunctionDecl` that has the body if the `FunctionDecl` being passed is a
different redeclaration. However, this also risks hiding bugs: A caller
might
inadverently perform the analysis for all redeclarations of a function
and end
up duplicating work without realizing it. By accepting only the
redeclaration
that contains the body, we prevent this.
I've checked, and all clients that I'm aware of do currently pass in the
redeclaration that contains the function body. Typically this is because
they
use the `ast_matchers::hasBody()` matcher which, unlike
`FunctionDecl::hasBody()`, only matches for the redeclaration containing
the
body.
2024-01-16 12:52:55 +01:00
|
|
|
assert(FuncDecl->doesThisDeclarationHaveABody());
|
2023-04-03 07:02:48 +00:00
|
|
|
|
2024-04-16 14:46:05 -04:00
|
|
|
ReferencedDecls Referenced = getReferencedDecls(*FuncDecl);
|
2023-04-03 07:02:48 +00:00
|
|
|
|
|
|
|
// These have to be added before the lines that follow to ensure that
|
|
|
|
// `create*` work correctly for structs.
|
2024-04-16 14:46:05 -04:00
|
|
|
DACtx->addModeledFields(Referenced.Fields);
|
2023-04-03 07:02:48 +00:00
|
|
|
|
2024-04-16 14:46:05 -04:00
|
|
|
for (const VarDecl *D : Referenced.Globals) {
|
2023-05-08 06:38:42 +00:00
|
|
|
if (getStorageLocation(*D) != nullptr)
|
2023-01-06 13:34:12 +00:00
|
|
|
continue;
|
2023-07-17 06:27:59 +00:00
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
// We don't run transfer functions on the initializers of global variables,
|
|
|
|
// so they won't be associated with a value or storage location. We
|
|
|
|
// therefore intentionally don't pass an initializer to `createObject()`;
|
|
|
|
// in particular, this ensures that `createObject()` will initialize the
|
|
|
|
// fields of record-type variables with values.
|
|
|
|
setStorageLocation(*D, createObject(*D, nullptr));
|
2022-02-23 13:38:51 +00:00
|
|
|
}
|
2023-04-18 04:49:38 +00:00
|
|
|
|
2024-04-16 14:46:05 -04:00
|
|
|
for (const FunctionDecl *FD : Referenced.Functions) {
|
2023-05-08 06:38:42 +00:00
|
|
|
if (getStorageLocation(*FD) != nullptr)
|
2023-04-18 04:49:38 +00:00
|
|
|
continue;
|
2024-04-11 08:20:35 +02:00
|
|
|
auto &Loc = createStorageLocation(*FD);
|
2023-04-18 04:49:38 +00:00
|
|
|
setStorageLocation(*FD, Loc);
|
|
|
|
}
|
2022-02-23 13:38:51 +00:00
|
|
|
}
|
|
|
|
|
2023-06-24 02:45:17 +02:00
|
|
|
Environment Environment::fork() const {
|
|
|
|
Environment Copy(*this);
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
Copy.FlowConditionToken = DACtx->forkFlowCondition(FlowConditionToken);
|
2023-06-24 02:45:17 +02:00
|
|
|
return Copy;
|
2022-04-25 15:23:42 +00:00
|
|
|
}
|
|
|
|
|
2022-08-15 19:58:23 +00:00
|
|
|
bool Environment::canDescend(unsigned MaxDepth,
|
|
|
|
const DeclContext *Callee) const {
|
2022-08-16 18:27:41 +02:00
|
|
|
return CallStack.size() <= MaxDepth && !llvm::is_contained(CallStack, Callee);
|
2022-08-15 19:58:23 +00:00
|
|
|
}
|
|
|
|
|
2022-07-26 17:54:13 +00:00
|
|
|
Environment Environment::pushCall(const CallExpr *Call) const {
|
|
|
|
Environment Env(*this);
|
2022-08-03 14:48:49 +00:00
|
|
|
|
2022-08-10 14:20:49 -07:00
|
|
|
if (const auto *MethodCall = dyn_cast<CXXMemberCallExpr>(Call)) {
|
|
|
|
if (const Expr *Arg = MethodCall->getImplicitObjectArgument()) {
|
2022-09-22 12:42:23 +00:00
|
|
|
if (!isa<CXXThisExpr>(Arg))
|
2024-04-19 10:12:57 +02:00
|
|
|
Env.ThisPointeeLoc =
|
|
|
|
cast<RecordStorageLocation>(getStorageLocation(*Arg));
|
2022-09-22 12:42:23 +00:00
|
|
|
// Otherwise (when the argument is `this`), retain the current
|
|
|
|
// environment's `ThisPointeeLoc`.
|
2022-08-10 14:20:49 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
if (Call->getType()->isRecordType() && Call->isPRValue())
|
|
|
|
Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
|
|
|
|
|
2022-08-10 14:01:18 +00:00
|
|
|
Env.pushCallInternal(Call->getDirectCallee(),
|
2023-01-06 16:56:23 +01:00
|
|
|
llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
|
2022-08-10 14:01:18 +00:00
|
|
|
|
|
|
|
return Env;
|
|
|
|
}
|
|
|
|
|
|
|
|
Environment Environment::pushCall(const CXXConstructExpr *Call) const {
|
|
|
|
Environment Env(*this);
|
|
|
|
|
2023-07-20 11:12:39 +00:00
|
|
|
Env.ThisPointeeLoc = &Env.getResultObjectLocation(*Call);
|
2024-04-11 08:20:35 +02:00
|
|
|
Env.LocForRecordReturnVal = &Env.getResultObjectLocation(*Call);
|
2022-08-10 14:01:18 +00:00
|
|
|
|
|
|
|
Env.pushCallInternal(Call->getConstructor(),
|
2023-01-06 16:56:23 +01:00
|
|
|
llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
|
2022-08-10 14:01:18 +00:00
|
|
|
|
|
|
|
return Env;
|
|
|
|
}
|
|
|
|
|
|
|
|
void Environment::pushCallInternal(const FunctionDecl *FuncDecl,
|
|
|
|
ArrayRef<const Expr *> Args) {
|
2023-05-23 09:35:52 +00:00
|
|
|
// Canonicalize to the definition of the function. This ensures that we're
|
|
|
|
// putting arguments into the same `ParamVarDecl`s` that the callee will later
|
|
|
|
// be retrieving them from.
|
|
|
|
assert(FuncDecl->getDefinition() != nullptr);
|
|
|
|
FuncDecl = FuncDecl->getDefinition();
|
|
|
|
|
2022-08-15 19:58:23 +00:00
|
|
|
CallStack.push_back(FuncDecl);
|
2022-08-10 14:01:18 +00:00
|
|
|
|
2023-04-18 04:49:38 +00:00
|
|
|
initFieldsGlobalsAndFuncs(FuncDecl);
|
2023-01-09 22:54:53 +00:00
|
|
|
|
2023-01-06 13:34:12 +00:00
|
|
|
const auto *ParamIt = FuncDecl->param_begin();
|
2022-07-26 17:54:13 +00:00
|
|
|
|
|
|
|
// FIXME: Parameters don't always map to arguments 1:1; examples include
|
|
|
|
// overloaded operators implemented as member functions, and parameter packs.
|
2022-08-10 14:01:18 +00:00
|
|
|
for (unsigned ArgIndex = 0; ArgIndex < Args.size(); ++ParamIt, ++ArgIndex) {
|
2022-07-26 21:02:31 -07:00
|
|
|
assert(ParamIt != FuncDecl->param_end());
|
2022-07-29 19:39:52 +00:00
|
|
|
const VarDecl *Param = *ParamIt;
|
2023-07-17 06:27:59 +00:00
|
|
|
setStorageLocation(*Param, createObject(*Param, Args[ArgIndex]));
|
2022-07-26 17:54:13 +00:00
|
|
|
}
|
2024-04-11 08:20:35 +02:00
|
|
|
|
|
|
|
ResultObjectMap = std::make_shared<PrValueToResultObject>(
|
|
|
|
buildResultObjectMap(DACtx, FuncDecl, getThisPointeeStorageLocation(),
|
|
|
|
LocForRecordReturnVal));
|
2022-07-26 17:54:13 +00:00
|
|
|
}
|
|
|
|
|
2023-05-23 09:35:52 +00:00
|
|
|
void Environment::popCall(const CallExpr *Call, const Environment &CalleeEnv) {
|
2023-08-28 11:50:03 +00:00
|
|
|
// We ignore some entries of `CalleeEnv`:
|
|
|
|
// - `DACtx` because is already the same in both
|
|
|
|
// - We don't want the callee's `DeclCtx`, `ReturnVal`, `ReturnLoc` or
|
|
|
|
// `ThisPointeeLoc` because they don't apply to us.
|
|
|
|
// - `DeclToLoc`, `ExprToLoc`, and `ExprToVal` capture information from the
|
|
|
|
// callee's local scope, so when popping that scope, we do not propagate
|
|
|
|
// the maps.
|
2022-07-29 19:39:52 +00:00
|
|
|
this->LocToVal = std::move(CalleeEnv.LocToVal);
|
|
|
|
this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
|
2023-05-23 09:35:52 +00:00
|
|
|
|
|
|
|
if (Call->isGLValue()) {
|
|
|
|
if (CalleeEnv.ReturnLoc != nullptr)
|
2023-07-31 12:37:01 +00:00
|
|
|
setStorageLocation(*Call, *CalleeEnv.ReturnLoc);
|
2023-05-23 09:35:52 +00:00
|
|
|
} else if (!Call->getType()->isVoidType()) {
|
|
|
|
if (CalleeEnv.ReturnVal != nullptr)
|
2023-07-31 12:37:01 +00:00
|
|
|
setValue(*Call, *CalleeEnv.ReturnVal);
|
2023-05-23 09:35:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void Environment::popCall(const CXXConstructExpr *Call,
|
|
|
|
const Environment &CalleeEnv) {
|
|
|
|
// See also comment in `popCall(const CallExpr *, const Environment &)` above.
|
|
|
|
this->LocToVal = std::move(CalleeEnv.LocToVal);
|
|
|
|
this->FlowConditionToken = std::move(CalleeEnv.FlowConditionToken);
|
2022-07-29 19:39:52 +00:00
|
|
|
}
|
|
|
|
|
2022-01-31 10:43:07 +00:00
|
|
|
bool Environment::equivalentTo(const Environment &Other,
|
|
|
|
Environment::ValueModel &Model) const {
|
2021-12-29 11:31:02 +00:00
|
|
|
assert(DACtx == Other.DACtx);
|
2022-01-31 10:43:07 +00:00
|
|
|
|
2023-05-23 09:35:52 +00:00
|
|
|
if (ReturnVal != Other.ReturnVal)
|
|
|
|
return false;
|
|
|
|
|
2022-08-04 17:42:01 +00:00
|
|
|
if (ReturnLoc != Other.ReturnLoc)
|
|
|
|
return false;
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
if (LocForRecordReturnVal != Other.LocForRecordReturnVal)
|
|
|
|
return false;
|
|
|
|
|
2022-08-04 17:45:30 +00:00
|
|
|
if (ThisPointeeLoc != Other.ThisPointeeLoc)
|
|
|
|
return false;
|
|
|
|
|
2022-01-31 10:43:07 +00:00
|
|
|
if (DeclToLoc != Other.DeclToLoc)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
if (ExprToLoc != Other.ExprToLoc)
|
|
|
|
return false;
|
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
if (!compareKeyToValueMaps(ExprToVal, Other.ExprToVal, *this, Other, Model))
|
|
|
|
return false;
|
2022-01-31 10:43:07 +00:00
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
if (!compareKeyToValueMaps(LocToVal, Other.LocToVal, *this, Other, Model))
|
|
|
|
return false;
|
2022-01-31 10:43:07 +00:00
|
|
|
|
|
|
|
return true;
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
LatticeEffect Environment::widen(const Environment &PrevEnv,
|
|
|
|
Environment::ValueModel &Model) {
|
2022-11-03 00:36:58 +00:00
|
|
|
assert(DACtx == PrevEnv.DACtx);
|
2023-05-23 09:35:52 +00:00
|
|
|
assert(ReturnVal == PrevEnv.ReturnVal);
|
2022-11-03 00:36:58 +00:00
|
|
|
assert(ReturnLoc == PrevEnv.ReturnLoc);
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(LocForRecordReturnVal == PrevEnv.LocForRecordReturnVal);
|
2022-11-03 00:36:58 +00:00
|
|
|
assert(ThisPointeeLoc == PrevEnv.ThisPointeeLoc);
|
|
|
|
assert(CallStack == PrevEnv.CallStack);
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(ResultObjectMap == PrevEnv.ResultObjectMap);
|
2022-11-03 00:36:58 +00:00
|
|
|
|
2024-04-04 08:39:51 -04:00
|
|
|
auto Effect = LatticeEffect::Unchanged;
|
2022-11-03 00:36:58 +00:00
|
|
|
|
2022-12-19 14:47:35 +00:00
|
|
|
// By the API, `PrevEnv` is a previous version of the environment for the same
|
|
|
|
// block, so we have some guarantees about its shape. In particular, it will
|
|
|
|
// be the result of a join or widen operation on previous values for this
|
2023-08-28 11:50:03 +00:00
|
|
|
// block. For `DeclToLoc`, `ExprToVal`, and `ExprToLoc`, join guarantees that
|
|
|
|
// these maps are subsets of the maps in `PrevEnv`. So, as long as we maintain
|
|
|
|
// this property here, we don't need change their current values to widen.
|
2022-11-03 00:36:58 +00:00
|
|
|
assert(DeclToLoc.size() <= PrevEnv.DeclToLoc.size());
|
2023-08-28 11:50:03 +00:00
|
|
|
assert(ExprToVal.size() <= PrevEnv.ExprToVal.size());
|
2022-11-03 00:36:58 +00:00
|
|
|
assert(ExprToLoc.size() <= PrevEnv.ExprToLoc.size());
|
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
ExprToVal = widenKeyToValueMap(ExprToVal, PrevEnv.ExprToVal, *this, PrevEnv,
|
|
|
|
Model, Effect);
|
2022-11-03 00:36:58 +00:00
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
LocToVal = widenKeyToValueMap(LocToVal, PrevEnv.LocToVal, *this, PrevEnv,
|
|
|
|
Model, Effect);
|
2022-11-03 00:36:58 +00:00
|
|
|
if (DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
|
|
|
|
ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
|
2023-08-28 11:50:03 +00:00
|
|
|
ExprToVal.size() != PrevEnv.ExprToVal.size() ||
|
2023-07-20 11:12:39 +00:00
|
|
|
LocToVal.size() != PrevEnv.LocToVal.size())
|
2024-04-04 08:39:51 -04:00
|
|
|
Effect = LatticeEffect::Changed;
|
2022-11-03 00:36:58 +00:00
|
|
|
|
|
|
|
return Effect;
|
|
|
|
}
|
|
|
|
|
2023-06-27 20:59:18 +02:00
|
|
|
Environment Environment::join(const Environment &EnvA, const Environment &EnvB,
|
[clang][nullability] Don't discard expression state before end of full-expression. (#82611)
In https://github.com/llvm/llvm-project/pull/72985, I made a change to
discard
expression state (`ExprToLoc` and `ExprToVal`) at the beginning of each
basic
block. I did so with the claim that "we never need to access entries
from these
maps outside of the current basic block", noting that there are
exceptions to
this claim when control flow happens inside a full-expression (the
operands of
`&&`, `||`, and the conditional operator live in different basic blocks
than the
operator itself) but that we already have a mechanism for retrieving the
values
of these operands from the environment for the block they are computed
in.
It turns out, however, that the operands of these operators aren't the
only
expressions whose values can be accessed from a different basic block;
when
control flow happens within a full-expression, that control flow can be
"interposed" between an expression and its parent. Here is an example:
```cxx
void f(int*, int);
bool cond();
void target() {
int i = 0;
f(&i, cond() ? 1 : 0);
}
```
([godbolt](https://godbolt.org/z/hrbj1Mj3o))
In the CFG[^1] , note how the expression for `&i` is computed in block
B4,
but the parent of this expression (the `CallExpr`) is located in block
B1.
The the argument expression `&i` and the `CallExpr` are essentially
"torn apart"
into different basic blocks by the conditional operator in the second
argument.
In other words, the edge between the `CallExpr` and its argument `&i`
straddles
the boundary between two blocks.
I used to think that this scenario -- where an edge between an
expression and
one of its children straddles a block boundary -- could only happen
between the
expression that triggers the control flow (`&&`, `||`, or the
conditional
operator) and its children, but the example above shows that other
expressions
can be affected as well; the control flow is still triggered by `&&`,
`||` or
the conditional operator, but the expressions affected lie outside these
operators.
Discarding expression state too soon is harmful. For example, an
analysis that
checks the arguments of the `CallExpr` above would not be able to
retrieve a
value for the `&i` argument.
This patch therefore ensures that we don't discard expression state
before the
end of a full-expression. In other cases -- when the evaluation of a
full-expression is complete -- we still want to discard expression state
for the
reasons explained in https://github.com/llvm/llvm-project/pull/72985
(avoid
performing joins on boolean values that are no longer needed, which
unnecessarily extends the flow condition; improve debuggability by
removing
clutter from the expression state).
The impact on performance from this change is about a 1% slowdown in the
Crubit nullability check benchmarks:
```
name old cpu/op new cpu/op delta
BM_PointerAnalysisCopyPointer 71.9µs ± 1% 71.9µs ± 2% ~ (p=0.987 n=15+20)
BM_PointerAnalysisIntLoop 190µs ± 1% 192µs ± 2% +1.06% (p=0.000 n=14+16)
BM_PointerAnalysisPointerLoop 325µs ± 5% 324µs ± 4% ~ (p=0.496 n=18+20)
BM_PointerAnalysisBranch 193µs ± 0% 192µs ± 4% ~ (p=0.488 n=14+18)
BM_PointerAnalysisLoopAndBranch 521µs ± 1% 525µs ± 3% +0.94% (p=0.017 n=18+19)
BM_PointerAnalysisTwoLoops 337µs ± 1% 341µs ± 3% +1.19% (p=0.004 n=17+19)
BM_PointerAnalysisJoinFilePath 1.62ms ± 2% 1.64ms ± 3% +0.92% (p=0.021 n=20+20)
BM_PointerAnalysisCallInLoop 1.14ms ± 1% 1.15ms ± 4% ~ (p=0.135 n=16+18)
```
[^1]:
```
[B5 (ENTRY)]
Succs (1): B4
[B1]
1: [B4.9] ? [B2.1] : [B3.1]
2: [B4.4]([B4.6], [B1.1])
Preds (2): B2 B3
Succs (1): B0
[B2]
1: 1
Preds (1): B4
Succs (1): B1
[B3]
1: 0
Preds (1): B4
Succs (1): B1
[B4]
1: 0
2: int i = 0;
3: f
4: [B4.3] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int *, int))
5: i
6: &[B4.5]
7: cond
8: [B4.7] (ImplicitCastExpr, FunctionToPointerDecay, _Bool (*)(void))
9: [B4.8]()
T: [B4.9] ? ... : ...
Preds (1): B5
Succs (2): B2 B3
[B0 (EXIT)]
Preds (1): B1
```
2024-03-07 13:31:23 +01:00
|
|
|
Environment::ValueModel &Model,
|
|
|
|
ExprJoinBehavior ExprBehavior) {
|
2023-06-27 20:59:18 +02:00
|
|
|
assert(EnvA.DACtx == EnvB.DACtx);
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(EnvA.LocForRecordReturnVal == EnvB.LocForRecordReturnVal);
|
2023-06-27 20:59:18 +02:00
|
|
|
assert(EnvA.ThisPointeeLoc == EnvB.ThisPointeeLoc);
|
|
|
|
assert(EnvA.CallStack == EnvB.CallStack);
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(EnvA.ResultObjectMap == EnvB.ResultObjectMap);
|
2021-12-29 11:31:02 +00:00
|
|
|
|
2023-06-27 20:59:18 +02:00
|
|
|
Environment JoinedEnv(*EnvA.DACtx);
|
2022-04-14 13:42:02 +00:00
|
|
|
|
2023-06-27 20:59:18 +02:00
|
|
|
JoinedEnv.CallStack = EnvA.CallStack;
|
2024-04-11 08:20:35 +02:00
|
|
|
JoinedEnv.ResultObjectMap = EnvA.ResultObjectMap;
|
|
|
|
JoinedEnv.LocForRecordReturnVal = EnvA.LocForRecordReturnVal;
|
2023-06-27 20:59:18 +02:00
|
|
|
JoinedEnv.ThisPointeeLoc = EnvA.ThisPointeeLoc;
|
2022-08-04 17:42:01 +00:00
|
|
|
|
2024-04-22 09:35:29 +02:00
|
|
|
if (EnvA.ReturnVal == nullptr || EnvB.ReturnVal == nullptr) {
|
|
|
|
// `ReturnVal` might not always get set -- for example if we have a return
|
|
|
|
// statement of the form `return some_other_func()` and we decide not to
|
|
|
|
// analyze `some_other_func()`.
|
|
|
|
// In this case, we can't say anything about the joined return value -- we
|
|
|
|
// don't simply want to propagate the return value that we do have, because
|
|
|
|
// it might not be the correct one.
|
|
|
|
// This occurs for example in the test `ContextSensitiveMutualRecursion`.
|
2023-05-23 09:35:52 +00:00
|
|
|
JoinedEnv.ReturnVal = nullptr;
|
2024-04-22 09:35:29 +02:00
|
|
|
} else if (areEquivalentValues(*EnvA.ReturnVal, *EnvB.ReturnVal)) {
|
|
|
|
JoinedEnv.ReturnVal = EnvA.ReturnVal;
|
2023-05-23 09:35:52 +00:00
|
|
|
} else {
|
2024-04-22 09:35:29 +02:00
|
|
|
assert(!EnvA.CallStack.empty());
|
2023-05-23 09:35:52 +00:00
|
|
|
// FIXME: Make `CallStack` a vector of `FunctionDecl` so we don't need this
|
|
|
|
// cast.
|
2023-06-27 20:59:18 +02:00
|
|
|
auto *Func = dyn_cast<FunctionDecl>(EnvA.CallStack.back());
|
2023-05-23 09:35:52 +00:00
|
|
|
assert(Func != nullptr);
|
2024-04-22 09:35:29 +02:00
|
|
|
if (Value *JoinedVal =
|
|
|
|
joinDistinctValues(Func->getReturnType(), *EnvA.ReturnVal, EnvA,
|
|
|
|
*EnvB.ReturnVal, EnvB, JoinedEnv, Model))
|
|
|
|
JoinedEnv.ReturnVal = JoinedVal;
|
2023-05-23 09:35:52 +00:00
|
|
|
}
|
|
|
|
|
2023-06-27 20:59:18 +02:00
|
|
|
if (EnvA.ReturnLoc == EnvB.ReturnLoc)
|
|
|
|
JoinedEnv.ReturnLoc = EnvA.ReturnLoc;
|
2023-05-23 09:35:52 +00:00
|
|
|
else
|
|
|
|
JoinedEnv.ReturnLoc = nullptr;
|
|
|
|
|
2023-11-22 16:34:24 +01:00
|
|
|
JoinedEnv.DeclToLoc = intersectDeclToLoc(EnvA.DeclToLoc, EnvB.DeclToLoc);
|
2022-01-20 09:28:25 +00:00
|
|
|
|
2022-11-03 00:36:58 +00:00
|
|
|
// FIXME: update join to detect backedges and simplify the flow condition
|
|
|
|
// accordingly.
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
JoinedEnv.FlowConditionToken = EnvA.DACtx->joinFlowConditions(
|
|
|
|
EnvA.FlowConditionToken, EnvB.FlowConditionToken);
|
2022-04-14 13:42:02 +00:00
|
|
|
|
2023-11-22 16:34:24 +01:00
|
|
|
JoinedEnv.LocToVal =
|
|
|
|
joinLocToVal(EnvA.LocToVal, EnvB.LocToVal, EnvA, EnvB, JoinedEnv, Model);
|
2022-01-24 13:29:06 +00:00
|
|
|
|
[clang][nullability] Don't discard expression state before end of full-expression. (#82611)
In https://github.com/llvm/llvm-project/pull/72985, I made a change to
discard
expression state (`ExprToLoc` and `ExprToVal`) at the beginning of each
basic
block. I did so with the claim that "we never need to access entries
from these
maps outside of the current basic block", noting that there are
exceptions to
this claim when control flow happens inside a full-expression (the
operands of
`&&`, `||`, and the conditional operator live in different basic blocks
than the
operator itself) but that we already have a mechanism for retrieving the
values
of these operands from the environment for the block they are computed
in.
It turns out, however, that the operands of these operators aren't the
only
expressions whose values can be accessed from a different basic block;
when
control flow happens within a full-expression, that control flow can be
"interposed" between an expression and its parent. Here is an example:
```cxx
void f(int*, int);
bool cond();
void target() {
int i = 0;
f(&i, cond() ? 1 : 0);
}
```
([godbolt](https://godbolt.org/z/hrbj1Mj3o))
In the CFG[^1] , note how the expression for `&i` is computed in block
B4,
but the parent of this expression (the `CallExpr`) is located in block
B1.
The the argument expression `&i` and the `CallExpr` are essentially
"torn apart"
into different basic blocks by the conditional operator in the second
argument.
In other words, the edge between the `CallExpr` and its argument `&i`
straddles
the boundary between two blocks.
I used to think that this scenario -- where an edge between an
expression and
one of its children straddles a block boundary -- could only happen
between the
expression that triggers the control flow (`&&`, `||`, or the
conditional
operator) and its children, but the example above shows that other
expressions
can be affected as well; the control flow is still triggered by `&&`,
`||` or
the conditional operator, but the expressions affected lie outside these
operators.
Discarding expression state too soon is harmful. For example, an
analysis that
checks the arguments of the `CallExpr` above would not be able to
retrieve a
value for the `&i` argument.
This patch therefore ensures that we don't discard expression state
before the
end of a full-expression. In other cases -- when the evaluation of a
full-expression is complete -- we still want to discard expression state
for the
reasons explained in https://github.com/llvm/llvm-project/pull/72985
(avoid
performing joins on boolean values that are no longer needed, which
unnecessarily extends the flow condition; improve debuggability by
removing
clutter from the expression state).
The impact on performance from this change is about a 1% slowdown in the
Crubit nullability check benchmarks:
```
name old cpu/op new cpu/op delta
BM_PointerAnalysisCopyPointer 71.9µs ± 1% 71.9µs ± 2% ~ (p=0.987 n=15+20)
BM_PointerAnalysisIntLoop 190µs ± 1% 192µs ± 2% +1.06% (p=0.000 n=14+16)
BM_PointerAnalysisPointerLoop 325µs ± 5% 324µs ± 4% ~ (p=0.496 n=18+20)
BM_PointerAnalysisBranch 193µs ± 0% 192µs ± 4% ~ (p=0.488 n=14+18)
BM_PointerAnalysisLoopAndBranch 521µs ± 1% 525µs ± 3% +0.94% (p=0.017 n=18+19)
BM_PointerAnalysisTwoLoops 337µs ± 1% 341µs ± 3% +1.19% (p=0.004 n=17+19)
BM_PointerAnalysisJoinFilePath 1.62ms ± 2% 1.64ms ± 3% +0.92% (p=0.021 n=20+20)
BM_PointerAnalysisCallInLoop 1.14ms ± 1% 1.15ms ± 4% ~ (p=0.135 n=16+18)
```
[^1]:
```
[B5 (ENTRY)]
Succs (1): B4
[B1]
1: [B4.9] ? [B2.1] : [B3.1]
2: [B4.4]([B4.6], [B1.1])
Preds (2): B2 B3
Succs (1): B0
[B2]
1: 1
Preds (1): B4
Succs (1): B1
[B3]
1: 0
Preds (1): B4
Succs (1): B1
[B4]
1: 0
2: int i = 0;
3: f
4: [B4.3] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(int *, int))
5: i
6: &[B4.5]
7: cond
8: [B4.7] (ImplicitCastExpr, FunctionToPointerDecay, _Bool (*)(void))
9: [B4.8]()
T: [B4.9] ? ... : ...
Preds (1): B5
Succs (2): B2 B3
[B0 (EXIT)]
Preds (1): B1
```
2024-03-07 13:31:23 +01:00
|
|
|
if (ExprBehavior == KeepExprState) {
|
|
|
|
JoinedEnv.ExprToVal = joinExprMaps(EnvA.ExprToVal, EnvB.ExprToVal);
|
|
|
|
JoinedEnv.ExprToLoc = joinExprMaps(EnvA.ExprToLoc, EnvB.ExprToLoc);
|
|
|
|
}
|
2021-12-29 11:31:02 +00:00
|
|
|
|
2023-06-26 20:01:04 +02:00
|
|
|
return JoinedEnv;
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
StorageLocation &Environment::createStorageLocation(QualType Type) {
|
2022-08-02 21:05:48 +00:00
|
|
|
return DACtx->createStorageLocation(Type);
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-10-11 22:18:46 +02:00
|
|
|
StorageLocation &Environment::createStorageLocation(const ValueDecl &D) {
|
2021-12-29 11:31:02 +00:00
|
|
|
// Evaluated declarations are always assigned the same storage locations to
|
|
|
|
// ensure that the environment stabilizes across loop iterations. Storage
|
|
|
|
// locations for evaluated declarations are stored in the analysis context.
|
2022-06-27 11:12:37 +02:00
|
|
|
return DACtx->getStableStorageLocation(D);
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2022-01-04 13:47:14 +00:00
|
|
|
StorageLocation &Environment::createStorageLocation(const Expr &E) {
|
|
|
|
// Evaluated expressions are always assigned the same storage locations to
|
|
|
|
// ensure that the environment stabilizes across loop iterations. Storage
|
|
|
|
// locations for evaluated expressions are stored in the analysis context.
|
2022-06-27 11:12:37 +02:00
|
|
|
return DACtx->getStableStorageLocation(E);
|
2022-01-04 13:47:14 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
void Environment::setStorageLocation(const ValueDecl &D, StorageLocation &Loc) {
|
2023-03-15 18:06:34 -07:00
|
|
|
assert(!DeclToLoc.contains(&D));
|
2024-04-11 08:20:35 +02:00
|
|
|
// The only kinds of declarations that may have a "variable" storage location
|
|
|
|
// are declarations of reference type and `BindingDecl`. For all other
|
|
|
|
// declaration, the storage location should be the stable storage location
|
|
|
|
// returned by `createStorageLocation()`.
|
|
|
|
assert(D.getType()->isReferenceType() || isa<BindingDecl>(D) ||
|
|
|
|
&Loc == &createStorageLocation(D));
|
2021-12-29 11:31:02 +00:00
|
|
|
DeclToLoc[&D] = &Loc;
|
|
|
|
}
|
|
|
|
|
2023-05-08 06:38:42 +00:00
|
|
|
StorageLocation *Environment::getStorageLocation(const ValueDecl &D) const {
|
2021-12-29 11:31:02 +00:00
|
|
|
auto It = DeclToLoc.find(&D);
|
[clang][dataflow] Eliminate intermediate `ReferenceValue`s from `Environment::DeclToLoc`.
For the wider context of this change, see the RFC at
https://discourse.llvm.org/t/70086.
After this change, global and local variables of reference type are associated
directly with the `StorageLocation` of the referenced object instead of the
`StorageLocation` of a `ReferenceValue`.
Some tests that explicitly check for an existence of `ReferenceValue` for a
variable of reference type have been modified accordingly.
As discussed in the RFC, I have added an assertion to `Environment::join()` to
check that if both environments contain an entry for the same declaration in
`DeclToLoc`, they both map to the same `StorageLocation`. As discussed in
https://discourse.llvm.org/t/70086/5, this also necessitates removing
declarations from `DeclToLoc` when they go out of scope.
In the RFC, I proposed a gradual migration for this change, but it appears
that all of the callers of `Environment::setStorageLocation(const ValueDecl &,
SkipPast` are in the dataflow framework itself, and that there are only a few of
them.
As this is the function whose semantics are changing in a way that callers
potentially need to adapt to, I've decided to change the semantics of the
function directly.
The semantics of `getStorageLocation(const ValueDecl &, SkipPast SP` now no
longer depend on the behavior of the `SP` parameter. (There don't appear to be
any callers that use `SkipPast::ReferenceThenPointer`, so I've added an
assertion that forbids this usage.)
This patch adds a default argument for the `SP` parameter and removes the
explicit `SP` argument at the callsites that are touched by this change. A
followup patch will remove the argument from the remaining callsites,
allowing the `SkipPast` parameter to be removed entirely. (I don't want to do
that in this patch so that semantics-changing changes can be reviewed separately
from semantics-neutral changes.)
Reviewed By: ymandel, xazax.hun, gribozavr2
Differential Revision: https://reviews.llvm.org/D149144
2023-05-04 07:42:05 +00:00
|
|
|
if (It == DeclToLoc.end())
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
StorageLocation *Loc = It->second;
|
|
|
|
|
|
|
|
return Loc;
|
2022-01-04 13:47:14 +00:00
|
|
|
}
|
|
|
|
|
2023-10-24 08:42:30 +02:00
|
|
|
void Environment::removeDecl(const ValueDecl &D) { DeclToLoc.erase(&D); }
|
2023-09-26 08:41:09 +02:00
|
|
|
|
2023-07-31 12:37:01 +00:00
|
|
|
void Environment::setStorageLocation(const Expr &E, StorageLocation &Loc) {
|
[clang][dataflow] Add `Strict` versions of `Value` and `StorageLocation` accessors.
This is part of the gradual migration to strict handling of value categories, as described in the RFC at https://discourse.llvm.org/t/70086.
This patch migrates some representative calls of the newly deprecated accessors to the new `Strict` functions. Followup patches will migrate the remaining callers. (There are a large number of callers, with some subtlety involved in some of them, so it makes sense to split this up into multiple patches rather than migrating all callers in one go.)
The `Strict` accessors as implemented here have some differences in semantics compared to the semantics originally proposed in the RFC; specifically:
* `setStorageLocationStrict()`: The RFC proposes to create an intermediate
`ReferenceValue` that then refers to the `StorageLocation` for the glvalue.
It turns out though that, even today, most places in the code are not doing
this but are instead associating glvalues directly with their
`StorageLocation`. It therefore didn't seem to make sense to introduce new
`ReferenceValue`s where there were none previously, so I have chosen to
instead make `setStorageLocationStrict()` simply call through to
`setStorageLocation(const Expr &, StorageLocation &)` and merely add the
assertion that the expression must be a glvalue.
* `getStorageLocationStrict()`: The RFC proposes that this should assert that
the storage location for the glvalue expression is associated with an
intermediate `ReferenceValue`, but, as explained, this is often not true.
The current state is inconsistent: Sometimes the intermediate
`ReferenceValue` is there, sometimes it isn't. For this reason,
`getStorageLocationStrict()` skips past a `ReferenceValue` if it is there but
otherwise directly returns the storage location associated with the
expression. This behavior is equivalent to the existing behavior of
`SkipPast::Reference`.
* `setValueStrict()`: The RFC proposes that this should always create the same
`StorageLocation` for a given `Value`, but, in fact, the transfer functions
that exist today don't guarantee this; almost all transfer functions
unconditionally create a new `StorageLocation` when associating an expression
with a `Value`.
There appears to be one special case:
`TerminatorVisitor::extendFlowCondition()` checks whether the expression is
already associated with a `StorageLocation` and, if so, reuses the existing
`StorageLocation` instead of creating a new one.
For this reason, `setValueStrict()` implements this logic (preserve an
existing `StorageLocation`) but makes no attempt to always associate the same
`StorageLocation` with a given `Value`, as nothing in the framework appers to
require this.
As `TerminatorVisitor::extendFlowCondition()` is an interesting special case,
the `setValue()` call there is among the ones that this patch migrates to
`setValueStrict()`.
Reviewed By: sammccall, ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D150653
2023-05-17 09:12:46 +00:00
|
|
|
// `DeclRefExpr`s to builtin function types aren't glvalues, for some reason,
|
|
|
|
// but we still want to be able to associate a `StorageLocation` with them,
|
|
|
|
// so allow these as an exception.
|
|
|
|
assert(E.isGLValue() ||
|
|
|
|
E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
|
2023-12-18 09:10:03 +01:00
|
|
|
const Expr &CanonE = ignoreCFGOmittedNodes(E);
|
|
|
|
assert(!ExprToLoc.contains(&CanonE));
|
|
|
|
ExprToLoc[&CanonE] = &Loc;
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-07-31 12:37:01 +00:00
|
|
|
StorageLocation *Environment::getStorageLocation(const Expr &E) const {
|
|
|
|
// See comment in `setStorageLocation()`.
|
[clang][dataflow] Add `Strict` versions of `Value` and `StorageLocation` accessors.
This is part of the gradual migration to strict handling of value categories, as described in the RFC at https://discourse.llvm.org/t/70086.
This patch migrates some representative calls of the newly deprecated accessors to the new `Strict` functions. Followup patches will migrate the remaining callers. (There are a large number of callers, with some subtlety involved in some of them, so it makes sense to split this up into multiple patches rather than migrating all callers in one go.)
The `Strict` accessors as implemented here have some differences in semantics compared to the semantics originally proposed in the RFC; specifically:
* `setStorageLocationStrict()`: The RFC proposes to create an intermediate
`ReferenceValue` that then refers to the `StorageLocation` for the glvalue.
It turns out though that, even today, most places in the code are not doing
this but are instead associating glvalues directly with their
`StorageLocation`. It therefore didn't seem to make sense to introduce new
`ReferenceValue`s where there were none previously, so I have chosen to
instead make `setStorageLocationStrict()` simply call through to
`setStorageLocation(const Expr &, StorageLocation &)` and merely add the
assertion that the expression must be a glvalue.
* `getStorageLocationStrict()`: The RFC proposes that this should assert that
the storage location for the glvalue expression is associated with an
intermediate `ReferenceValue`, but, as explained, this is often not true.
The current state is inconsistent: Sometimes the intermediate
`ReferenceValue` is there, sometimes it isn't. For this reason,
`getStorageLocationStrict()` skips past a `ReferenceValue` if it is there but
otherwise directly returns the storage location associated with the
expression. This behavior is equivalent to the existing behavior of
`SkipPast::Reference`.
* `setValueStrict()`: The RFC proposes that this should always create the same
`StorageLocation` for a given `Value`, but, in fact, the transfer functions
that exist today don't guarantee this; almost all transfer functions
unconditionally create a new `StorageLocation` when associating an expression
with a `Value`.
There appears to be one special case:
`TerminatorVisitor::extendFlowCondition()` checks whether the expression is
already associated with a `StorageLocation` and, if so, reuses the existing
`StorageLocation` instead of creating a new one.
For this reason, `setValueStrict()` implements this logic (preserve an
existing `StorageLocation`) but makes no attempt to always associate the same
`StorageLocation` with a given `Value`, as nothing in the framework appers to
require this.
As `TerminatorVisitor::extendFlowCondition()` is an interesting special case,
the `setValue()` call there is among the ones that this patch migrates to
`setValueStrict()`.
Reviewed By: sammccall, ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D150653
2023-05-17 09:12:46 +00:00
|
|
|
assert(E.isGLValue() ||
|
|
|
|
E.getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn));
|
2023-12-18 09:10:03 +01:00
|
|
|
auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
|
|
|
|
return It == ExprToLoc.end() ? nullptr : &*It->second;
|
|
|
|
}
|
|
|
|
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
RecordStorageLocation &
|
2023-12-18 09:10:03 +01:00
|
|
|
Environment::getResultObjectLocation(const Expr &RecordPRValue) const {
|
2023-07-20 11:12:39 +00:00
|
|
|
assert(RecordPRValue.getType()->isRecordType());
|
|
|
|
assert(RecordPRValue.isPRValue());
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
assert(ResultObjectMap != nullptr);
|
|
|
|
RecordStorageLocation *Loc = ResultObjectMap->lookup(&RecordPRValue);
|
|
|
|
assert(Loc != nullptr);
|
|
|
|
// In release builds, use the "stable" storage location if the map lookup
|
|
|
|
// failed.
|
|
|
|
if (Loc == nullptr)
|
2023-12-18 09:10:03 +01:00
|
|
|
return cast<RecordStorageLocation>(
|
|
|
|
DACtx->getStableStorageLocation(RecordPRValue));
|
2024-04-11 08:20:35 +02:00
|
|
|
return *Loc;
|
2023-07-20 11:12:39 +00:00
|
|
|
}
|
|
|
|
|
2022-06-27 14:14:01 +02:00
|
|
|
PointerValue &Environment::getOrCreateNullPointerValue(QualType PointeeType) {
|
|
|
|
return DACtx->getOrCreateNullPointerValue(PointeeType);
|
|
|
|
}
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
|
|
|
|
QualType Type) {
|
2024-03-08 08:19:02 +01:00
|
|
|
llvm::DenseSet<QualType> Visited;
|
|
|
|
int CreatedValuesCount = 0;
|
2024-04-11 08:20:35 +02:00
|
|
|
initializeFieldsWithValues(Loc, Type, Visited, 0, CreatedValuesCount);
|
2024-03-08 08:19:02 +01:00
|
|
|
if (CreatedValuesCount > MaxCompositeValueSize) {
|
2024-04-11 08:20:35 +02:00
|
|
|
llvm::errs() << "Attempting to initialize a huge value of type: " << Type
|
|
|
|
<< '\n';
|
2024-03-08 08:19:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-13 13:53:52 +00:00
|
|
|
void Environment::setValue(const StorageLocation &Loc, Value &Val) {
|
2024-04-19 09:39:52 +02:00
|
|
|
// Records should not be associated with values.
|
|
|
|
assert(!isa<RecordStorageLocation>(Loc));
|
2023-07-20 11:12:39 +00:00
|
|
|
LocToVal[&Loc] = &Val;
|
2023-06-20 08:00:01 +00:00
|
|
|
}
|
|
|
|
|
2023-07-31 12:37:01 +00:00
|
|
|
void Environment::setValue(const Expr &E, Value &Val) {
|
2024-01-16 15:48:44 +01:00
|
|
|
const Expr &CanonE = ignoreCFGOmittedNodes(E);
|
|
|
|
|
|
|
|
assert(CanonE.isPRValue());
|
2024-04-19 09:39:52 +02:00
|
|
|
// Records should not be associated with values.
|
|
|
|
assert(!CanonE.getType()->isRecordType());
|
2024-01-16 15:48:44 +01:00
|
|
|
ExprToVal[&CanonE] = &Val;
|
[clang][dataflow] Add `Strict` versions of `Value` and `StorageLocation` accessors.
This is part of the gradual migration to strict handling of value categories, as described in the RFC at https://discourse.llvm.org/t/70086.
This patch migrates some representative calls of the newly deprecated accessors to the new `Strict` functions. Followup patches will migrate the remaining callers. (There are a large number of callers, with some subtlety involved in some of them, so it makes sense to split this up into multiple patches rather than migrating all callers in one go.)
The `Strict` accessors as implemented here have some differences in semantics compared to the semantics originally proposed in the RFC; specifically:
* `setStorageLocationStrict()`: The RFC proposes to create an intermediate
`ReferenceValue` that then refers to the `StorageLocation` for the glvalue.
It turns out though that, even today, most places in the code are not doing
this but are instead associating glvalues directly with their
`StorageLocation`. It therefore didn't seem to make sense to introduce new
`ReferenceValue`s where there were none previously, so I have chosen to
instead make `setStorageLocationStrict()` simply call through to
`setStorageLocation(const Expr &, StorageLocation &)` and merely add the
assertion that the expression must be a glvalue.
* `getStorageLocationStrict()`: The RFC proposes that this should assert that
the storage location for the glvalue expression is associated with an
intermediate `ReferenceValue`, but, as explained, this is often not true.
The current state is inconsistent: Sometimes the intermediate
`ReferenceValue` is there, sometimes it isn't. For this reason,
`getStorageLocationStrict()` skips past a `ReferenceValue` if it is there but
otherwise directly returns the storage location associated with the
expression. This behavior is equivalent to the existing behavior of
`SkipPast::Reference`.
* `setValueStrict()`: The RFC proposes that this should always create the same
`StorageLocation` for a given `Value`, but, in fact, the transfer functions
that exist today don't guarantee this; almost all transfer functions
unconditionally create a new `StorageLocation` when associating an expression
with a `Value`.
There appears to be one special case:
`TerminatorVisitor::extendFlowCondition()` checks whether the expression is
already associated with a `StorageLocation` and, if so, reuses the existing
`StorageLocation` instead of creating a new one.
For this reason, `setValueStrict()` implements this logic (preserve an
existing `StorageLocation`) but makes no attempt to always associate the same
`StorageLocation` with a given `Value`, as nothing in the framework appers to
require this.
As `TerminatorVisitor::extendFlowCondition()` is an interesting special case,
the `setValue()` call there is among the ones that this patch migrates to
`setValueStrict()`.
Reviewed By: sammccall, ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D150653
2023-05-17 09:12:46 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
Value *Environment::getValue(const StorageLocation &Loc) const {
|
2024-04-19 09:39:52 +02:00
|
|
|
// Records should not be associated with values.
|
|
|
|
assert(!isa<RecordStorageLocation>(Loc));
|
2023-06-12 08:11:01 -07:00
|
|
|
return LocToVal.lookup(&Loc);
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-05-08 19:08:36 +00:00
|
|
|
Value *Environment::getValue(const ValueDecl &D) const {
|
2023-05-08 06:38:42 +00:00
|
|
|
auto *Loc = getStorageLocation(D);
|
2022-01-04 13:47:14 +00:00
|
|
|
if (Loc == nullptr)
|
|
|
|
return nullptr;
|
|
|
|
return getValue(*Loc);
|
|
|
|
}
|
|
|
|
|
2023-07-31 12:36:37 +00:00
|
|
|
Value *Environment::getValue(const Expr &E) const {
|
2024-04-19 09:39:52 +02:00
|
|
|
// Records should not be associated with values.
|
|
|
|
assert(!E.getType()->isRecordType());
|
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
if (E.isPRValue()) {
|
|
|
|
auto It = ExprToVal.find(&ignoreCFGOmittedNodes(E));
|
|
|
|
return It == ExprToVal.end() ? nullptr : It->second;
|
|
|
|
}
|
|
|
|
|
2023-07-31 12:36:37 +00:00
|
|
|
auto It = ExprToLoc.find(&ignoreCFGOmittedNodes(E));
|
|
|
|
if (It == ExprToLoc.end())
|
2022-01-04 13:47:14 +00:00
|
|
|
return nullptr;
|
2023-07-31 12:36:37 +00:00
|
|
|
return getValue(*It->second);
|
[clang][dataflow] Add `Strict` versions of `Value` and `StorageLocation` accessors.
This is part of the gradual migration to strict handling of value categories, as described in the RFC at https://discourse.llvm.org/t/70086.
This patch migrates some representative calls of the newly deprecated accessors to the new `Strict` functions. Followup patches will migrate the remaining callers. (There are a large number of callers, with some subtlety involved in some of them, so it makes sense to split this up into multiple patches rather than migrating all callers in one go.)
The `Strict` accessors as implemented here have some differences in semantics compared to the semantics originally proposed in the RFC; specifically:
* `setStorageLocationStrict()`: The RFC proposes to create an intermediate
`ReferenceValue` that then refers to the `StorageLocation` for the glvalue.
It turns out though that, even today, most places in the code are not doing
this but are instead associating glvalues directly with their
`StorageLocation`. It therefore didn't seem to make sense to introduce new
`ReferenceValue`s where there were none previously, so I have chosen to
instead make `setStorageLocationStrict()` simply call through to
`setStorageLocation(const Expr &, StorageLocation &)` and merely add the
assertion that the expression must be a glvalue.
* `getStorageLocationStrict()`: The RFC proposes that this should assert that
the storage location for the glvalue expression is associated with an
intermediate `ReferenceValue`, but, as explained, this is often not true.
The current state is inconsistent: Sometimes the intermediate
`ReferenceValue` is there, sometimes it isn't. For this reason,
`getStorageLocationStrict()` skips past a `ReferenceValue` if it is there but
otherwise directly returns the storage location associated with the
expression. This behavior is equivalent to the existing behavior of
`SkipPast::Reference`.
* `setValueStrict()`: The RFC proposes that this should always create the same
`StorageLocation` for a given `Value`, but, in fact, the transfer functions
that exist today don't guarantee this; almost all transfer functions
unconditionally create a new `StorageLocation` when associating an expression
with a `Value`.
There appears to be one special case:
`TerminatorVisitor::extendFlowCondition()` checks whether the expression is
already associated with a `StorageLocation` and, if so, reuses the existing
`StorageLocation` instead of creating a new one.
For this reason, `setValueStrict()` implements this logic (preserve an
existing `StorageLocation`) but makes no attempt to always associate the same
`StorageLocation` with a given `Value`, as nothing in the framework appers to
require this.
As `TerminatorVisitor::extendFlowCondition()` is an interesting special case,
the `setValue()` call there is among the ones that this patch migrates to
`setValueStrict()`.
Reviewed By: sammccall, ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D150653
2023-05-17 09:12:46 +00:00
|
|
|
}
|
|
|
|
|
2022-01-17 15:17:05 +00:00
|
|
|
Value *Environment::createValue(QualType Type) {
|
2021-12-29 11:31:02 +00:00
|
|
|
llvm::DenseSet<QualType> Visited;
|
2022-02-24 20:02:00 +00:00
|
|
|
int CreatedValuesCount = 0;
|
|
|
|
Value *Val = createValueUnlessSelfReferential(Type, Visited, /*Depth=*/0,
|
|
|
|
CreatedValuesCount);
|
|
|
|
if (CreatedValuesCount > MaxCompositeValueSize) {
|
2022-04-20 22:09:03 +01:00
|
|
|
llvm::errs() << "Attempting to initialize a huge value of type: " << Type
|
|
|
|
<< '\n';
|
2022-02-24 20:02:00 +00:00
|
|
|
}
|
|
|
|
return Val;
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2022-01-17 15:17:05 +00:00
|
|
|
Value *Environment::createValueUnlessSelfReferential(
|
2022-02-24 20:02:00 +00:00
|
|
|
QualType Type, llvm::DenseSet<QualType> &Visited, int Depth,
|
|
|
|
int &CreatedValuesCount) {
|
2021-12-29 11:31:02 +00:00
|
|
|
assert(!Type.isNull());
|
2023-07-26 12:30:32 +00:00
|
|
|
assert(!Type->isReferenceType());
|
2024-04-19 09:39:52 +02:00
|
|
|
assert(!Type->isRecordType());
|
2021-12-29 11:31:02 +00:00
|
|
|
|
2022-02-24 20:02:00 +00:00
|
|
|
// Allow unlimited fields at depth 1; only cap at deeper nesting levels.
|
|
|
|
if ((Depth > 1 && CreatedValuesCount > MaxCompositeValueSize) ||
|
|
|
|
Depth > MaxCompositeValueDepth)
|
|
|
|
return nullptr;
|
|
|
|
|
2022-03-04 11:03:29 +00:00
|
|
|
if (Type->isBooleanType()) {
|
|
|
|
CreatedValuesCount++;
|
|
|
|
return &makeAtomicBoolValue();
|
|
|
|
}
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
if (Type->isIntegerType()) {
|
2022-11-03 00:36:58 +00:00
|
|
|
// FIXME: consider instead `return nullptr`, given that we do nothing useful
|
|
|
|
// with integers, and so distinguishing them serves no purpose, but could
|
|
|
|
// prevent convergence.
|
2022-02-24 20:02:00 +00:00
|
|
|
CreatedValuesCount++;
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
return &arena().create<IntegerValue>();
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-07-26 12:30:32 +00:00
|
|
|
if (Type->isPointerType()) {
|
2022-02-24 20:02:00 +00:00
|
|
|
CreatedValuesCount++;
|
2023-04-05 11:20:33 +00:00
|
|
|
QualType PointeeType = Type->getPointeeType();
|
2023-07-20 11:12:39 +00:00
|
|
|
StorageLocation &PointeeLoc =
|
|
|
|
createLocAndMaybeValue(PointeeType, Visited, Depth, CreatedValuesCount);
|
2021-12-29 11:31:02 +00:00
|
|
|
|
2023-07-26 12:30:32 +00:00
|
|
|
return &arena().create<PointerValue>(PointeeLoc);
|
2021-12-29 11:31:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2023-07-20 11:12:39 +00:00
|
|
|
StorageLocation &
|
|
|
|
Environment::createLocAndMaybeValue(QualType Ty,
|
|
|
|
llvm::DenseSet<QualType> &Visited,
|
|
|
|
int Depth, int &CreatedValuesCount) {
|
|
|
|
if (!Visited.insert(Ty.getCanonicalType()).second)
|
|
|
|
return createStorageLocation(Ty.getNonReferenceType());
|
2024-04-19 09:39:52 +02:00
|
|
|
auto EraseVisited = llvm::make_scope_exit(
|
|
|
|
[&Visited, Ty] { Visited.erase(Ty.getCanonicalType()); });
|
2023-07-20 11:12:39 +00:00
|
|
|
|
|
|
|
Ty = Ty.getNonReferenceType();
|
|
|
|
|
2024-04-19 09:39:52 +02:00
|
|
|
if (Ty->isRecordType()) {
|
|
|
|
auto &Loc = cast<RecordStorageLocation>(createStorageLocation(Ty));
|
|
|
|
initializeFieldsWithValues(Loc, Ty, Visited, Depth, CreatedValuesCount);
|
|
|
|
return Loc;
|
|
|
|
}
|
2023-07-20 11:12:39 +00:00
|
|
|
|
|
|
|
StorageLocation &Loc = createStorageLocation(Ty);
|
2024-04-19 09:39:52 +02:00
|
|
|
|
|
|
|
if (Value *Val = createValueUnlessSelfReferential(Ty, Visited, Depth,
|
|
|
|
CreatedValuesCount))
|
|
|
|
setValue(Loc, *Val);
|
|
|
|
|
2023-07-20 11:12:39 +00:00
|
|
|
return Loc;
|
|
|
|
}
|
|
|
|
|
2024-02-13 10:01:25 +01:00
|
|
|
void Environment::initializeFieldsWithValues(RecordStorageLocation &Loc,
|
2024-04-11 08:20:35 +02:00
|
|
|
QualType Type,
|
2024-02-13 10:01:25 +01:00
|
|
|
llvm::DenseSet<QualType> &Visited,
|
|
|
|
int Depth,
|
|
|
|
int &CreatedValuesCount) {
|
|
|
|
auto initField = [&](QualType FieldType, StorageLocation &FieldLoc) {
|
|
|
|
if (FieldType->isRecordType()) {
|
|
|
|
auto &FieldRecordLoc = cast<RecordStorageLocation>(FieldLoc);
|
2024-04-11 08:20:35 +02:00
|
|
|
initializeFieldsWithValues(FieldRecordLoc, FieldRecordLoc.getType(),
|
|
|
|
Visited, Depth + 1, CreatedValuesCount);
|
2024-02-13 10:01:25 +01:00
|
|
|
} else {
|
2024-04-19 09:39:52 +02:00
|
|
|
if (getValue(FieldLoc) != nullptr)
|
|
|
|
return;
|
2024-02-13 10:01:25 +01:00
|
|
|
if (!Visited.insert(FieldType.getCanonicalType()).second)
|
|
|
|
return;
|
|
|
|
if (Value *Val = createValueUnlessSelfReferential(
|
|
|
|
FieldType, Visited, Depth + 1, CreatedValuesCount))
|
|
|
|
setValue(FieldLoc, *Val);
|
|
|
|
Visited.erase(FieldType.getCanonicalType());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
for (const FieldDecl *Field : DACtx->getModeledFields(Type)) {
|
2024-02-13 10:01:25 +01:00
|
|
|
assert(Field != nullptr);
|
|
|
|
QualType FieldType = Field->getType();
|
|
|
|
|
|
|
|
if (FieldType->isReferenceType()) {
|
|
|
|
Loc.setChild(*Field,
|
|
|
|
&createLocAndMaybeValue(FieldType, Visited, Depth + 1,
|
|
|
|
CreatedValuesCount));
|
|
|
|
} else {
|
2024-04-11 08:20:35 +02:00
|
|
|
StorageLocation *FieldLoc = Loc.getChild(*Field);
|
2024-02-13 10:01:25 +01:00
|
|
|
assert(FieldLoc != nullptr);
|
|
|
|
initField(FieldType, *FieldLoc);
|
|
|
|
}
|
|
|
|
}
|
2024-04-11 08:20:35 +02:00
|
|
|
for (const auto &[FieldName, FieldType] : DACtx->getSyntheticFields(Type)) {
|
2024-02-13 10:01:25 +01:00
|
|
|
// Synthetic fields cannot have reference type, so we don't need to deal
|
|
|
|
// with this case.
|
|
|
|
assert(!FieldType->isReferenceType());
|
|
|
|
initField(FieldType, Loc.getSyntheticField(FieldName));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-11 22:18:46 +02:00
|
|
|
StorageLocation &Environment::createObjectInternal(const ValueDecl *D,
|
2023-07-17 06:27:59 +00:00
|
|
|
QualType Ty,
|
|
|
|
const Expr *InitExpr) {
|
|
|
|
if (Ty->isReferenceType()) {
|
|
|
|
// Although variables of reference type always need to be initialized, it
|
|
|
|
// can happen that we can't see the initializer, so `InitExpr` may still
|
|
|
|
// be null.
|
|
|
|
if (InitExpr) {
|
2023-07-31 12:37:01 +00:00
|
|
|
if (auto *InitExprLoc = getStorageLocation(*InitExpr))
|
2024-04-19 10:12:57 +02:00
|
|
|
return *InitExprLoc;
|
2023-07-17 06:27:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Even though we have an initializer, we might not get an
|
|
|
|
// InitExprLoc, for example if the InitExpr is a CallExpr for which we
|
|
|
|
// don't have a function body. In this case, we just invent a storage
|
|
|
|
// location and value -- it's the best we can do.
|
|
|
|
return createObjectInternal(D, Ty.getNonReferenceType(), nullptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
StorageLocation &Loc =
|
|
|
|
D ? createStorageLocation(*D) : createStorageLocation(Ty);
|
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
if (Ty->isRecordType()) {
|
|
|
|
auto &RecordLoc = cast<RecordStorageLocation>(Loc);
|
|
|
|
if (!InitExpr)
|
|
|
|
initializeFieldsWithValues(RecordLoc);
|
|
|
|
} else {
|
|
|
|
Value *Val = nullptr;
|
|
|
|
if (InitExpr)
|
|
|
|
// In the (few) cases where an expression is intentionally
|
|
|
|
// "uninterpreted", `InitExpr` is not associated with a value. There are
|
|
|
|
// two ways to handle this situation: propagate the status, so that
|
|
|
|
// uninterpreted initializers result in uninterpreted variables, or
|
|
|
|
// provide a default value. We choose the latter so that later refinements
|
|
|
|
// of the variable can be used for reasoning about the surrounding code.
|
|
|
|
// For this reason, we let this case be handled by the `createValue()`
|
|
|
|
// call below.
|
|
|
|
//
|
|
|
|
// FIXME. If and when we interpret all language cases, change this to
|
|
|
|
// assert that `InitExpr` is interpreted, rather than supplying a
|
|
|
|
// default value (assuming we don't update the environment API to return
|
|
|
|
// references).
|
|
|
|
Val = getValue(*InitExpr);
|
|
|
|
if (!Val)
|
|
|
|
Val = createValue(Ty);
|
|
|
|
if (Val)
|
|
|
|
setValue(Loc, *Val);
|
|
|
|
}
|
2023-07-17 06:27:59 +00:00
|
|
|
|
|
|
|
return Loc;
|
|
|
|
}
|
|
|
|
|
[clang][dataflow] Add `Environment::allows()`. (#70046)
This allows querying whether, given the flow condition, a certain
formula still
has a solution (though it is not necessarily implied by the flow
condition, as
`flowConditionImplies()` would check).
This can be checked today, but only with a double negation, i.e. to
check
whether, given the flow condition, a formula F has a solution, you can
check
`!Env.flowConditionImplies(Arena.makeNot(F))`. The double negation makes
this
hard to reason about, and it would be nicer to have a way of directly
checking
this.
For consistency, this patch also renames `flowConditionImplies()` to
`proves()`;
the old name is kept around for compatibility but deprecated.
2023-10-25 16:02:22 +02:00
|
|
|
void Environment::assume(const Formula &F) {
|
|
|
|
DACtx->addFlowConditionConstraint(FlowConditionToken, F);
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
}
|
2022-03-01 11:19:00 +00:00
|
|
|
|
[clang][dataflow] Add `Environment::allows()`. (#70046)
This allows querying whether, given the flow condition, a certain
formula still
has a solution (though it is not necessarily implied by the flow
condition, as
`flowConditionImplies()` would check).
This can be checked today, but only with a double negation, i.e. to
check
whether, given the flow condition, a formula F has a solution, you can
check
`!Env.flowConditionImplies(Arena.makeNot(F))`. The double negation makes
this
hard to reason about, and it would be nicer to have a way of directly
checking
this.
For consistency, this patch also renames `flowConditionImplies()` to
`proves()`;
the old name is kept around for compatibility but deprecated.
2023-10-25 16:02:22 +02:00
|
|
|
bool Environment::proves(const Formula &F) const {
|
|
|
|
return DACtx->flowConditionImplies(FlowConditionToken, F);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Environment::allows(const Formula &F) const {
|
|
|
|
return DACtx->flowConditionAllows(FlowConditionToken, F);
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
}
|
2022-03-01 11:19:00 +00:00
|
|
|
|
2023-01-13 19:26:57 +00:00
|
|
|
void Environment::dump(raw_ostream &OS) const {
|
2024-01-31 08:11:13 +01:00
|
|
|
llvm::DenseMap<const StorageLocation *, std::string> LocToName;
|
2024-04-11 08:20:35 +02:00
|
|
|
if (LocForRecordReturnVal != nullptr)
|
|
|
|
LocToName[LocForRecordReturnVal] = "(returned record)";
|
2024-01-31 08:11:13 +01:00
|
|
|
if (ThisPointeeLoc != nullptr)
|
|
|
|
LocToName[ThisPointeeLoc] = "this";
|
2023-01-13 19:26:57 +00:00
|
|
|
|
2024-01-31 08:11:13 +01:00
|
|
|
OS << "DeclToLoc:\n";
|
|
|
|
for (auto [D, L] : DeclToLoc) {
|
|
|
|
auto Iter = LocToName.insert({L, D->getNameAsString()}).first;
|
|
|
|
OS << " [" << Iter->second << ", " << L << "]\n";
|
|
|
|
}
|
2023-01-13 19:26:57 +00:00
|
|
|
OS << "ExprToLoc:\n";
|
|
|
|
for (auto [E, L] : ExprToLoc)
|
|
|
|
OS << " [" << E << ", " << L << "]\n";
|
|
|
|
|
2023-08-28 11:50:03 +00:00
|
|
|
OS << "ExprToVal:\n";
|
|
|
|
for (auto [E, V] : ExprToVal)
|
2023-08-31 12:41:35 +00:00
|
|
|
OS << " [" << E << ", " << V << ": " << *V << "]\n";
|
2023-08-28 11:50:03 +00:00
|
|
|
|
2023-01-13 19:26:57 +00:00
|
|
|
OS << "LocToVal:\n";
|
|
|
|
for (auto [L, V] : LocToVal) {
|
2024-01-31 08:11:13 +01:00
|
|
|
OS << " [" << L;
|
|
|
|
if (auto Iter = LocToName.find(L); Iter != LocToName.end())
|
|
|
|
OS << " (" << Iter->second << ")";
|
|
|
|
OS << ", " << V << ": " << *V << "]\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
if (const FunctionDecl *Func = getCurrentFunc()) {
|
|
|
|
if (Func->getReturnType()->isReferenceType()) {
|
|
|
|
OS << "ReturnLoc: " << ReturnLoc;
|
|
|
|
if (auto Iter = LocToName.find(ReturnLoc); Iter != LocToName.end())
|
|
|
|
OS << " (" << Iter->second << ")";
|
|
|
|
OS << "\n";
|
2024-04-11 08:20:35 +02:00
|
|
|
} else if (Func->getReturnType()->isRecordType() ||
|
|
|
|
isa<CXXConstructorDecl>(Func)) {
|
|
|
|
OS << "LocForRecordReturnVal: " << LocForRecordReturnVal << "\n";
|
2024-01-31 08:11:13 +01:00
|
|
|
} else if (!Func->getReturnType()->isVoidType()) {
|
|
|
|
if (ReturnVal == nullptr)
|
|
|
|
OS << "ReturnVal: nullptr\n";
|
|
|
|
else
|
|
|
|
OS << "ReturnVal: " << *ReturnVal << "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isa<CXXMethodDecl>(Func)) {
|
|
|
|
OS << "ThisPointeeLoc: " << ThisPointeeLoc << "\n";
|
|
|
|
}
|
2023-01-13 19:26:57 +00:00
|
|
|
}
|
|
|
|
|
[clang][dataflow] Simplify flow conditions displayed in HTMLLogger. (#70848)
This can make the flow condition significantly easier to interpret; see
below
for an example.
I had hoped that adding the simplification as a preprocessing step
before the
SAT solver (in `DataflowAnalysisContext::querySolver()`) would also
speed up SAT
solving and maybe even eliminate SAT solver timeouts, but in my testing,
this
actually turns out to be a pessimization. It appears that these
simplifications
are easy enough for the SAT solver to perform itself.
Nevertheless, the improvement in debugging alone makes this a worthwhile
change.
Example of flow condition output with these changes:
```
Flow condition token: V37
Constraints:
(V16 = (((V15 & (V19 = V12)) & V22) & V25))
(V15 = ((V12 & ((V14 = V9) | (V14 = V4))) & (V13 = V14)))
True atoms: (V0, V1, V2, V5, V6, V7, V29, V30, V32, V34, V35, V37)
False atoms: (V3, V8, V17)
Equivalent atoms:
(V11, V15)
Flow condition constraints before simplification:
V37
((!V3 & !V8) & !V17)
(V37 = V34)
(V34 = (V29 & (V35 = V30)))
(V29 = (((V16 | V2) & V32) & (V30 = V32)))
(V16 = (((V15 & (V19 = V12)) & V22) & V25))
(V15 = V11)
(V11 = ((((V7 | V2) & V12) & ((V7 & (V14 = V9)) | (V2 & (V14 = V4)))) & (V13 = V14)))
(V2 = V1)
(V1 = V0)
V0
(V7 = V6)
(V6 = V5)
(V5 = V2)
```
2023-11-07 15:18:34 +01:00
|
|
|
OS << "\n";
|
Reland "[dataflow] Add dedicated representation of boolean formulas"
This reverts commit 7a72ce98224be76d9328e65eee472381f7c8e7fe.
Test problems were due to unspecified order of function arg evaluation.
Reland "[dataflow] Replace most BoolValue subclasses with references to Formula (and AtomicBoolValue => Atom and BoolValue => Formula where appropriate)"
This properly frees the Value hierarchy from managing boolean formulas.
We still distinguish AtomicBoolValue; this type is used in client code.
However we expect to convert such uses to BoolValue (where the
distinction is not needed) or Atom (where atomic identity is intended),
and then fold AtomicBoolValue into FormulaBoolValue.
We also distinguish TopBoolValue; this has distinct rules for
widen/join/equivalence, and top-ness is not represented in Formula.
It'd be nice to find a cleaner representation (e.g. the absence of a
formula), but no immediate plans.
For now, BoolValues with the same Formula are deduplicated. This doesn't
seem desirable, as Values are mutable by their creators (properties).
We can probably drop this for FormulaBoolValue immediately (not in this
patch, to isolate changes). For AtomicBoolValue we first need to update
clients to stop using value pointers for atom identity.
The data structures around flow conditions are updated:
- flow condition tokens are Atom, rather than AtomicBoolValue*
- conditions are Formula, rather than BoolValue
Most APIs were changed directly, some with many clients had a
new version added and the existing one deprecated.
The factories for BoolValues in Environment keep their existing
signatures for now (e.g. makeOr(BoolValue, BoolValue) => BoolValue)
and are not deprecated. These have very many clients and finding the
most ergonomic API & migration path still needs some thought.
Differential Revision: https://reviews.llvm.org/D153469
2023-07-05 11:35:06 +02:00
|
|
|
DACtx->dumpFlowCondition(FlowConditionToken, OS);
|
2022-07-23 01:23:17 +02:00
|
|
|
}
|
|
|
|
|
2024-04-19 10:12:57 +02:00
|
|
|
void Environment::dump() const { dump(llvm::dbgs()); }
|
2023-01-13 19:26:57 +00:00
|
|
|
|
2024-04-11 08:20:35 +02:00
|
|
|
Environment::PrValueToResultObject Environment::buildResultObjectMap(
|
|
|
|
DataflowAnalysisContext *DACtx, const FunctionDecl *FuncDecl,
|
|
|
|
RecordStorageLocation *ThisPointeeLoc,
|
|
|
|
RecordStorageLocation *LocForRecordReturnVal) {
|
|
|
|
assert(FuncDecl->doesThisDeclarationHaveABody());
|
|
|
|
|
|
|
|
PrValueToResultObject Map;
|
|
|
|
|
|
|
|
ResultObjectVisitor Visitor(Map, LocForRecordReturnVal, *DACtx);
|
|
|
|
if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FuncDecl))
|
|
|
|
Visitor.TraverseConstructorInits(Ctor, ThisPointeeLoc);
|
|
|
|
Visitor.TraverseStmt(FuncDecl->getBody());
|
|
|
|
|
|
|
|
return Map;
|
|
|
|
}
|
|
|
|
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
RecordStorageLocation *getImplicitObjectLocation(const CXXMemberCallExpr &MCE,
|
|
|
|
const Environment &Env) {
|
2023-05-12 11:59:21 +00:00
|
|
|
Expr *ImplicitObject = MCE.getImplicitObjectArgument();
|
|
|
|
if (ImplicitObject == nullptr)
|
|
|
|
return nullptr;
|
|
|
|
if (ImplicitObject->getType()->isPointerType()) {
|
2023-12-21 09:02:20 +01:00
|
|
|
if (auto *Val = Env.get<PointerValue>(*ImplicitObject))
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
return &cast<RecordStorageLocation>(Val->getPointeeLoc());
|
2023-05-12 11:59:21 +00:00
|
|
|
return nullptr;
|
|
|
|
}
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
return cast_or_null<RecordStorageLocation>(
|
2023-07-31 12:37:01 +00:00
|
|
|
Env.getStorageLocation(*ImplicitObject));
|
2023-05-12 11:59:21 +00:00
|
|
|
}
|
|
|
|
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
|
|
|
|
const Environment &Env) {
|
2023-05-12 11:59:21 +00:00
|
|
|
Expr *Base = ME.getBase();
|
|
|
|
if (Base == nullptr)
|
|
|
|
return nullptr;
|
|
|
|
if (ME.isArrow()) {
|
2023-12-21 09:02:20 +01:00
|
|
|
if (auto *Val = Env.get<PointerValue>(*Base))
|
[clang][dataflow] Rename `AggregateStorageLocation` to `RecordStorageLocation` and `StructValue` to `RecordValue`.
- Both of these constructs are used to represent structs, classes, and unions;
Clang uses the collective term "record" for these.
- The term "aggregate" in `AggregateStorageLocation` implies that, at some
point, the intention may have been to use it also for arrays, but it don't
think it's possible to use it for arrays. Records and arrays are very
different and therefore need to be modeled differently. Records have a fixed
set of named fields, which can have different type; arrays have a variable
number of elements, but they all have the same type.
- Futhermore, "aggregate" has a very specific meaning in C++
(https://en.cppreference.com/w/cpp/language/aggregate_initialization).
Aggregates of class type may not have any user-declared or inherited
constructors, no private or protected non-static data members, no virtual
member functions, and so on, but we use `AggregateStorageLocations` to model all objects of class type.
In addition, for consistency, we also rename the following:
- `getAggregateLoc()` (in `RecordValue`, formerly known as `StructValue`) to
simply `getLoc()`.
- `refreshStructValue()` to `refreshRecordValue()`
We keep the old names around as deprecated synonyms to enable clients to be migrated to the new names.
Reviewed By: ymandel, xazax.hun
Differential Revision: https://reviews.llvm.org/D156788
2023-08-01 13:23:37 +00:00
|
|
|
return &cast<RecordStorageLocation>(Val->getPointeeLoc());
|
2023-05-12 11:59:21 +00:00
|
|
|
return nullptr;
|
|
|
|
}
|
2023-12-21 09:02:20 +01:00
|
|
|
return Env.get<RecordStorageLocation>(*Base);
|
2023-05-12 11:59:21 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 11:31:02 +00:00
|
|
|
} // namespace dataflow
|
|
|
|
} // namespace clang
|