https://github.com/jcsxky updated https://github.com/llvm/llvm-project/pull/68510
>From 3978a4322ed7f82b52a1978debe8108f00f18acc Mon Sep 17 00:00:00 2001 From: huqizhi <huqi...@feysh.com> Date: Sun, 8 Oct 2023 16:00:29 +0800 Subject: [PATCH] [clang][analysis]Use dyn_cast_or_null instead cast to prevent crash --- .../bugprone/unchecked-optional-access.cpp | 41 +++++++++++++++++++ .../Models/UncheckedOptionalAccessModel.cpp | 3 +- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp index 1921291f2187d92..c797a263a3220b8 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp @@ -180,3 +180,44 @@ void std_forward_rvalue_ref_safe(absl::optional<int>&& opt) { std::forward<absl::optional<int>>(opt).value(); } + +namespace std { + +template<typename T> +class optional { +public: + template <typename U> + optional& operator=(const U &u){ + data = u; + } +private: + T data; +}; + +template <typename T> +class vector { +public: + vector() {} + T &operator[](unsigned long index) { return data[index]; } + bool empty() { return size == 0UL; } + +private: + T *data; + unsigned long size; +}; + +} // namespace std + +struct LinearGradient { + struct Stop { + std::optional<float> position; + }; + std::vector<Stop> stops; +}; + + +void use_dyn_cast_or_null() { + LinearGradient gradient; + if (!gradient.stops.empty()) + gradient.stops[0].position = 0; +} diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp index f61f26ff27804ec..f60510c9bc93f81 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp @@ -26,6 +26,7 @@ #include "clang/Analysis/FlowSensitive/NoopLattice.h" #include "clang/Analysis/FlowSensitive/StorageLocation.h" #include "clang/Analysis/FlowSensitive/Value.h" +#include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" @@ -599,7 +600,7 @@ void transferAssignment(const CXXOperatorCallExpr *E, BoolValue &HasValueVal, LatticeTransferState &State) { assert(E->getNumArgs() > 0); - if (auto *Loc = cast<RecordStorageLocation>( + if (auto *Loc = cast_or_null<RecordStorageLocation>( State.Env.getStorageLocation(*E->getArg(0)))) { createOptionalValue(*Loc, HasValueVal, State.Env); _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits