According to [C++14/17 12.6.2 p16] [C++11 12.6.2 p13] calling member functions of the current class before all the base classes are initialized is undefined behavior. Some compilers (such as GCC 5.3 + ubsan) can produce a segfaulting code in the program when such code is encountered (see GCC bug #70035), so clang should generate a warning about the UB.
Details
- Reviewers
rsmith
Diff Detail
Event Timeline
You might want to mention that it's 12.6.2p16 in C++14/17 but p13 in C++11.
I wonder if we should have the example in the standard, verbatim. (Plus the added tests you made)
I meant changing the diff, but if you prefer to have a smaller comment, I'm ok with the different "paths" in the standards being mentioned only in the commit message.
lib/Sema/SemaDeclCXX.cpp | ||
---|---|---|
3981 | For someone reading the source code, it's probably best to mention the different "paths" in the standards here too. |
Oh, totally forgot that I also had a reference in the code, thanks! Will fix it ASAP.
Adding the example from the standard to the test cases sounds good. It actually tests a few things that aren't covered by the current test.
- Standard reference is now specifying what standard (C++11)
- Added test based on the standard example
- Also check base classes now for member calls (to pass the test from the standard example).
The patch needs to get through clang-format.
Should we deal with typeid and dynamic_cast, since they're mentioned in the same paragraph in the standard?
lib/Sema/SemaDeclCXX.cpp | ||
---|---|---|
3964 | What's the rationale for warning if getRecordDecl returns nullptr? | |
3966 | Please run clang-format on the patch. | |
3980 | clang-format | |
3981 | "before the base class is initialized"? |
Have you looked at http://reviews.llvm.org/D6561 which was a previous attempt at this warning?
No, didn't saw the thread so far. I assume the comments in there are still valid, so I'll update this patch.
Thanks for the feedback so far!
- Moved checks to the UninitializedFieldVisitor
- Also check for dynamic_cast on this during construction
- Added checks and tests for typeid
- Moved warnings into same warning group
- Check that only possibly evaluated expressions are checked
Sorry, couldn't help it. This patch looks so useful and so lonely :)
include/clang/Basic/DiagnosticSemaKinds.td | ||
---|---|---|
6782 | I don't see these things referred to as "ctor-initializers" in other diagnostics. I'd rather say "initializer". Also "has undefined behavior" is shorter and nicer. | |
lib/Sema/SemaDeclCXX.cpp | ||
2295 | I'd be scared not to initialize this variable to null. Also, this visitor scans only one constructor throughout its lifetime, right? | |
2588–2589 | Ugh. This is worth a test case! |
I don't see these things referred to as "ctor-initializers" in other diagnostics. I'd rather say "initializer".
Also "has undefined behavior" is shorter and nicer.