llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang Author: Valentyn Yukhymenko (BaLiKfromUA) <details> <summary>Changes</summary> This is the first part of a split of #<!-- -->233219 . It adds only the base dataflow model and its unit tests. Model supports `std::expected` as well as `tl::expected` from https://github.com/TartanLlama/expected since it's a very popular backport option in a codebase where I work. And API differences are minimal. The clang-tidy check and the rest of the modeling will follow in separate PRs. Current expected scope of diagnostics: ```cpp void f(std::expected<int, int> e) { e.value(); // diagnosed: unchecked value access if (e) { *e; // ok e.error(); // diagnosed: unchecked error access } else { e.error(); // ok } } ``` #### AI usage I used AI to split my big end-to-end PR (#<!-- -->233219) as well as port `clang-tidy` style tests to `clang` model unit tests. I also describe how I used AI for #<!-- -->233219 Assisted-by: Claude Opus 5.5 --- Patch is 37.57 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/242868.diff 6 Files Affected: - (added) clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h (+92) - (modified) clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt (+1) - (added) clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp (+202) - (modified) clang/unittests/Analysis/FlowSensitive/CMakeLists.txt (+1) - (modified) clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp (+271) - (added) clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp (+588) ``````````diff diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h new file mode 100644 index 00000000000000..2928bc172fc24c --- /dev/null +++ b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h @@ -0,0 +1,92 @@ +//===-- UncheckedExpectedAccessModel.h --------------------------*- 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 a dataflow analysis that detects unsafe accesses to the +// values of `std::expected` and `tl::expected` objects. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H +#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H + +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Analysis/CFG.h" +#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h" +#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h" +#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" +#include "clang/Analysis/FlowSensitive/NoopLattice.h" +#include "clang/Basic/SourceLocation.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" + +namespace clang { +namespace dataflow { + +/// Dataflow analysis that models whether expected objects hold values. +/// +/// Supported types are `std::expected` and `tl::expected` +/// (https://github.com/TartanLlama/expected). +class UncheckedExpectedAccessModel + : public DataflowAnalysis<UncheckedExpectedAccessModel, NoopLattice> { +public: + UncheckedExpectedAccessModel(ASTContext &Ctx, Environment &Env); + + /// Returns a matcher for calls to member functions of a supported expected + /// type. + static ast_matchers::StatementMatcher callToExpectedClass(); + + static NoopLattice initialElement() { return {}; } + + void transfer(const CFGElement &Elt, NoopLattice &L, Environment &Env); + +private: + CFGMatchSwitch<TransferState<NoopLattice>> TransferMatchSwitch; +}; + +/// The part of an expected object that is accessed. +/// +/// The values are used as `%select` indices in diagnostics, so they must not +/// be reordered. +enum class UncheckedExpectedAccessKind : int { + /// `value()`, `operator*` or `operator->`, which require a value. + Value = 0, + /// `error()`, which requires an error. + Error = 1, +}; + +/// Diagnostic information for an unchecked expected access. +struct UncheckedExpectedAccessDiagnostic { + SourceLocation Loc; + UncheckedExpectedAccessKind Kind; + /// The accessed type, either "std::expected" or "tl::expected". + llvm::StringRef TypeName; +}; + +/// Reports accesses to the value (or error) of expected objects that are not +/// provably preceded by a check that the object holds a value (or error). +class UncheckedExpectedAccessDiagnoser { +public: + UncheckedExpectedAccessDiagnoser(); + + llvm::SmallVector<UncheckedExpectedAccessDiagnostic> + operator()(const CFGElement &Elt, ASTContext &Ctx, + const TransferStateForDiagnostics<NoopLattice> &State) { + return DiagnoseMatchSwitch(Elt, Ctx, State.Env); + } + +private: + CFGMatchSwitch<const Environment, + llvm::SmallVector<UncheckedExpectedAccessDiagnostic>> + DiagnoseMatchSwitch; +}; + +} // namespace dataflow +} // namespace clang + +#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H diff --git a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt index 62c9473842779d..41ab2c6fa786c5 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt +++ b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt @@ -1,5 +1,6 @@ add_clang_library(clangAnalysisFlowSensitiveModels ChromiumCheckModel.cpp + UncheckedExpectedAccessModel.cpp UncheckedOptionalAccessModel.cpp UncheckedStatusOrAccessModel.cpp GtestModelHelpers.cpp diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp new file mode 100644 index 00000000000000..6d44442ae04fff --- /dev/null +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -0,0 +1,202 @@ +//===-- UncheckedExpectedAccessModel.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 a dataflow analysis that detects unsafe accesses to the +// values of `std::expected` and `tl::expected` objects. +// +//===----------------------------------------------------------------------===// + +#include "clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/ExprCXX.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Analysis/FlowSensitive/Arena.h" +#include "clang/Analysis/FlowSensitive/Formula.h" +#include "clang/Analysis/FlowSensitive/StorageLocation.h" +#include "clang/Analysis/FlowSensitive/Value.h" + +namespace clang { +namespace dataflow { + +/// Returns true if `DC` is `std` or the top-level `tl` namespace, which holds +/// `tl::expected` (https://github.com/TartanLlama/expected). +static bool isSupportedNamespace(const DeclContext &DC) { + if (DC.isStdNamespace()) + return true; + const auto *NS = dyn_cast<NamespaceDecl>(&DC); + return NS != nullptr && NS->getDeclName().isIdentifier() && + NS->getName() == "tl" && NS->getParent()->isTranslationUnit(); +} + +static bool isExpectedClass(const CXXRecordDecl &RD) { + return RD.getDeclName().isIdentifier() && RD.getName() == "expected" && + isSupportedNamespace(*RD.getDeclContext()); +} + +/// Returns the name of the expected class `RD` to show in diagnostics. +static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD) { + return RD.getDeclContext()->isStdNamespace() ? "std::expected" + : "tl::expected"; +} + +// Classes derived from `std::expected` or `tl::expected` are deliberately not +// supported. +static bool isExpectedType(QualType Ty) { + const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); + return RD != nullptr && isExpectedClass(*RD); +} + +namespace { + +using namespace ::clang::ast_matchers; + +using LatticeTransferState = TransferState<NoopLattice>; + +AST_MATCHER(CXXRecordDecl, expectedClass) { return isExpectedClass(Node); } + +auto expectedMemberCall(ast_matchers::internal::Matcher<NamedDecl> Name) { + return cxxMemberCallExpr( + callee(cxxMethodDecl(Name, ofClass(expectedClass())))); +} + +auto expectedOperatorCall(ArrayRef<StringRef> Names) { + return cxxOperatorCallExpr(hasAnyOverloadedOperatorName(Names), + callee(cxxMethodDecl(ofClass(expectedClass())))); +} + +StorageLocation &locForHasValue(const RecordStorageLocation &ExpectedLoc) { + return ExpectedLoc.getSyntheticField("has_value"); +} + +/// Returns the symbolic value that represents the "has_value" property of the +/// expected at `ExpectedLoc`. Returns null if `ExpectedLoc` is null or is not +/// the location of a `std::expected` or `tl::expected` object (e.g. of a +/// derived class object). +BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) { + if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType())) + return nullptr; + StorageLocation &HasValueLoc = locForHasValue(*ExpectedLoc); + auto *HasValueVal = Env.get<BoolValue>(HasValueLoc); + if (HasValueVal == nullptr) { + HasValueVal = &Env.makeAtomicBoolValue(); + Env.setValue(HasValueLoc, *HasValueVal); + } + return HasValueVal; +} + +void transferHasValueCall(const CXXMemberCallExpr *E, + const MatchFinder::MatchResult &, + LatticeTransferState &State) { + if (BoolValue *HasValueVal = + getHasValue(State.Env, getImplicitObjectLocation(*E, State.Env))) + State.Env.setValue(*E, *HasValueVal); +} + +// FIXME: Model the constructors, assignments, `emplace` and `swap`. +auto buildTransferMatchSwitch() { + return CFGMatchSwitchBuilder<LatticeTransferState>() + // expected::has_value, expected::operator bool + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasAnyName("has_value", "operator bool")), + transferHasValueCall) + .Build(); +} + +/// `ExpectedClass` is the class of the called accessor. +llvm::SmallVector<UncheckedExpectedAccessDiagnostic> +diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, + const CXXRecordDecl &ExpectedClass, + const RecordStorageLocation *ExpectedLoc, + const Environment &Env) { + if (ExpectedLoc != nullptr) { + // Accesses through classes derived from an expected are not modeled. + if (!isExpectedType(ExpectedLoc->getType())) + return {}; + if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) { + // The value may only be accessed if the expected holds a value, and the + // error only if it does not. + const Formula &Safe = Kind == UncheckedExpectedAccessKind::Value + ? HasValueVal->formula() + : Env.arena().makeNot(HasValueVal->formula()); + if (Env.proves(Safe)) + return {}; + } + } + + return {{AccessLoc, Kind, getExpectedTypeName(ExpectedClass)}}; +} + +auto buildDiagnoseMatchSwitch() { + return CFGMatchSwitchBuilder< + const Environment, + llvm::SmallVector<UncheckedExpectedAccessDiagnostic>>() + // expected::value + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasName("value")), + [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + return diagnoseAccess(E->getExprLoc(), + UncheckedExpectedAccessKind::Value, + *E->getMethodDecl()->getParent(), + getImplicitObjectLocation(*E, Env), Env); + }) + // expected::operator*, expected::operator-> + .CaseOfCFGStmt<CXXOperatorCallExpr>( + expectedOperatorCall({"*", "->"}), + [](const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + // `getExprLoc` of `operator->` is the start of the object + // expression, so point at the operator token instead. + return diagnoseAccess( + E->getOperatorLoc(), UncheckedExpectedAccessKind::Value, + *cast<CXXMethodDecl>(E->getCalleeDecl())->getParent(), + Env.get<RecordStorageLocation>(*E->getArg(0)), Env); + }) + // expected::error + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasName("error")), + [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + return diagnoseAccess(E->getExprLoc(), + UncheckedExpectedAccessKind::Error, + *E->getMethodDecl()->getParent(), + getImplicitObjectLocation(*E, Env), Env); + }) + .Build(); +} + +} // namespace + +ast_matchers::StatementMatcher +UncheckedExpectedAccessModel::callToExpectedClass() { + return callExpr(callee(cxxMethodDecl(ofClass(expectedClass())))); +} + +UncheckedExpectedAccessModel::UncheckedExpectedAccessModel(ASTContext &Ctx, + Environment &Env) + : DataflowAnalysis<UncheckedExpectedAccessModel, NoopLattice>(Ctx), + TransferMatchSwitch(buildTransferMatchSwitch()) { + Env.getDataflowAnalysisContext().setSyntheticFieldCallback( + [&Ctx](QualType Ty) -> llvm::StringMap<QualType> { + if (!isExpectedType(Ty)) + return {}; + return {{"has_value", Ctx.BoolTy}}; + }); +} + +void UncheckedExpectedAccessModel::transfer(const CFGElement &Elt, + NoopLattice &L, Environment &Env) { + LatticeTransferState State(L, Env); + TransferMatchSwitch(Elt, getASTContext(), State); +} + +UncheckedExpectedAccessDiagnoser::UncheckedExpectedAccessDiagnoser() + : DiagnoseMatchSwitch(buildDiagnoseMatchSwitch()) {} + +} // namespace dataflow +} // namespace clang diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt index 1d932ec6e8a963..8dae4d0c3282b2 100644 --- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt +++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt @@ -24,6 +24,7 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests TransferBranchTest.cpp TransferTest.cpp TypeErasedDataflowAnalysisTest.cpp + UncheckedExpectedAccessModelTest.cpp UncheckedOptionalAccessModelTest.cpp UncheckedStatusOrAccessModelTest.cpp UncheckedStatusOrAccessModelTestFixture.cpp diff --git a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp index 3601d3efbcf1bf..f325b913ae2c7f 100644 --- a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp +++ b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp @@ -820,6 +820,275 @@ constexpr bool operator!=(const T &value, const optional<U> &opt); } // namespace std )"; +static constexpr char StdExpectedHeader[] = R"( +#ifndef STD_EXPECTED_H +#define STD_EXPECTED_H + +namespace std { + +template <class E> class unexpected { +public: + unexpected(const unexpected &) = default; + unexpected(unexpected &&) = default; + + template <class Err = E> explicit unexpected(Err &&e); + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; +}; + +template <class E> unexpected(E) -> unexpected<E>; + +struct unexpect_t { + explicit unexpect_t() = default; +}; + +inline constexpr unexpect_t unexpect{}; + +template <class T, class E> class expected { +public: + using value_type = T; + using error_type = E; + using unexpected_type = unexpected<E>; + + expected(); + expected(const expected &); + expected(expected &&) noexcept; + + template <class U = T> expected(U &&v); + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + template <class... Args> + explicit expected(unexpect_t, Args &&...args); + + expected &operator=(const expected &); + expected &operator=(expected &&) noexcept; + + const T *operator->() const noexcept; + T *operator->() noexcept; + + const T &operator*() const & noexcept; + T &operator*() & noexcept; + const T &&operator*() const && noexcept; + T &&operator*() && noexcept; + + explicit operator bool() const noexcept; + bool has_value() const noexcept; + + const T &value() const &; + T &value() &; + const T &&value() const &&; + T &&value() &&; + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; + + template <class U> T value_or(U &&v) const &; + template <class U> T value_or(U &&v) &&; + + template <class G> E error_or(G &&e) const &; + template <class G> E error_or(G &&e) &&; + + template <class... Args> T &emplace(Args &&...args) noexcept; + + void swap(expected &rhs) noexcept; +}; + +template <class E> class expected<void, E> { +public: + using value_type = void; + using error_type = E; + using unexpected_type = unexpected<E>; + + expected() noexcept; + expected(const expected &); + expected(expected &&) noexcept; + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + template <class... Args> + explicit expected(unexpect_t, Args &&...args); + + expected &operator=(const expected &); + expected &operator=(expected &&) noexcept; + + explicit operator bool() const noexcept; + bool has_value() const noexcept; + + void operator*() const noexcept; + + void value() const &; + void value() &&; + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; + + template <class G> E error_or(G &&e) const &; + template <class G> E error_or(G &&e) &&; + + void emplace() noexcept; + + void swap(expected &rhs) noexcept; +}; + +} // namespace std + +#endif // STD_EXPECTED_H +)"; + +static constexpr char TlExpectedHeader[] = R"( +#ifndef TL_EXPECTED_H +#define TL_EXPECTED_H + +// Mock of `tl::expected` from https://github.com/TartanLlama/expected. +// +// Unlike `std::expected`, it has no `void` specialization. + +#include "std_type_traits.h" + +namespace tl { + +template <class T, class E> class expected; + +struct in_place_t { + explicit in_place_t() = default; +}; +static constexpr in_place_t in_place{}; + +template <class E> class unexpected { +public: + unexpected() = delete; + explicit unexpected(const E &e); + explicit unexpected(E &&e); + + const E &value() const &; + E &value() &; + E &&value() &&; + const E &&value() const &&; +}; + +template <class E> unexpected(E) -> unexpected<E>; + +template <class E> +unexpected<typename std::decay<E>::type> make_unexpected(E &&e); + +struct unexpect_t { + unexpect_t() = default; +}; +static constexpr unexpect_t unexpect{}; + +namespace detail { + +template <class> constexpr bool is_unexpected = false; +template <class E> constexpr bool is_unexpected<unexpected<E>> = true; + +} // namespace detail + +template <class T, class E> class expected { +public: + typedef T value_type; + typedef E error_type; + typedef unexpected<E> unexpected_type; + + constexpr expected() = default; + constexpr expected(const expected &rhs) = default; + constexpr expected(expected &&rhs) = default; + expected &operator=(const expected &rhs) = default; + expected &operator=(expected &&rhs) = default; + + template <class... Args> expected(in_place_t, Args &&...args); + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + template <class... Args> explicit expected(unexpect_t, Args &&...args); + + template <class U, class G, + std::enable_if_t<__is_constructible(T, const U &) && + __is_constructible(E, const G &)> * = nullptr> + expected(const expected<U, G> &rhs); + template <class U, class G, + std::enable_if_t<__is_constructible(T, U &&) && + __is_constructible(E, G &&)> * = nullptr> + expected(expected<U, G> &&rhs); + + template < + class U = T, + std::enable_if_t< + __is_constructible(T, U &&) && + !std::is_same<typename std::decay<U>::type, in_place_t>::value && + !std::is_same<typename std::decay<U>::type, unexpect_t>::value && + !std::is_same<typename std::decay<U>::type, expected>::value && + !detail::is_unexpected<typename std::decay<U>::type>> * = nullptr> + expected(U &&v); + + // `G` delays forming `T &`, which is ill-formed for `void`. + template < + class U = T, class G = T, + std::enable_if_t< + __is_constructible(T, U &&) && __is_assignable(G &, U &&) && + !std::is_same<typename std::decay<U>::type, expected>::value && + !detail::is_unexpected<typename std::decay<U>::type>> * = nullptr> + expected &operator=(U &&v); + + template <class G> expected &operator=(const unexpected<G> &rhs); + template <class G> expected &operator=(unexpected<G> &&rhs); + + template <class... Args> void emplace(Args &&...args); + + void swap(expected &rhs); + + const T *operator->() const; + T *operator->(); + + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + const U &operator*(... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/242868 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
