llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[clang][dataflow] Crashes in getChild with incorrect "base" StorageLocation after #127338

Open jvoung opened this issue 1 year ago • 17 comments

After #127338 we are seeing some crashes in bugprone-unchecked-optional-access checker in the dataflow framework.

New test to trigger the crash: https://github.com/llvm/llvm-project/pull/128065 inline:

   struct NonTrivDtor {
      NonTrivDtor(int x);
      ~NonTrivDtor() {}
    };
    struct Other {
      std::optional<int> x = std::nullopt;
      NonTrivDtor y = x.has_value() ? NonTrivDtor(*x) : NonTrivDtor(-1);
    };
    struct target {
      target() { Other{}; }
    };
  1. evaluating the ListInit for Other{} in the target ctor
  2. involves some default inits for y, which references this->x -- the this should be for Other
  3. but the this is being confused for target (also in target's ctor)

Example stack:

 #0 0x000056125e5df14b llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (clang/unittests/Analysis/FlowSensitive
/./ClangAnalysisFlowSensitiveTests+0x53a14b)
 #1 0x000056125e5dbe16 SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #2 0x00007f383c574590 (/lib/x86_64-linux-gnu/libc.so.6+0x3f590)
 #3 0x00007f383c5c33ac __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
 #4 0x00007f383c5744f2 raise ./signal/../sysdeps/posix/raise.c:27:6
 #5 0x00007f383c55d4ed abort ./stdlib/abort.c:81:7
 #6 0x00007f383c55d415 _nl_load_domain ./intl/loadmsgcat.c:1177:9
 #7 0x00007f383c56d012 (/lib/x86_64-linux-gnu/libc.so.6+0x38012)
 #8 0x000056125e3d64b2 clang::dataflow::RecordStorageLocation::getChild(clang::ValueDecl const&) const (clang/unit
tests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x3314b2)
 #9 0x000056125ed61b55 clang::dataflow::(anonymous namespace)::TransferVisitor::VisitMemberExpr(clang::MemberExpr const*) Transfer.cpp:0:0
#10 0x000056125ed64b9a clang::dataflow::transfer(clang::dataflow::StmtToEnvMap const&, clang::Stmt const&, clang::dataflow::Environment&, clang::dataflow::Environment::ValueModel&) (/
usr/local/google/home/jvoung/w/jvoung-llvm/llvm-project/build/tools/clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0xcbfb9a)
#11 0x000056125ed54a30 clang::dataflow::transferCFGBlock(clang::CFGBlock const&, clang::dataflow::(anonymous namespace)::AnalysisContext&, clang::dataflow::CFGEltCallbacksTypeErased c
onst&) TypeErasedDataflowAnalysis.cpp:0:0
#12 0x000056125ed55a26 clang::dataflow::runTypeErasedDataflowAnalysis(clang::dataflow::AdornedCFG const&, clang::dataflow::TypeErasedDataflowAnalysis&, clang::dataflow::Environment co
nst&, clang::dataflow::CFGEltCallbacksTypeErased const&, int) (clang/unittests/Analysis/FlowSensitive/./ClangAnaly
sisFlowSensitiveTests+0xcb0a26)
#13 0x000056125e5568d2 llvm::Error clang::dataflow::test::checkDataflow<clang::dataflow::UncheckedOptionalAccessModel>(clang::dataflow::test::AnalysisInputs<clang::dataflow::UncheckedOptionalAccessModel>, std::function<void (clang::dataflow::test::AnalysisOutputs const&)>) (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x4b18d2)
#14 0x000056125e5573d1 llvm::Error clang::dataflow::test::checkDataflow<clang::dataflow::UncheckedOptionalAccessModel>(clang::dataflow::test::AnalysisInputs<clang::dataflow::UncheckedOptionalAccessModel>, std::function<void (llvm::DenseMap<unsigned int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, llvm::DenseMapInfo<unsigned int, void>, llvm::detail::DenseMapPair<unsigned int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>> const&, clang::dataflow::test::AnalysisOutputs const&)>) (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x4b23d1)
#15 0x000056125e55a2dd void UncheckedOptionalAccessTest::ExpectDiagnosticsFor<clang::ast_matchers::internal::Matcher<clang::NamedDecl>>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, clang::ast_matchers::internal::Matcher<clang::NamedDecl>, char const*, bool) (.isra.0) UncheckedOptionalAccessModelTest.cpp:0:0
#16 0x000056125e55a977 UncheckedOptionalAccessTest::ExpectDiagnosticsFor(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, bool) (.constprop.0.isra.0) UncheckedOptionalAccessModelTest.cpp:0:0
#17 0x000056125e55aa4c UncheckedOptionalAccessTest_ConstructorOtherStructField_Test::TestBody() (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x4b5a4c)
#18 0x000056125e63789e testing::Test::Run() (.part.0) gtest-all.cc:0:0
#19 0x000056125e63ecf2 testing::TestInfo::Run() (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x599cf2)
#20 0x000056125e64b2f9 testing::TestSuite::Run() (.part.0) gtest-all.cc:0:0
#21 0x000056125e64bcba testing::internal::UnitTestImpl::RunAllTests() (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x5a6cba)
#22 0x000056125e64c54e testing::UnitTest::Run() (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x5a754e)
#23 0x000056125e33eb09 main (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x299b09)
#24 0x00007f383c55ec8a __libc_start_call_main ./csu/../sysdeps/nptl/libc_start_call_main.h:74:3
#25 0x00007f383c55ed45 call_init ./csu/../csu/libc-start.c:128:20
#26 0x00007f383c55ed45 __libc_start_main ./csu/../csu/libc-start.c:347:5
#27 0x000056125e3888d1 _start (clang/unittests/Analysis/FlowSensitive/./ClangAnalysisFlowSensitiveTests+0x2e38d1)

jvoung avatar Feb 20 '25 21:02 jvoung

@jvoung Thank you report this issue, can you provide a simple reproducer for this issue? I'm sorry that I'm not familier with clang-tidy, I tried to reproduce it locally but failed(https://godbolt.org/z/7331q8cb5).

yronglin avatar Feb 21 '25 15:02 yronglin

Sure, I think you were mainly missing the clang-tidy tool window and args -checks='-*,bugprone-unchecked-optional-access' in compiler explorer: https://godbolt.org/z/YTGa9YGh4

Otherwise the test from https://github.com/llvm/llvm-project/pull/128065/commits/a7002fb5a61c2f6f3c4df2347b6d5f861bf45f8e can be run with check-clang (or maybe check-clang-tools)

jvoung avatar Feb 21 '25 15:02 jvoung

Hmmm, it seems we need to support default-init/-arg in dataflow analysis, the CFG looks very different:

A more simple reproducer:

namespace std {
template <typename T> struct optional {
  bool has_value() const;
  T &operator*();
};
constexpr optional<int> nullopt;
} // namespace std

struct NonTrivDtor {
  NonTrivDtor(int x);
  ~NonTrivDtor() {}
};
struct Other {
  std::optional<int> x = std::nullopt;
  NonTrivDtor y = x.has_value() ? NonTrivDtor(*x) : NonTrivDtor(-1);
};
struct target {
  target() { Other{}; }
};

Before https://github.com/llvm/llvm-project/pull/127338


 [B4 (ENTRY)]
   Succs (1): B3

 [B1]
   1: ~NonTrivDtor() (Temporary object destructor)
   Preds (1): B3
   Succs (1): B0

 [B2]
   1: ~NonTrivDtor() (Temporary object destructor)
   Preds (1): B3
   Succs (1): B0

 [B3]
   1: 
   2: 
   3: {}
   4: [B3.3] (BindTemporary)
   5: Other[B3.4] (CXXFunctionalCastExpr, NoOp, Other)
   6: ~Other() (Temporary object destructor)
   T: (Temp Dtor) -1
   Preds (1): B4
   Succs (2): B2 B1

 [B0 (EXIT)]
   Preds (2): B1 B2

After:


 [B7 (ENTRY)]
   Succs (1): B6

 [B1]
   1: ~NonTrivDtor() (Temporary object destructor)
   Preds (1): B3
   Succs (1): B0

 [B2]
   1: ~NonTrivDtor() (Temporary object destructor)
   Preds (1): B3
   Succs (1): B0

 [B3]
   1: [B6.6] ? [B4.9] : [B5.5]
   2: [B3.1]
   3: 
   4: {}
   5: [B3.4] (BindTemporary)
   6: Other[B3.5] (CXXFunctionalCastExpr, NoOp, Other)
   7: ~Other() (Temporary object destructor)
   T: (Temp Dtor) [B5.4]
   Preds (2): B4 B5
   Succs (2): B2 B1

 [B4]
   1: operator*
   2: [B4.1] (ImplicitCastExpr, FunctionToPointerDecay, int &(*)(void))
   3: this
   4: [B4.3]->x
   5: * [B4.4] (OperatorCall)
   6: [B4.5] (ImplicitCastExpr, LValueToRValue, int)
   7: [B4.6] (CXXConstructExpr, NonTrivDtor)
   8: [B4.7] (BindTemporary)
   9: NonTrivDtor([B4.8]) (CXXFunctionalCastExpr, ConstructorConversion, NonTrivDtor)
   Preds (1): B6
   Succs (1): B3

 [B5]
   1: 1
   2: -[B5.1]
   3: [B5.2] (CXXConstructExpr, NonTrivDtor)
   4: [B5.3] (BindTemporary)
   5: NonTrivDtor([B5.4]) (CXXFunctionalCastExpr, ConstructorConversion, NonTrivDtor)
   Preds (1): B6
   Succs (1): B3

 [B6]
   1: 
   2: this
   3: [B6.2]->x
   4: [B6.3] (ImplicitCastExpr, NoOp, const struct std::optional<int>)
   5: [B6.4].has_value
   6: [B6.5]()
   T: [B6.6] ? ... : ...
   Preds (1): B7
   Succs (2): B4 B5

 [B0 (EXIT)]
   Preds (2): B1 B2

yronglin avatar Feb 21 '25 16:02 yronglin

CC @steakhal

yronglin avatar Feb 21 '25 16:02 yronglin

I'm not familiar with the clang DFG. /cc @Xazax-hun for an expert there. I'll never the less pay attention to this issue to maybe learn something :)

steakhal avatar Feb 21 '25 16:02 steakhal

involves some default inits for y, which references this->x -- the this should be for Other but the this is being confused for target (also in target's ctor)

Do you mean that the CFG has the wrong this expression in the basic block (with the wrong type)? Or is this a confusion in the dataflow analysis framework? Unfortunately, the dump alone does not answer the question.

Xazax-hun avatar Feb 21 '25 17:02 Xazax-hun

I haven't looked into this deeply, but I think some codepaths might have the expectation that CXXThisExpr always refers to the parent type of the current member function. With default arg/init rewrite this is no longer true. The injected initializer expressions might have CXXThisExprs that actually refer to the currently initialized object rather than the enclosing type of the member function.

Xazax-hun avatar Feb 21 '25 17:02 Xazax-hun

involves some default inits for y, which references this->x -- the this should be for Other but the this is being confused for target (also in target's ctor)

Do you mean that the CFG has the wrong this expression in the basic block (with the wrong type)? Or is this a confusion in the dataflow analysis framework? Unfortunately, the dump alone does not answer the question.

I think the latter: confusion is in the dataflow analysis framework. It isn't yet handling "CXXThisExprs that actually refer to the currently initialized object rather than the enclosing type of the member function".

For example around here: https://github.com/llvm/llvm-project/blob/386a45c6bd6358128f1e8e0819bacc92767f8db6/clang/lib/Analysis/FlowSensitive/Transfer.cpp#L416 it will just get the ThisPointeeLoc set up during initialize(). Perhaps the initialize could try do another walk to set up other Locs for possible default-inits that we can then look up later in the TransferVisitor? Not yet sure if there is a better way.

jvoung avatar Feb 21 '25 19:02 jvoung

I think it should be possible to work this around in the dataflow analysis framework. That being said, I wonder if the better solution would be to fix the AST. I.e., rewrite the AST to replace CxxThisExprs with the actual currently initialized object. This would fix this problem for all AST consumers, not just for the dataflow. I would imagine other people also getting bitten by this.

Xazax-hun avatar Feb 22 '25 11:02 Xazax-hun

That's a good point about other consumers getting bitten by this, and rewriting the AST, but I'm not sure what we can rewrite it to? It could be that I'm just not familiar enough with the options =) The currently initialized object is a parent in the tree (e.g., a CXXTemporary) -- how would we refer to it?

jvoung avatar Feb 25 '25 18:02 jvoung

Good point, we do not have a way to refer to a CXXTemporary, my bad! This makes me wonder if we should have a separate AST node to represent the concept of the currently initialised object.

Xazax-hun avatar Feb 25 '25 18:02 Xazax-hun

Just an interested bystander, but here's a simplified repro that does away with the need for std::optional entirely:

int f();
struct NonTrivDtor {
  NonTrivDtor(int x);
  ~NonTrivDtor() {}
};
struct Other {
  int x = f();
  NonTrivDtor y = x > 0 ? NonTrivDtor(1) : NonTrivDtor(-1);
};
struct target {
  target() { Other{}; }
};

godbolt

The AST is pretty long, so I won't quote it here (just go to the godbolt), but note the CXXThisExpr on line 83 of the AST. (I don't think it's necessary to look at the CFG -- that just complicates things, and I think the issue is perfectly clear from the AST itself.)

IIUC, the crux of the matter is that the dataflow framework is getting confused about what this CXXThisExpr refers to. The dataflow framework assumes that it refers to the this pointer of the enclosing CXXMethodDecl (which in this case is a CXXConstructorDecl), but in fact it refers to the temporary that's being initialized by the InitListExpr on line 72.

This isn't an ambiguity in the AST, though, or the compiler wouldn't be able to generate correct code. What I'm not clear on is what the rule is that disambiguates this. Is it simply that if a CXXThisExpr is contained in an InitListExpr, it refers to the result object of that InitListExpr (and not the this pointer of the enclosing CXXMethodDecl)? That doesn't seem too terrible, and I think it's a rule we can expect consumers of the AST to "know".

If we want to change the AST to make this situation easier to disambiguate (as @Xazax-hun suggests above), that's probably going to require some design work.

martinboehme avatar Feb 25 '25 20:02 martinboehme

Hi experts, I try to pick up this issue. IIUC, the AST is correct. It's beacuse CXXThisExpr is inside CXXDefaultInitExpr, and this CXXDefaultInitExpr was used to init fields in Other. We will rebuild default-init in aggregate initialization. I once added the ability to print the rebuilt Init (has rewritten init after CXXDefaultInitExpr) for clang AST dump. Maybe this feature misled people. Maybe we should handle this problem in the dataflow analysis framework. What do you think?

Aslo CC @AaronBallman @cor3ntin

https://github.com/llvm/llvm-project/blob/e933cfcfb2d207a7ff63cf152a7a78555d431d49/clang/lib/Sema/SemaInit.cpp#L804-L824

yronglin avatar Jun 27 '25 15:06 yronglin

It seemed like other options would require more design, and it isn't clear yet how many other places are affected outside of the dataflow framework. So yes, maybe we should handle this in the dataflow framework. I can take a stab at it.

jvoung avatar Jun 27 '25 19:06 jvoung

It seemed like other options would require more design, and it isn't clear yet how many other places are affected outside of the dataflow framework. So yes, maybe we should handle this in the dataflow framework. I can take a stab at it.

I have created a PR(https://github.com/llvm/llvm-project/pull/146281) to fix this issue.

I can take a stab at it.

Could you help finish the dataflow part? Many thanks! I have also added your tests into this PR.

yronglin avatar Jun 29 '25 16:06 yronglin

Could you help finish the dataflow part? Many thanks! I have also added your tests into this PR.

SG -- I made PR #146900 for the dataflow part.

jvoung avatar Jul 03 '25 17:07 jvoung

Fixed, though there is a draft followup in https://github.com/llvm/llvm-project/pull/221299

jvoung avatar Sep 18 '26 17:09 jvoung