Reverts llvm/llvm-project#133265
This causes the whole libc++ CI to fail, since we're not building
against a compiler built from current trunk. Specifically, the CMake
changes causes some feature detection to fail, resulting in CMake
being unable to configure libc++.
This turns on the unnecessary-virtual-specifier warning in general, but
disables it when building LLVM. It also tweaks the warning description
to be slightly more accurate.
Background: I've been working on cleaning up this warning in two
codebases: LLVM and chromium (plus its dependencies). The chromium
cleanup has been straightforward. Git archaeology shows that there are
two reasons for the warnings: classes to which `final` was added after
they were initially committed, and classes with virtual destructors that
nobody remarks on. Presumably the latter case is because people are just
very used to destructors being virtual.
The LLVM cleanup was more surprising: I discovered that we have an [old
policy](https://llvm.org/docs/CodingStandards.html#provide-a-virtual-method-anchor-for-classes-in-headers)
about including out-of-line virtual functions in every class with a
vtable, even `final` ones. This means our codebase has many virtual
"anchor" functions which do nothing except control where the vtable is
emitted, and which trigger the warning. I looked into alternatives to
satisfy the policy, such as using destructors instead of introducing a
new function, but it wasn't clear if they had larger implications.
Overall, it seems like the warning is genuinely useful in most codebases
(evidenced by chromium and its dependencies), and LLVM is an unusual
case. Therefore we should enable the warning by default, and turn it off
only for LLVM builds.
* Move parts of `InitializationSequence::InitializeFrom` corresponding
to C++ [dcl.init.general] p16.6.1 and p16.6.2 into a separate
function,`TryConstructorOrParenListInitialization`
* Use it in `TryListInitialization` to implement [dcl.init.list] p3.2
* Fix parenthesized aggregate initialization being attempted in
copy-initialization contexts or when the constructor call is ambiguous
Co-authored-by: cor3ntin <corentinjabot@gmail.com>
Original PR: #130537
Originally reverted due to revert of dependent commit. Relanding with no
changes.
This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the base class.
Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.
The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntatically, and
they represent the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.
This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.
As usual, includes a few drive-by fixes in order to make use of the
improvements.
This introduces some tablegen helpers for defining compatibility
warnings. The main aim of this is to both simplify adding new
compatibility warnings as well as to unify the naming of compatibility
warnings.
I’ve refactored ~half of the compatiblity warnings (that follow the
usual scheme) in `DiagnosticSemaKinds.td` for illustration purposes and
also to simplify/unify the wording of some of them (I also corrected a
typo in one of them as a drive-by fix).
I haven’t (yet) migrated *all* warnings even in that one file, and there
are some more specialised ones for which the scheme I’ve established
here doesn’t work (e.g. because they’re warning+error instead of
warning+extwarn; however, warning+extension *is* supported), but the
point of this isn’t to implement *all* compatibility-related warnings
this way, only to make the common case a bit easier to handle.
This currently also only handles C++ compatibility warnings, but it
should be fairly straight-forward to extend the tablegen code so it can
also be used for C compatibility warnings (if this gets merged, I’m
planning to do that in a follow-up pr).
The vast majority of compatibility warnings are emitted by writing
```c++
Diag(Loc, getLangOpts().CPlusPlusYZ ? diag::ext_... : diag::warn_...)
```
in accordance with which I’ve chosen the following naming scheme:
```c++
Diag(Loc, getLangOpts().CPlusPlusYZ ? diag::compat_cxxyz_foo : diag::compat_pre_cxxyz_foo)
```
That is, for a warning about a C++20 feature—i.e. C++≤17
compatibility—we get:
```c++
Diag(Loc, getLangOpts().CPlusPlus20 ? diag::compat_cxx20_foo : diag::compat_pre_cxx20_foo)
```
While there is an argument to be made against writing ‘`compat_cxx20`’
here since is technically a case of ‘C++17 compatibility’ and not ‘C++20
compatibility’, I at least find this easier to reason about, because I
can just write the same number 3 times instead of having to use
`ext_cxx20_foo` but `warn_cxx17_foo`. Instead, I like to read this as a
warning about the ‘compatibility *of* a C++20 feature’ rather than
‘*with* C++17’.
I also experimented with moving all compatibility warnings to a separate
file, but 1. I don’t think it’s worth the effort, and 2. I think it
hurts compile times a bit because at least in my testing I felt that I
had to recompile more code than if we just keep e.g. Sema-specific
compat warnings in the Sema diagnostics file.
Instead, I’ve opted to put them all in the same place within any one
file; currently this is a the very top but I don’t really have strong
opinions about this.
Original PR: #130537
Reland after updating lldb too.
This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the base class.
Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.
The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntatically, and
they represent the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.
This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.
As usual, includes a few drive-by fixes in order to make use of the
improvements.
This changes the MemberPointerType representation to use a
NestedNameSpecifier instead of a Type to represent the class.
Since the qualifiers are always parsed as nested names, there was an
impedance mismatch when converting these back and forth into types, and
this led to issues in preserving sugar.
The nested names are indeed a better match for these, as the differences
which a QualType can represent cannot be expressed syntactically, and it
also represents the use case more exactly, being either dependent or
referring to a CXXRecord, unqualified.
This patch also makes the MemberPointerType able to represent sugar for
a {up/downcast}cast conversion of the base class, although for now the
underlying type is canonical, as preserving the sugar up to that point
requires further work.
As usual, includes a few drive-by fixes in order to make use of the
improvements, and removing some duplications, for example
CheckBaseClassAccess is deduplicated from across SemaAccess and
SemaCast.
WG14 added N3411 to the list of papers which apply to older versions of
C in C2y, and WG21 adopted CWG787 as a Defect Report in C++11. So we no
longer should be issuing a pedantic diagnostic about a file which does
not end with a newline character.
We do, however, continue to support -Wnewline-eof as an opt-in
diagnostic.
CWG472 is one of the CWG issues that were assigned to Mike Miller with
`drafting` status, but recently got back to `open`, because Mike is no
longer active in CWG. Nothing to be done here, except for changing the
status.
CWG1432 was recently reopened after a CWG reflector discussion. I
changed the status to claim that we test for the previous resolution.
For an expression `nodiscard_function().static_member(), the nodiscard
warnings added by #120223, are not useful or actionable, and are
disruptive to some library implementations; we just remove them.
Fixes#131410
This caused incorrect -Wunguarded-availability warnings. See comment on
the pull request.
> We were missing a call to DiagnoseUseOfDecl when performing typename
> access.
>
> This refactors the code so that TypeDecl lookups funnel through a helper
> which performs all the necessary checks, removing some related
> duplication on the way.
>
> Fixes#58547
>
> Differential Revision: https://reviews.llvm.org/D136533
This reverts commit 4c4fd6b03149348cf11af245ad2603d24144a9d5.
This clears up the printing of a NestedNameSpecifier so a trailing '::'
is not printed, unless it refers into the global scope.
This fixes a bunch of diagnostics where the trailing :: was awkward.
This also prints the NNS quoted consistenty.
There is a drive-by improvement to error recovery, where now we print
the actual type instead of `<dependent type>`.
This will clear up further uses of NNS printing in further patches.
The resolution of [CWG2285](https://wg21.link/cwg2285) adds the point of
declaration of a structured binding, and was implemented in
bdb84f374c
.
Drive-by changes: modify comment and diagnostic messages mentioned in
CWG2285.
Instead of manually adding a note pointing to the relevant template
parameter to every relevant error, which is very easy to miss, this
patch adds a new instantiation context note, so that this can work using
RAII magic.
This fixes a bunch of places where these notes were missing, and is more
future-proof.
Some diagnostics are reworked to make better use of this note:
- Errors about missing template arguments now refer to the parameter
which is missing an argument.
- Template Template parameter mismatches now refer to template
parameters as parameters instead of arguments.
It's likely this will add the note to some diagnostics where the
parameter is not super relevant, but this can be reworked with time and
the decrease in maintenance burden makes up for it.
This bypasses the templight dumper for the new context entry, as the
tests are very hard to update.
This depends on #125453, which is needed to avoid losing the context
note for errors occuring during template argument deduction.
Fixes#46386
---
When an abbreviated function template appears in an `extern "C"` block
and all template parameters are invented,
`TemplateParams->getTemplateLoc()` becomes invalid, leading to an
incorrect error location. These changes ensure that the error points to
the parameter's location when the template location is invalid.
We were missing a call to DiagnoseUseOfDecl when performing typename
access.
This refactors the code so that TypeDecl lookups funnel through a helper
which performs all the necessary checks, removing some related
duplication on the way.
Fixes#58547
Differential Revision: https://reviews.llvm.org/D136533
This skips the provisional resolution of CWG1432 just when ordering the
candidates for function call code completion, as otherwise this breaks
some assumptions the implementation makes about how closely related the
candidates are.
As a drive-by, deduplicate the implementation with the one used for
class template partial ordering, and strenghten an assertion which was
previosuly dependent on the order of candidates.
Also add a test for the fix for CWG1432 when partial ordering function
templates, which was otherwise untested.
Fixes#125500
Commit 77d3f8a avoids distinct tags for any pointers where the ultimate
pointee type is `void`, to solve breakage in real-world code that uses
(indirections to) `void*` for polymorphism over different pointer types.
While this matches the TBAA implementation in GCC, this patch implements
a refinement that distinguishes void pointers by pointer depth, as
described in the "strict aliasing" documentation included in the
aforementioned commit:
> `void*` is permitted to alias any pointer type, `void**` is permitted
> to alias any pointer to pointer type, and so on.
For example, `void**` is no longer considered to alias `int*` in this
refinement, but it remains possible to use `void**` for polymorphism
over pointers to pointers.
This patch makes it so the correct instantiation context is printed for
diagnostics suppessed by template argument deduction.
The context is saved along with the suppressed diagnostic, and when the
declaration they were attached to becomes used, we print the correct
context, instead of whatever context was at this point.
Example from the issue:
```c++
void Func(int x) {
switch (x) {
[[likely]] case 0:
case 1:
int i = 3;
case 2:
break;
}
}
```
Clang checks if ``case 2`` can be reachable by checking its scope. The
variable declaration should create a scope containing ``case 2``, but
due to the structure of the AST, ``case 2`` gets the scope of the
``likely`` statement, but not ``int i = 3;``. Therefore, I changed this
code to force attribute statement not to be scope parents.
Fixes#84072
Recently I had a scenario where I had:
1. A class C with many members m_1...m_n of the same type T
2. T's default constructor was deleted
3. I accidentally omitted an explicitly constructed member in the
initializer list C() : m_1(foo), m_2(bar), ... { }
Clang told me that T's default constructor was deleted, and told me that
the call to T() was in C() (which it implicitly was), but didn't tell me
which member was being default constructed.
It was difficult to fix this problem because I had no easy way to list
all the members of type T in C and C's superclasses which would have let
me find which member was missing,
clang/test/CXX/class/class.init/p1.cpp is a simplified version of this
problem (a2 is missing from the initializer list of B)
This fixes the core issue described in P3579, following the design
intent of P0522 to not introduce any new cases where a template template
parameter match is allowed for a template which is not valid for all
possible uses.
With this patch, narrowing conversions are disallowed for TTP matching.
This reuses the existing machinery for diagnosing narrowing in a
converted constant expression.
Since P0522 is a DR and we apply it all the way back to C++98, this
brings that machinery to use in older standards, in this very narrow
scope of TTP matching.
This still doesn't solve the ambiguity when partial ordering NTTPs of
different integral types, this is blocked by a different bug which will
be fixed in a subsequent patch (but the test cases are added).
The issue occurred because the template parameter scope was skipped
too early, before diagnosing the alias name shadowing.
To fix this, the patch moves it to after LookupName, such that the behavior
remains consistent with the typedef implementation.
Fixes llvm#123423
This patch relands the following PRs:
* #111711
* #107350
* #111457
All of these patches were reverted due to an issue reported in
https://github.com/llvm/llvm-project/pull/111711#issuecomment-2406491485,
due to interdependencies.
---
[clang] Finish implementation of P0522
This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.
Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.
This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.
With this patch, we apply the P0522 rules throughout.
This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.
It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.
This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.
The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.
The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.
The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.
So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.
This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
[clang] CWG2398: improve overload resolution backwards compat
With this change, we discriminate if the primary template and which partial
specializations would have participated in overload resolution prior to
P0522 changes.
We collect those in an initial set. If this set is not empty, or the
primary template would have matched, we proceed with this set as the
candidates for overload resolution.
Otherwise, we build a new overload set with everything else, and proceed
as usual.
---
[clang] Implement TTP 'reversed' pack matching for deduced function template calls.
Clang previously missed implementing P0522 pack matching
for deduced function template calls.
Reapplies #104458, fixing a bug that occurs when a class member access expression calls an `operator->` operator function that returns a non-dependent class type.
In preparation of making `-Wreturn-type` default to an error (as there
is virtually no situation where you’d *want* to fall off the end of a
function that is supposed to return a value), this patch fixes tests
that have relied on this being only a warning, of which there seem
to be 3 kinds:
1. Tests which for no apparent reason have a function that triggers the
warning.
I suspect that a lot of these were on accident (or from before the
warning was introduced), since a lot of people will open issues w/ their
problematic code in the `main` function (which is the one case where you
don’t need to return from a non-void function, after all...), which
someone will then copy, possibly into a namespace, possibly renaming it,
the end result of that being that you end up w/ something that
definitely is not `main` anymore, but which still is declared as
returning `int`, and which still has no return statement (another reason
why I think this might apply to a lot of these is because usually the
actual return type of such problematic functions is quite literally
`int`).
A lot of these are really old tests that don’t use `-verify`, which is
why no-one noticed or had to care about the extra warning that was
already being emitted by them until now.
2. Tests which test either `-Wreturn-type`, `[[noreturn]]`, or what
codegen and sanitisers do whenever you do fall off the end of a
function.
3. Tests where I struggle to figure out what is even being tested
(usually because they’re Objective-C tests, and I don’t know
Objective-C), whether falling off the end of a function matters in the
first place, and tests where actually spelling out an expression to
return would be rather cumbersome (e.g. matrix types currently don’t
support list initialisation, so I can’t write e.g. `return {}`).
For tests that fall into categories 2 and 3, I just added
`-Wno-error=return-type` to the `RUN` lines and called it a day. This
was especially necessary for the former since `-Wreturn-type` is an
analysis-based warning, meaning that it is currently impossible to test
for more than one occurrence of it in the same compilation if it
defaults to an error since the analysis pass is skipped for subsequent
functions as soon as an error is emitted.
I’ve also added `-Werror=return-type` to a few tests that I had already
updated as this patch was previously already making the warning an error
by default, but we’ve decided to split that into two patches instead.
Close https://github.com/llvm/llvm-project/issues/90154
This patch is also an optimization to the lookup process to utilize the
information provided by `export` keyword.
Previously, in the lookup process, the `export` keyword only takes part
in the check part, it doesn't get involved in the lookup process. That
said, previously, in a name lookup for 'name', we would load all of
declarations with the name 'name' and check if these declarations are
valid or not. It works well. But it is inefficient since it may load
declarations that may not be wanted.
Note that this patch actually did a trick in the lookup process instead
of bring module information to DeclarationName or considering module
information when deciding if two declarations are the same. So it may
not be a surprise to me if there are missing cases. But it is not a
regression. It should be already the case. Issue reports are welcomed.
In this patch, I tried to split the big lookup table into a lookup table
as before and a module local lookup table, which takes a combination of
the ID of the DeclContext and hash value of the primary module name as
the key. And refactored `DeclContext::lookup()` method to take the
module information. So that a lookup in a DeclContext won't load
declarations that are local to **other** modules.
And also I think it is already beneficial to split the big lookup table
since it may reduce the conflicts during lookups in the hash table.
BTW, this patch introduced a **regression** for a reachability rule in
C++20 but it was false-negative. See
'clang/test/CXX/module/module.interface/p7.cpp' for details.
This patch is not expected to introduce any other
regressions for non-c++20-modules users since the module local lookup
table should be empty for them.
Close https://github.com/llvm/llvm-project/issues/90154
This patch is also an optimization to the lookup process to utilize the
information provided by `export` keyword.
Previously, in the lookup process, the `export` keyword only takes part
in the check part, it doesn't get involved in the lookup process. That
said, previously, in a name lookup for 'name', we would load all of
declarations with the name 'name' and check if these declarations are
valid or not. It works well. But it is inefficient since it may load
declarations that may not be wanted.
Note that this patch actually did a trick in the lookup process instead
of bring module information to DeclarationName or considering module
information when deciding if two declarations are the same. So it may
not be a surprise to me if there are missing cases. But it is not a
regression. It should be already the case. Issue reports are welcomed.
In this patch, I tried to split the big lookup table into a lookup table
as before and a module local lookup table, which takes a combination of
the ID of the DeclContext and hash value of the primary module name as
the key. And refactored `DeclContext::lookup()` method to take the
module information. So that a lookup in a DeclContext won't load
declarations that are local to **other** modules.
And also I think it is already beneficial to split the big lookup table
since it may reduce the conflicts during lookups in the hash table.
BTW, this patch introduced a **regression** for a reachability rule in
C++20 but it was false-negative. See
'clang/test/CXX/module/module.interface/p7.cpp' for details.
This patch is not expected to introduce any other
regressions for non-c++20-modules users since the module local lookup
table should be empty for them.
---
On the API side, this patch unfortunately add a maybe-confusing argument
`Module *NamedModule` to
`ExternalASTSource::FindExternalVisibleDeclsByName()`. People may think
we can get the information from the first argument `const DeclContext
*DC`. But sadly there are declarations (e.g., namespace) can appear in
multiple different modules as a single declaration. So we have to add
additional information to indicate this.
This patch adds test for
[CWG170](https://cplusplus.github.io/CWG/issues/170.html). The
resolution adds explicit undefined behavior, so I think the best we can
do is to put the test into constexpr evaluator. Change to
[expr.static.cast] is not tested, because it was a drive-by fix that
removed an impossible case (I confirmed it using minutes). Minutes
mention several times a comprehensive paper in this design space which
no one seem to remember. I believe it's
[P0149R0](https://wg21.link/p0149r0) "Generalised member pointers".
When a destroying delete overload is selected, the destructor is not
automatically called. Therefore, the destructor can be deleted without
causing the program to be ill-formed.
Fixes#46818
... between unrelated declarations or literals.
Leaving this small (I haven't run the whole test suite locally) to get
some feedback on the wording and implementation first.
The output of the sample in
https://github.com/llvm/llvm-project/issues/117409 is now:
```console
./array.cpp:57:6: warning: expression result unused [-Wunused-value]
57 | am - aj.af();
| ~~ ^ ~~~~~~~
./array.cpp:70:8: error: call to consteval function 'L::L<bx>' is not a constant expression
70 | q(0, [] {
| ^
./array.cpp:57:6: note: arithmetic on addresses of literals has unspecified value
57 | am - aj.af();
| ^
./array.cpp:62:5: note: in call to 'al(&""[0], {&""[0]})'
62 | al(bp.af(), k);
| ^~~~~~~~~~~~~~
./array.cpp:70:8: note: in call to 'L<bx>({})'
70 | q(0, [] {
| ^~~~
71 | struct bx {
| ~~~~~~~~~~~
72 | constexpr operator ab<g<l<decltype(""[0])>::e>::e>() { return t(""); }
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
73 | };
| ~~
74 | return bx();
| ~~~~~~~~~~~~
75 | }());
| ~~~
```
The output for
```c++
int a, b;
constexpr int n = &b - &a
```
is now:
```console
./array.cpp:80:15: error: constexpr variable 'n' must be initialized by a constant expression
80 | constexpr int n = &b - &a;
| ^ ~~~~~~~
./array.cpp:80:22: note: arithmetic involving '&b' and '&a' has unspecified value
80 | constexpr int n = &b - &a;
| ^
1 error generated.
```
This patch adds test for
[CWG203](https://cplusplus.github.io/CWG/issues/203.html). Author was
asking to change the type of pointer-to-member expression to be closer
to how it's written as opposed to where the resulting member belongs to,
but was turned down due to backwards compatibility concerns, so we're
testing the status quo.
There are a total of 6 examples in the filing, so I decided to just
throw all of them into the test. I had to turn example 2 into
`constexpr` test that unfortunately requires C++20. Outcomes in example
5 that Tomasz expected are not in line with implementation behavior and
my reading of the Standard. I think he got confused by the fact that
unlike regular pointers, pointers-to-members can be implicitly
_downcasted_, but not upcasted. I left comments in the example.