Commit Graph

2154 Commits

Author SHA1 Message Date
Richard Smith d1446017f3 DR458: Search template parameter scopes in the right order.
C++ unqualified name lookup searches template parameter scopes
immediately after finishing searching the entity the parameters belong
to. (Eg, for a class template, you search the template parameter scope
after looking in that class template and its base classes and before
looking in the scope containing the class template.) This is complicated
by the fact that scope lookup within a template parameter scope looks in
a different sequence of places prior to reaching the end of the
declarator-id in the template declaration.

We used to approximate the proper lookup rule with a hack in the scope /
decl context walk inside name lookup. Now we instead compute the lookup
parent for each template parameter scope.

In order to get this right, we now make sure to enter a distinct Scope
for each template parameter scope, and make sure to re-enter the
enclosing class scopes properly when handling delay-parsed regions
within a class.
2020-06-23 17:14:33 -07:00
Richard Smith 02fccc26cf Revert "DR458: Search template parameter scopes in the right order."
We weren't re-entering template scopes in the right order, causing this
to break self-host with -fdelayed-template-parsing.

This reverts commit 237c2a23b6.
2020-06-16 23:53:44 -07:00
Richard Smith 237c2a23b6 DR458: Search template parameter scopes in the right order.
C++ unqualified name lookup searches template parameter scopes
immediately after finishing searching the entity the parameters belong
to. (Eg, for a class template, you search the template parameter scope
after looking in that class template and its base classes and before
looking in the scope containing the class template.) This is complicated
by the fact that scope lookup within a template parameter scope looks in
a different sequence of places prior to reaching the end of the
declarator-id in the template declaration.

We used to approximate the proper lookup rule with a hack in the scope /
decl context walk inside name lookup. Now we instead compute the lookup
parent for each template parameter scope. This gets the right answer and
as a bonus is substantially simpler and more uniform.

In order to get this right, we now make sure to enter a distinct Scope
for each template parameter scope. (The fact that we didn't before was
already a bug, but not really observable most of the time, since
template parameters can't shadow each other.)
2020-06-16 19:41:14 -07:00
Bruno Ricci f13d704a50
[clang][NFC] Mark CWG 1443 (Default arguments and non-static data members)...
...as done. This is a NAD which has always been implemented correctly.
2020-06-13 13:59:54 +01:00
Bruno Ricci eb614db0a0
[clang][NFC] Mark CWG 974 and 1814 (default argument in a...
...lambda-expression) as done. They have been allowed since at least clang 3.3.
2020-06-13 13:49:07 +01:00
Haojian Wu 58ea1059df [AST][RecoveryExpr] Build recovery expressions by default for C++.
Reland https://reviews.llvm.org/D76696
All known crashes have been fixed, another attemption.

We have rolled out this to all internal users for a while, didn't see
big issues, we consider it is stable enough.

Reviewed By: sammccall

Subscribers: rsmith, hubert.reinterpretcast, ebevhan, jkorous, arphaman, kadircet, usaxena95, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D78350
2020-06-12 15:21:38 +02:00
Bruno Ricci 40ea01f654
[clang] Convert a default argument expression to the parameter type...
...before checking that the default argument is valid with
CheckDefaultArgumentVisitor.

Currently the restrictions on a default argument are checked with the visitor
CheckDefaultArgumentVisitor in ActOnParamDefaultArgument before
performing the conversion to the parameter type in SetParamDefaultArgument.

This was fine before the previous patch but now some valid code post-CWG 2346
is rejected:

void test() {
  const int i2 = 0;
  extern void h2a(int x = i2);     // FIXME: ok, not odr-use
  extern void h2b(int x = i2 + 0); // ok, not odr-use
}

This is because the reference to i2 in h2a has not been marked yet with
NOUR_Constant. i2 is marked NOUR_Constant when the conversion to the parameter
type is done, which is done just after.

The solution is to do the conversion to the parameter type before checking
the restrictions on default arguments with CheckDefaultArgumentVisitor.
This has the side-benefit of improving some diagnostics.

Differential Revision: https://reviews.llvm.org/D81616

Reviewed By: rsmith
2020-06-11 13:18:45 +01:00
Bruno Ricci 5951ff4512
[clang] CWG 2082 and 2346: loosen the restrictions on parameters and local variables in default arguments.
This patch implements the resolution of CWG 2082 and CWG 2346.

The resolution of CWG 2082 changed [dcl.fct.default]p7 and p9 to allow
a parameter or local variable to appear in a default argument if not
in a potentially-evaluated expression.

The resolution of CWG 2346 changed [dcl.fct.default]p7 to allow a local
variable to appear in a default argument if not odr-used.

An issue remains after this patch
(see the FIXME in test/CXX/dcl.decl/dcl.meaning/dcl.fct.default/p7.cpp).
This is addressed by the next patch.

Differential Revision: https://reviews.llvm.org/D81615

Reviewed By: rsmith, erichkeane
2020-06-11 12:41:08 +01:00
Richard Smith 16437992ca Undo removal of test for dr777. 2020-06-02 14:19:42 -07:00
Richard Smith b5f2c4e45b PR23029 / C++ DR2233: Allow expanded parameter packs to follow
parameters with default arguments.

Directly follow the wording by relaxing the AST invariant that all
parameters after one with a default arguemnt also have default
arguments, and removing the diagnostic on missing default arguments
on a pack-expanded parameter following a parameter with a default
argument.

Testing also revealed that we need to special-case explicit
specializations of templates with a pack following a parameter with a
default argument, as such explicit specializations are otherwise
impossible to write. The standard wording doesn't address this case; a
issue has been filed.

This exposed a bug where we would briefly consider a parameter to have
no default argument while we parse a delay-parsed default argument for
that parameter, which is also fixed.

Partially incorporates a patch by Raul Tambre.
2020-06-02 13:48:59 -07:00
Eli Friedman 62f3ef2b53 [CGCall] Annotate references with "align" attribute.
If we're going to assume references are dereferenceable, we should also
assume they're aligned: otherwise, we can't actually dereference them.

See also D80072.

Differential Revision: https://reviews.llvm.org/D80166
2020-05-19 20:21:30 -07:00
Akira Hatanaka 50a81ea2bc Don't apply lvalue-to-rvalue conversion in DefaultLValueConversion to
the expression that is passed to it if it has a function type or array
type

lvalue-to-rvalue conversion should only be applied to non-function,
non-array types, but clang was applying the conversion to discarded
value expressions of array types.

rdar://problem/61203170

Differential Revision: https://reviews.llvm.org/D78134
2020-05-13 20:12:10 -07:00
Richard Smith c90e198107 Fix parsing of enum-base to follow C++11 rules.
Previously we implemented non-standard disambiguation rules to
distinguish an enum-base from a bit-field but otherwise treated a :
after an elaborated-enum-specifier as introducing an enum-base. That
misparses various examples (anywhere an elaborated-type-specifier can
appear followed by a colon, such as within a ternary operator or
_Generic).

We now implement the C++11 rules, with the old cases accepted as
extensions where that seemed reasonable. These amount to:
 * an enum-base must always be accompanied by an enum definition (except
   in a standalone declaration of the form 'enum E : T;')
 * in a member-declaration, 'enum E :' always introduces an enum-base,
   never a bit-field
 * in a type-specifier (or similar context), 'enum E :' is not
   permitted; the colon means whatever else it would mean in that
   context.

Fixed underlying types for enums are also permitted in Objective-C and
under MS extensions, plus as a language extension in all other modes.
The behavior in ObjC and MS extensions modes is unchanged (but the
bit-field disambiguation is a bit better); remaining language modes
follow the C++11 rules.

Fixes PR45726, PR39979, PR19810, PR44941, and most of PR24297, plus C++
core issues 1514 and 1966.
2020-05-08 19:32:00 -07:00
Richard Smith 0a088ead85 Improve diagnostics for missing import / #include of module.
Fix a few bugs where we would fail to properly determine header to
module correspondence when determining whether to suggest a #include or
import, and suggest a #include more often in language modes where there
is no import syntax. Generally, if the target is in a header with
include guards or #pragma once, we should suggest either #including or
importing that header, and not importing a module that happens to
textually include it.

In passing, improve the notes we attach to the corresponding
diagnostics: calling an entity that we couldn't see "previous" is
confusing.
2020-04-28 18:41:14 -07:00
Haojian Wu 89d9912cbf [AST] dont invaliate VarDecl when the initializer contains errors.
Summary:
This patch contains 2 separate changes:
1) the initializer of a variable should play no part in decl "invalid" bit;
2) preserve the invalid initializer via recovery exprs;

With 1), we will regress the diagnostics (one big regression is that we loose
the "selected 'begin' function with iterator type" diagnostic in for-range stmt;
but with 2) together, we don't have regressions (the new diagnostics seems to be
improved).

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D78116
2020-04-21 10:53:35 +02:00
Matthias Gehre 0642e5e7a7 [clang-tidy] modernize-use-using: Fix broken fixit with 'template' keyword
Summary:
Before this PR, `modernize-use-using` would transform the typedef in
```

template <typename a> class TemplateKeyword {
  typedef typename a::template f<> e;
  typedef typename a::template f<>::d e2;
};
```
into
```
template <typename a> class TemplateKeyword {
  using d = typename a::b<>;
  using d2 = typename a::template a::b<>::c;
};
```
The first one is missing the `template` keyword,
the second one has an extra `a::` scope. Both result
in compilation errors.

Reviewers: aaron.ballman, alexfh, hokein, njames93

Subscribers: xazax.hun, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D78139
2020-04-17 10:37:24 +02:00
Aaron Ballman 2ec5520a54 Disallow [[nodiscard]] on a function pointer declaration.
This is not allowed by [dcl.attr.nodiscard]p1 for the standard attribute, but
is still supported for the [[clang::warn_unused_result]] spelling.
2020-04-16 09:28:49 -04:00
Haojian Wu 9657385960 [AST] Dont invalide VarDecl even the default initializaiton is failed.
Summary:
This patch would cause clang emit more diagnostics, but it is much better than https://reviews.llvm.org/D76831

```cpp
struct A {
  A(int);
  ~A() = delete;
};
void k() {
  A a;
}

```

before the patch:

/tmp/t3.cpp:24:5: error: no matching constructor for initialization of 'A'
  A a;
    ^
/tmp/t3.cpp:20:3: note: candidate constructor not viable: requires 1 argument, but 0 were provided
  A(int);
  ^
/tmp/t3.cpp:19:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct A {

After the patch:

/tmp/t3.cpp:24:5: error: no matching constructor for initialization of 'A'
  A a;
    ^
/tmp/t3.cpp:20:3: note: candidate constructor not viable: requires 1 argument, but 0 were provided
  A(int);
  ^
/tmp/t3.cpp:19:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct A {
       ^
/tmp/t3.cpp:24:5: error: attempt to use a deleted function
  A a;
    ^
/tmp/t3.cpp:21:3: note: '~A' has been explicitly marked deleted here
  ~A() = delete;

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77395
2020-04-14 12:58:48 +02:00
Reid Kleckner 55efb68c19 [MS] Mark vbase dtors used when marking dtor used
In the MS C++ ABI, the complete destructor variant for a class with
virtual bases is emitted whereever it is needed, instead of directly
alongside the base destructor variant. The complete destructor calls the
base destructor of the current class and the base destructors of each
virtual base. In order for this to work reliably, translation units that
use the destructor of a class also need to mark destructors of virtual
bases of that class used.

Fixes PR38521

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D77081
2020-04-09 14:19:36 -07:00
Fangrui Song d0d076fed9 [Driver] Flip the CC1 default of -fdiagnostics-show-option
The driver enables -fdiagnostics-show-option by default, so flip the CC1
default to reduce the lengths of common CC1 command lines.

This change also makes ParseDiagnosticArgs() consistently enable
-fdiagnostics-show-option by default.
2020-03-31 21:59:27 -07:00
Richard Smith 0c42539df3 Improve error recovery from missing '>' in template argument list.
Produce the conventional "to match this '<'" note, so that the user
knows why we expected a '>', and properly handle '>>' in C++11 onwards.
2020-03-27 18:59:01 -07:00
Richard Smith b3f6e3d6d6 Improve recovery from invalid template-ids.
Instead of bailing out of parsing when we encounter an invalid
template-name or template arguments in a template-id, produce an
annotation token describing the invalid construct.

This avoids duplicate errors and generally allows us to recover better.
In principle we should be able to extend this to store some kinds of
invalid template-id in the AST for tooling use, but that isn't handled
as part of this change.
2020-03-27 17:11:04 -07:00
Sam McCall 159a9f7e76 [AST] Print a<b<c>> without extra spaces in C++11 or later.
Summary: It's not 1998 anymore.

Reviewers: kadircet

Subscribers: jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D76801
2020-03-26 09:53:54 +01:00
Richard Smith 502915c619 PR45142: 'template ~X<T>' is ill-formed; reject it rather than crashing. 2020-03-23 15:07:06 -07:00
Richard Smith dc4259d5a3 [c++20] Further extend the set of comparisons broken by C++20 that we
accept as an extension.

This attempts to accept the same cases a GCC, plus cases where a
comparison is rewritten to an operator== with an integral but non-bool
return type; this is sufficient to avoid most problems with various
major open-source projects (such as ICU) and appears to fix all but one
of the comparison-related C++20 build breaks in LLVM.

This approach is being pursued for standardization.
2020-03-20 14:22:48 -07:00
Richard Smith 461566b046 Add a test triple to avoid failure under MS ABI.
MS ABI has slightly different rules for when destructors are implicitly
defined and when the 'delete this' is checked that are out of scope for
the intent of this test.
2020-03-12 16:44:09 -07:00
Richard Smith 9975dc38bf Defer checking for mismatches between the deletedness of and overriding
function and an overridden function until we know whether the overriding
function is deleted.

We previously did these checks when we first built the declaration,
which was too soon in some cases. We now defer all these checks to the
end of the class.

Also add missing check that a consteval function cannot override a
non-consteval function and vice versa.
2020-03-12 13:07:22 -07:00
Anastasia Stulova fa755d3e71 [Sema][C++] Propagate conversion kind to specialize the diagnostics
Compute and propagate conversion kind to diagnostics helper in C++
to provide more specific diagnostics about incorrect implicit
conversions in assignments, initializations, params, etc...

Duplicated some diagnostics as errors because C++ is more strict.

Tags: #clang

Differential Revision: https://reviews.llvm.org/D74116
2020-02-25 16:05:37 +00:00
Michele Scandale bd5b22070b Fix TryParsePtrOperatorSeq.
The syntax rules for ptr-operator allow attributes after *, &,
&&, therefore we should be able to parse the following:

void fn() {
    void (*[[attr]] x)() = &fn;
    void (&[[attr]] y)() = fn;
    void (&&[[attr]] z)() = fn;
}
However the current logic in TryParsePtrOperatorSeq does not consider
the presence of attributes leading to unexpected parsing errors.

Moreover we should also consider _Atomic a possible qualifier that can
appear after the sequence of attribute specifiers.
2020-02-24 08:08:47 -05:00
Richard Smith 061f3a50dd P0593R6: Pseudo-destructor expressions end object lifetimes.
This only has an observable effect on constant evaluation.
2020-02-18 18:41:03 -08:00
Richard Smith 24ad121582 Add -std=c++20 flag, replace C++2a with C++20 throughout the Clang
user interface and documentation, and update __cplusplus for C++20.

WG21 considers the C++20 standard to be finished (even though it still
has some more steps to pass through in the ISO process).

The old flag names are accepted for compatibility, as usual, and we
still have lots of references to C++2a in comments and identifiers;
those can be cleaned up separately.
2020-02-18 16:16:37 -08:00
Saar Raz 5fef14d932 [Concepts] Do not check constraints if not all template arguments have been deduced
We previously checked the constraints of instantiated function templates even in cases where
PartialOverloading was true and not all template arguments have been deduced, which caused crashes
in clangd (bug 44714).

We now check if all arguments have been deduced before checking constraints in partial overloading
scenarios.
2020-02-12 16:02:12 +02:00
Richard Smith 9ce6dc9872 CWG1423: don't permit implicit conversion of nullptr_t to bool.
The C++ rules briefly allowed this, but the rule changed nearly 10 years
ago and we never updated our implementation to match. However, we've
warned on this by default for a long time, and no other compiler accepts
(even as an extension).
2020-02-11 06:52:45 -08:00
Richard Smith 7ef45f45f6 P1957R2: conversion from a pointer to bool is considered narrowing.
This is being implemented somewhat speculatively, to match GCC's
behavior.
2020-02-11 06:52:44 -08:00
Richard Smith 0e3a487784 PR12350: Handle remaining cases permitted by CWG DR 244.
Also add extension warnings for the cases that are disallowed by the
current rules for destructor name lookup, refactor and simplify the
lookup code, and improve the diagnostic quality when lookup fails.

The special case we previously supported for converting
p->N::S<int>::~S() from naming a class template into naming a
specialization thereof is subsumed by a more general rule here (which is
also consistent with Clang's historical behavior and that of other
compilers): if we can't find a suitable S in N, also look in N::S<int>.

The extension warnings are off by default, except for a warning when
lookup for p->N::S::~T() looks for T in scope instead of in N (or N::S).
That seems sufficiently heinous to warn on by default, especially since
we can't support it for a dependent nested-name-specifier.
2020-02-07 18:40:41 -08:00
Richard Smith 7ae1b4a0ce Implement P1766R1: diagnose giving non-C-compatible classes a typedef name for linkage purposes.
Summary:
Due to a recent (but retroactive) C++ rule change, only sufficiently
C-compatible classes are permitted to be given a typedef name for
linkage purposes. Add an enabled-by-default warning for these cases, and
rephrase our existing error for the case where we encounter the typedef
name for linkage after we've already computed and used a wrong linkage
in terms of the new rule.

Reviewers: rjmccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D74103
2020-02-07 11:47:37 -08:00
Richard Smith 96c899449b C++ DR2026: static storage duration variables are not zeroed before
constant initialization.

Removing this zeroing regressed our code generation in a few cases, also
fixed here. We now compute whether a variable has constant destruction
even if it doesn't have a constant initializer, by trying to destroy a
default-initialized value, and skip emitting a trivial default
constructor for a variable even if it has non-trivial (but perhaps
constant) destruction.
2020-02-06 16:37:22 -08:00
Richard Smith cfacf9ae20 PR44761: Fix fallback to later tiebreakers if two non-template functions
are equally constrained.
2020-02-04 12:21:42 -08:00
Fangrui Song dbc96b518b Revert "[CodeGenModule] Assume dso_local for -fpic -fno-semantic-interposition"
This reverts commit 789a46f2d7.

Accidentally committed.
2020-02-03 10:09:39 -08:00
Fangrui Song 789a46f2d7 [CodeGenModule] Assume dso_local for -fpic -fno-semantic-interposition
Summary:
Clang -fpic defaults to -fno-semantic-interposition (GCC -fpic defaults
to -fsemantic-interposition).
Users need to specify -fsemantic-interposition to get semantic
interposition behavior.

Semantic interposition is currently a best-effort feature. There may
still be some cases where it is not handled well.

Reviewers: peter.smith, rnk, serge-sans-paille, sfertile, jfb, jdoerfert

Subscribers: dschuff, jyknight, dylanmckay, nemanjai, jvesely, kbarton, fedor.sergeev, asb, rbar, johnrusso, simoncook, sabuasal, niosHD, jrtc27, zzheng, edward-jones, atanasyan, rogfer01, MartinMosbeck, brucehoult, the_o, arphaman, PkmX, jocewei, jsji, Jim, lenary, s.egerton, pzheng, sameer.abuasal, apazos, luismarques, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D73865
2020-02-03 09:52:48 -08:00
Richard Smith 42d4a55f22 PR44723: Trigger return type deduction for operator<=>s whose return
types are needed to compute the return type of a defaulted operator<=>.

This raises the question of what to do if return type deduction fails.
The standard doesn't say, and implementations vary, so for now reject
that case eagerly to keep our options open.
2020-01-31 13:06:48 -08:00
Saar Raz ba1f3db4b0 [Concepts] Correctly form initial parameter mapping for parameter packs, support substitution into SubstNonTypeTemplateParmExpr
We previously would not correctly for the initial parameter mapping for variadic template parameters in Concepts.
Testing this lead to the discovery that with the normalization process we would need to substitute into already-substituted-into
template arguments, which means we need to add NonTypeTemplateParmExpr support to TemplateInstantiator.
We do that by substituting into the replacement and the type separately, and then re-checking the expression against the NTTP
with the new type, in order to form any new required implicit casts (for cases where the type of the NTTP was dependent).
2020-01-31 15:59:42 +02:00
Richard Smith 1db66e705f PR44627: Consider reversing == and <=> candidates found by ADL. 2020-01-30 18:41:54 -08:00
Saar Raz 980517b353 [Concepts] Check function constraints before deducing auto return type
A constrained function with an auto return type would have it's definition
instantiated in order to deduce the auto return type before the constraints
are checked.

Move the constraints check after the return type deduction.
2020-01-31 03:51:26 +02:00
Richard Smith 1f3f8c369a PR44721: Don't consider overloaded operators for built-in comparisons
when building a defaulted comparison.

As a convenient way of asking whether `x @ y` is valid and building it,
we previouly always performed overload resolution and built an
overloaded expression, which would both end up picking a builtin
operator candidate when given a non-overloadable type. But that's not
quite right, because it can result in our finding a user-declared
operator overload, which we should never do when applying operators
non-overloadable types.

Handle this more correctly: skip overload resolution when building
`x @ y` if the operands are not overloadable. But still perform overload
resolution (considering only builtin candidates) when checking validity,
as we don't have any other good way to ask whether a binary operator
expression would be valid.
2020-01-30 17:16:50 -08:00
Saar Raz c83d9bedc0 [Concept] Fix incorrect check for containsUnexpandedParameterPack in CSE
We previously checked for containsUnexpandedParameterPack in CSEs by observing the property
in the converted arguments of the CSE. This may not work if the argument is an expanded
type-alias that contains a pack-expansion (see added test).

Check the as-written arguments when determining containsUnexpandedParameterPack and isInstantiationDependent.
2020-01-30 20:45:44 +02:00
Richard Smith 04f131da0b DR1753: Don't permit x.NS::~T() as a pseudo-destructor name.
When used as qualified names, pseudo-destructors are always named as if
they were members of the type, never as members of the namespace
enclosing the type.
2020-01-24 18:53:50 -08:00
Roman Lebedev 1d0972ff5e
[Sema] Introduce MaximumAlignment value, to be used instead of magical constants
There is llvm::Value::MaximumAlignment, which is numerically
equivalent to these constants, but we can't use it directly
because we can't include llvm IR headers in clang Sema.
So instead, copy-paste the constant, and fixup the places to use it.

This was initially reviewed in https://reviews.llvm.org/D72998
2020-01-24 17:49:17 +03:00
Saar Raz 73eaf62463 [Concepts] Make constraint expressions unevaluated until satisfaction checking
As per P1980R0, constraint expressions are unevaluated operands, and their constituent atomic
constraints only become constant evaluated during satisfaction checking.

Change the evaluation context during parsing and instantiation of constraints to unevaluated.
2020-01-24 02:24:21 +02:00
Saar Raz 67c608a969 [Concepts] Deprecate -fconcepts-ts, enable Concepts under -std=c++2a
Now with concepts support merged and mostly complete, we do not need -fconcepts-ts
(which was also misleading as we were not implementing the TS) and can enable
concepts features under C++2a. A warning will be generated if users still attempt
to use -fconcepts-ts.
2020-01-24 00:48:59 +02:00