3722 Commits

Author SHA1 Message Date
Vlad Serebrennikov
b45c9c313c
[clang][NFC] Move more functions to SemaHLSL (#88354)
A follow-up to #87912. I'm moving more HLSL-related functions from
`Sema` to `SemaHLSL`. I'm also dropping `HLSL` from their names in the
process.
2024-04-12 07:44:58 +04:00
Piyou Chen
334e07f18e
[RISCV] Disallow target attribute use in multiversioning (#85899)
For RISC-V target only `target_clones` and `target_version` can enable
function multiversion(FMV).

This patch make target attribute trigger redefinition instead of emit
FMV.

Here is spec
https://github.com/riscv-non-isa/riscv-c-api-doc/blob/master/riscv-c-api.md#__attribute__targetattr-string
2024-04-12 10:59:06 +08:00
Krystian Stasiowski
198ffb8531
[Clang][Sema] Implement approved resolution for CWG2858 (#88042)
The approved resolution for CWG2858 changes
[expr.prim.id.qual] p2 sentence 2 to read:
> A declarative _nested-name-specifier_ shall not have a
_computed-type-specifier_.

This patch implements the approved resolution. Since we don't consider
_nested-name-specifiers_ in friend declarations to be declarative (yet),
it currently isn't possible to write a test that would produce this
diagnostic (`diagnoseQualifiedDeclaration` is never called if the
`DeclContext` can't be computed). Nevertheless, tests were added which
will produce the diagnostic once we start calling
`diagnoseQualifiedDeclaration` for friend declarations.
2024-04-11 11:23:24 -04:00
Bill Wendling
fca51911d4
[NFC][Clang] Improve const correctness for IdentifierInfo (#79365)
The IdentifierInfo isn't typically modified. Use 'const' wherever
possible.
2024-04-11 00:33:40 +00:00
Dinar Temirbulatov
4e85e1ffca
[Clang][AArch64] Warn when calling non/streaming about vector size difference (#79842)
The compiler doesn't know in advance if the streaming and non-streaming
vector-lengths are different, so it should be safe to give a warning
diagnostic to warn the user about possible undefined behaviour. If the
user knows the vector lengths are equal, they can disable the warning
separately.
2024-04-10 08:39:50 +01:00
Qizhi Hu
cfb86ae749
[Clang][Sema] Skip checking anonymous enum in using enum declaration (#87144)
Try to fix https://github.com/llvm/llvm-project/issues/86790
`getFETokenInfo` requires `DeclarationName` shouldn't be empty and this
will produce crash when checking name conflict of an anonymous
`NamedDecl` in `Sema::PushOnScopeChains` and whether it's a reserved
identifier or not. These wouldn't happen when it's a anonymous enum and
we can skip the checking and just add the declaration to current scope.

Co-authored-by: huqizhi <836744285@qq.com>
2024-04-05 15:18:07 +08:00
Youngsuk Kim
90453f4a9a
[Clang][Sema] Warn unused cxx vardecl which entirely consists condition expr of if/while/for construct (#87348)
Emit `-Wunused-but-set-variable` warning on C++ variables whose
declaration (with initializer) entirely consist the condition expression
of a if/while/for construct but are not actually used in the body of the
if/while/for construct.

Fixes #41447
2024-04-04 20:45:18 -04:00
Krystian Stasiowski
eb08c0f165
[Clang][Sema] Fix explicit specializations of member function templates with a deduced return type (#86817)
Clang erroneously rejects the following:
```
template<typename T>
struct A
{
    template<typename U>
    auto f();
};

template<>
template<typename U>
auto A<int>::f(); // error: conflicting types for 'f'
```
This happens because the explicit specialization of `f` has its return
type replaced with a dependent `AutoType` in `ActOnFunctionDeclarator`,
but no such replacement occurs for the implicitly instantiated function
template `A<int>::f`. Since the return types don't match, the explicit
specialization is diagnosed as an invalid redeclaration.

This patch moves the replacement of the return type to
`CheckFunctionDeclaration` so it also happens during instantiation.
`setObjectOfFriendDecl` will have been called by then, so the `isFriend
&& CurContext->isDependentContext()` condition is made redundant &
removed (as it already happens in `DeclContext::isDependentContext`).
`Sema::IsOverload` only checks the _declared_ return type (which isn't
changed by the adjustment), so adjusting the return type afterwards
should be safe.
2024-04-02 08:35:42 -04:00
Sam McCall
7ef602b58c
Reapply "[clang][nullability] allow _Nonnull etc on nullable class types (#82705)" (#87325)
This reverts commit 28760b63bbf9e267713957105a8d17091fb0d20e.

The last commit was missing the new testcase, now fixed.
2024-04-02 13:48:45 +02:00
Sirraide
af34ac4508
[Clang] [Sema] No longer diagnose type definitions in offsetof in C23 mode (#84169)
This is now allowed in C23; continue to diagnose it in earlier language
modes as before, but now as a C23 extension rather than a GNU extension.

This fixes #83658.
2024-03-29 17:42:09 +01:00
Chuanqi Xu
abfc5efb55 [NFC] [Decl] Introduce Decl::isFromExplicitGlobalModule
Introduce `Decl::isFromExplicitGlobalModule` to replace the
`D->getOwningModule() && D->getOwningModule()->isExplicitGlobalModule()`
pattern to save some typings.
2024-03-29 16:21:02 +08:00
dyung
28760b63bb
Revert "Reapply "[clang][nullability] allow _Nonnull etc on nullable class types (#82705)"" (#87041)
This reverts commit bbbcc1d99d08855069f4501c896c43a6d4d7b598.

This change is causing the following build bots to fail due to a missing
header file:
- https://lab.llvm.org/buildbot/#/builders/188/builds/43765
- https://lab.llvm.org/buildbot/#/builders/176/builds/9428
- https://lab.llvm.org/buildbot/#/builders/187/builds/14696
- https://lab.llvm.org/buildbot/#/builders/186/builds/15551
- https://lab.llvm.org/buildbot/#/builders/182/builds/9413
- https://lab.llvm.org/buildbot/#/builders/245/builds/22507
- https://lab.llvm.org/buildbot/#/builders/258/builds/16026
- https://lab.llvm.org/buildbot/#/builders/249/builds/17221
- https://lab.llvm.org/buildbot/#/builders/38/builds/18566
- https://lab.llvm.org/buildbot/#/builders/214/builds/11735
- https://lab.llvm.org/buildbot/#/builders/231/builds/21947
- https://lab.llvm.org/buildbot/#/builders/230/builds/26675
- https://lab.llvm.org/buildbot/#/builders/57/builds/33922
- https://lab.llvm.org/buildbot/#/builders/124/builds/10311
- https://lab.llvm.org/buildbot/#/builders/109/builds/86173
- https://lab.llvm.org/buildbot/#/builders/280/builds/1043
- https://lab.llvm.org/buildbot/#/builders/283/builds/440
- https://lab.llvm.org/buildbot/#/builders/247/builds/16034
- https://lab.llvm.org/buildbot/#/builders/139/builds/62423
- https://lab.llvm.org/buildbot/#/builders/216/builds/36718
- https://lab.llvm.org/buildbot/#/builders/259/builds/2039
- https://lab.llvm.org/buildbot/#/builders/36/builds/44091
- https://lab.llvm.org/buildbot/#/builders/272/builds/12629
- https://lab.llvm.org/buildbot/#/builders/271/builds/6020
- https://lab.llvm.org/buildbot/#/builders/236/builds/10319
2024-03-29 00:50:11 -07:00
Sam McCall
bbbcc1d99d Reapply "[clang][nullability] allow _Nonnull etc on nullable class types (#82705)"
This reverts commit ca4c4a6758d184f209cb5d88ef42ecc011b11642.

This was intended not to introduce new consistency diagnostics for
smart pointer types, but failed to ignore sugar around types when
detecting this.
Fixed and test added.
2024-03-28 23:57:09 +01:00
Kees Cook
14ba782a87
[Clang][Sema] Allow flexible arrays in unions and alone in structs (#84428)
GNU and MSVC have extensions where flexible array members (or their
equivalent) can be in unions or alone in structs. This is already fully
supported in Clang through the 0-sized array ("fake flexible array")
extension or when C99 flexible array members have been syntactically
obfuscated.

Clang needs to explicitly allow these extensions directly for C99
flexible arrays, since they are common code patterns in active use by
the
Linux kernel (and other projects). Such projects have been using either
0-sized arrays (which is considered deprecated in favor of C99 flexible
array members) or via obfuscated syntax, both of which complicate their
code bases.

For example, these do not error by default:
```
union one {
	int a;
	int b[0];
};

union two {
	int a;
	struct {
		struct { } __empty;
		int b[];
	};
};
```
But this does:
```
union three {
	int a;
	int b[];
};
```
Remove the default error diagnostics for this but continue to provide
warnings under Microsoft or GNU extensions checks. This will allow for
a seamless transition for code bases away from 0-sized arrays without
losing existing code patterns. Add explicit checking for the warnings
under various constructions.

Additionally fixes a CodeGen bug with flexible array members in unions
in C++, which was found when adding a testcase for:
```
union { char x[]; } z = {0};
```
which only had Sema tests originally.

Fixes #84565
2024-03-27 16:56:19 -06:00
Brandon Wu
13b653ab11
[clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (#83674)
It is currently not possible to use "RVV type" and "RVV intrinsics" if
the "zve32x" is not enabled globally. However in some cases we may want
to use them only in some functions, for instance:
```
#include <riscv_vector.h>

__attribute__((target("+zve32x")))
vint32m1_t rvv_add(vint32m1_t v1, vint32m1_t v2, size_t vl) {
  return __riscv_vadd(v1, v2, vl);
}

int other_add(int i1, int i2) {
  return i1 + i2;
}
```
, it is supposed to be compilable even the vector is not specified, e.g.
`clang -target riscv64 -march=rv64gc -S test.c`.
2024-03-27 23:22:01 +08:00
Chris B
28ddbd4a86
[NFC] Refactor ConstantArrayType size storage (#85716)
In PR #79382, I need to add a new type that derives from
ConstantArrayType. This means that ConstantArrayType can no longer use
`llvm::TrailingObjects` to store the trailing optional Expr*.

This change refactors ConstantArrayType to store a 60-bit integer and
4-bits for the integer size in bytes. This replaces the APInt field
previously in the type but preserves enough information to recreate it
where needed.

To reduce the number of places where the APInt is re-constructed I've
also added some helper methods to the ConstantArrayType to allow some
common use cases that operate on either the stored small integer or the
APInt as appropriate.

Resolves #85124.
2024-03-26 14:15:56 -05:00
Jie Fu
feebcd65fb [clang] Fix -Wunused-variable in SemaDecl.cpp (NFC)
llvm-project/clang/lib/Sema/SemaDecl.cpp:11653:20:
error: unused variable 'OldMVKind' [-Werror,-Wunused-variable]
  MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
                   ^
1 error generated.
2024-03-26 20:41:46 +08:00
Alexandros Lamprineas
da9ac43433
[FMV] Allow mixing target_version with target_clones. (#86493)
The latest ACLE allows it and further clarifies the following
in regards to the combination of the two attributes:

"If the `default` matches with another explicitly provided
 version in the same translation unit, then the compiler can
 emit only one function instead of the two. The explicitly
 provided version shall be preferred."

("default" refers to the default clone here)

https://github.com/ARM-software/acle/pull/310
2024-03-26 11:36:34 +00:00
Alexandros Lamprineas
772e316457
[FMV] Allow multi versioning without default declaration. (#85454)
This was a limitation which has now been lifted. Please read the
thread below for more details:

https://github.com/llvm/llvm-project/pull/84405#discussion_r1525583647

Basically it allows to separate versioned implementations across
different TUs without having to share private header files which
contain the default declaration.

The ACLE spec has been updated accordingly to make this explicit:
"Each version declaration should be visible at the translation
 unit in which the corresponding function version resides."

https://github.com/ARM-software/acle/pull/310

If a resolver is required (because there is a caller in the TU),
then a default declaration is implicitly generated.
2024-03-25 09:43:41 +00:00
Nikolas Klauser
2699072b4b
[clang] Accept lambdas in C++03 as an extensions (#73376)
Implements
https://discourse.llvm.org/t/rfc-allow-c-11-lambdas-in-c-03-as-an-extension/75262
2024-03-21 12:57:24 +01:00
Yeoul Na
3eb9ff3095
Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (#78000)
In `-fbounds-safety`, bounds annotations are considered type attributes
rather than declaration attributes. Constructing them as type attributes
allows us to extend the attribute to apply nested pointers, which is
essential to annotate functions that involve out parameters: `void
foo(int *__counted_by(*out_count) *out_buf, int *out_count)`.

We introduce a new sugar type to support bounds annotated types,
`CountAttributedType`. In order to maintain extra data (the bounds
expression and the dependent declaration information) that is not
trackable in `AttributedType` we create a new type dedicate to this
functionality.

This patch also extends the parsing logic to parse the `counted_by`
argument as an expression, which will allow us to extend the model to
support arguments beyond an identifier, e.g., `__counted_by(n + m)` in
the future as specified by `-fbounds-safety`.

This also adjusts `__bdos` and array-bounds sanitizer code that already
uses `CountedByAttr` to check `CountAttributedType` instead to get the
field referred to by the attribute.
2024-03-20 13:36:56 +09:00
Sam McCall
ca4c4a6758 Revert "[clang][nullability] allow _Nonnull etc on nullable class types (#82705)"
This reverts commit 92a09c0165b87032e1bd05020a78ed845cf35661.

This is triggering a bunch of new -Wnullability-completeness warnings
in code with existing raw pointer nullability annotations.

The intent was the new nullability locations wouldn't affect those
warnings, so this is a bug at least for now.
2024-03-15 21:55:37 +01:00
Sam McCall
92a09c0165
[clang][nullability] allow _Nonnull etc on nullable class types (#82705)
This enables clang and external nullability checkers to make use of
these annotations on nullable C++ class types like unique_ptr.

These types are recognized by the presence of the _Nullable attribute.
Nullable standard library types implicitly receive this attribute.

Existing static warnings for raw pointers are extended to smart
pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply
them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

Support can be detected as `__has_feature(nullability_on_classes)`.
This is needed for back-compatibility, as previously clang would issue a
hard error when _Nullable appears on a smart pointer.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.

Discussion:
https://discourse.llvm.org/t/rfc-allowing-nonnull-etc-on-smart-pointers/77201/26
2024-03-14 16:45:24 +01:00
Younan Zhang
c1c8a0cb17
[concepts] Preserve the FoundDecl of ConceptReference properly (#85032)
The `ConceptReference`'s `FoundDecl` claims it "can differ from
`NamedConcept` when, for example, the concept was found through a
`UsingShadowDecl`", but such the contract was not previously respected.

Fixes https://github.com/llvm/llvm-project/issues/82628
2024-03-14 10:09:47 +08:00
Krystian Stasiowski
ee94bd20ba
Revert "[Clang][Sema] Fix crash when using name of UnresolvedUsingValueDecl with template arguments (#83842)" (#84457)
This reverts commit a642eb89bdaf10c6b4994fc1187de27b441236ed (see #83842)
2024-03-08 05:57:04 -05:00
Mariya Podchishchaeva
dd36138e9c
[clang] Error on explicit specialization of lambda call operator (#84343)
Fixes https://github.com/llvm/llvm-project/issues/83267
2024-03-08 09:52:42 +01:00
Stefan Gränitz
4b70d17bcf
[clang-repl] Names declared in if conditions and for-init statements are local to the inner context (#84150)
Make TopLevelStmtDecl a DeclContext so that variables defined in statements
are attached to the TopLevelDeclContext. This fixes redefinition errors
from variables declared in if conditions and for-init statements. These
must be local to the inner context (C++ 3.3.2p4), but they had generated
definitions on global scope instead.

This PR makes the TopLevelStmtDecl looking more like a FunctionDecl and
that's fine because the FunctionDecl is very close in terms of semantics.

Additionally, ActOnForStmt() requires a CompoundScope when processing a
NullStmt body.

---------

Co-authored-by: Vassil Vassilev <v.g.vassilev@gmail.com>
2024-03-07 14:27:04 +01:00
Alexandros Lamprineas
92529eb4ae
[FMV] Allow target version definitions in any order. (#83887)
This patch fixes #71698. It allows defining the default target version
prior to other version definitions without raising semantic errors.
2024-03-06 10:42:39 +00:00
Mariya Podchishchaeva
aced81c0a5
[C23] Implement N3018: The constexpr specifier for object definitions (#73099)
The implementation mostly reuses C++ code paths where possible,
including narrowing check in order to provide diagnostic messages in
case initializer for constexpr variable is not exactly representable in
target type.

The following won't work due to lack of support for other features:
- Diagnosing of underspecified declarations involving constexpr
- Constexpr attached to compound literals

Also due to lack of support for char8_t some of examples with utf-8
strings don't work properly.

Fixes https://github.com/llvm/llvm-project/issues/64742
2024-03-06 09:46:35 +01:00
Krystian Stasiowski
a642eb89bd
[Clang][Sema] Fix crash when using name of UnresolvedUsingValueDecl with template arguments (#83842)
The following snippet causes a crash:
```
template<typename T>
struct A : T {
  using T::f;
  void f();

  void g() {
    f<int>(); // crash here
  }
};
```
This happens because we cast the result of `getAsTemplateNameDecl` as a
`TemplateDecl` in `Sema::ClassifyName`, which we cannot do for an
`UnresolvedUsingValueDecl`. This patch fixes the crash by considering a name
to be that of a template if _any_ function declaration is found per [temp.names] p3.3.
2024-03-05 08:52:20 -05:00
Krystian Stasiowski
c1d8d0aa15
Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (#79683)
Reapplies #78274 with the addition of a default-error warning
(`strict-primary-template-shadow`) that is issued for instances of
shadowing which were previously accepted prior to this patch.

I couldn't find an established convention for naming diagnostics related
to compatibility with previous versions of clang, so I just used the
prefix `ext_compat_`.
2024-03-04 09:18:21 -05:00
Vinayak Dev
2b4d67bf59
[Clang][Sema]: Allow copy constructor side effects (#81127)
Copy constructors can have initialization with side effects, and thus
clang should not emit a warning when -Wunused-variable is used in this
context. Currently however, a warning is emitted.

Now, compilation happens without warnings.

Fixes #79518
2024-03-01 10:40:46 -05:00
Egor Zhdan
440b1743ee
[APINotes] Upstream Sema logic to apply API Notes to decls
This upstreams more of the Clang API Notes functionality that is
currently implemented in the Apple fork:
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes

This was extracted from a larger PR:
https://github.com/llvm/llvm-project/pull/73017
2024-02-26 13:52:27 +00:00
Krystian Stasiowski
fb615cf3b9
[Clang][Sema] Diagnose declarative nested-name-specifiers naming alias templates (#80842)
According to [expr.prim.id.qual] p3:
> The _nested-name-specifier_ `​::` nominates the global namespace. A
_nested-name-specifier_ with a _computed-type-specifier_ nominates the
type denoted by the _computed-type-specifier_, which shall be a class or
enumeration type. **If a _nested-name-specifier_ `N` is declarative and
has a _simple-template-id_ with a template argument list `A` that
involves a template parameter, let `T` be the template nominated by `N`
without `A`. `T` shall be a class template.**

Meaning, the out-of-line definition of `A::f` in the following example
is ill-formed:
```
template<typename T>
struct A 
{ 
    void f(); 
};

template<typename T>
using B = A<T>;

template<typename T>
void B<T>::f() { } // error: a declarative nested name specifier cannot name an alias template
```

This patch diagnoses such cases as an extension (in group `alias-template-in-declaration-name`).
2024-02-20 13:25:12 -05:00
Aaron Ballman
3b7ba2482e
[C23] No longer assert on huge enumerator values (#81760)
C23 added the wb and uwb suffixes to generate a bit-precise integer
value. These values can be larger than what is representable in intmax_t
or uintmax_t.

We were asserting that an enumerator constant could not have a value
larger than unsigned long long but that's now a possibility. This patch
turns the assertion into a "value too large" diagnostic.

Note, we do not yet implement WG14 N3029 and so the behavior of this
patch will cause the enumerator to be cast to unsigned long long, but
this behavior may change in the future. GCC selects __uint128_t as the
underlying type for such an enumeration and we may want to match that
behavior in the future. This patch has several FIXME comments related to
this and the release notes call out the possibility of a change in
behavior in the future.

Fixes https://github.com/llvm/llvm-project/issues/69352
2024-02-20 11:58:03 -05:00
Mikael Holmen
4a32a414ee [clang] Fix two gcc warnings about unused variables [NFC]
Without the fix gcc warns like
 ../../clang/lib/Sema/SemaDecl.cpp:2963:24: warning: unused variable 'SupA' [-Wunused-variable]
  2963 |   else if (const auto *SupA = dyn_cast<SuppressAttr>(Attr))
       |                        ^~~~
and
 ../../clang/lib/Driver/Driver.cpp:4192:17: warning: unused variable 'IAA' [-Wunused-variable]
  4192 |       if (auto *IAA = dyn_cast<InstallAPIJobAction>(Current)) {
       |                 ^~~

Remove the unused variables and change the "dyn_cast"s into "isa"s.
2024-02-15 10:31:59 +01:00
Vlad Serebrennikov
502756905c
[clang][NFC] Use "notable" for "interesting" identifiers in IdentifierInfo (#81542)
This patch expands notion of "interesting" in `IdentifierInto` it to
also cover ObjC keywords and builtins, which matches notion of
"interesting" in serialization layer. What was previously "interesting"
in `IdentifierInto` is now called "notable".

Beyond clearing confusion between serialization and the rest of the
compiler, it also resolved a naming problem: ObjC keywords, notable
identifiers, and builtin IDs are all stored in the same bit-field. Now
we can use "interesting" to name it and its corresponding type, instead
of `ObjCKeywordOrInterestingOrBuiltin` abomination.
2024-02-14 16:39:00 +04:00
Artem Dergachev
017675fff1
[attributes][analyzer] Generalize [[clang::suppress]] to declarations. (#80371)
The attribute is now allowed on an assortment of declarations, to
suppress warnings related to declarations themselves, or all warnings in
the lexical scope of the declaration.

I don't necessarily see a reason to have a list at all, but it does look
as if some of those more niche items aren't properly supported by the
compiler itself so let's maintain a short safe list for now.

The initial implementation raised a question whether the attribute
should apply to lexical declaration context vs. "actual" declaration
context. I'm using "lexical" here because it results in less warnings
suppressed, which is the conservative behavior: we can always expand it
later if we think this is wrong, without breaking any existing code. I
also think that this is the correct behavior that we will probably never
want to change, given that the user typically desires to keep the
suppressions as localized as possible.
2024-02-13 14:57:55 -08:00
Krystian Stasiowski
3a48630a4b
[Clang][Sema] Diagnose friend declarations with enum elaborated-type-specifier in all language modes (#80171)
According to [dcl.type.elab] p4:
> If an _elaborated-type-specifier_ appears with the `friend` specifier
as an entire _member-declaration_, the _member-declaration_ shall have
one of the following forms:
>     `friend` _class-key_ _nested-name-specifier_(opt) _identifier_ `;`
>     `friend` _class-key_ _simple-template-id_ `;`
> `friend` _class-key_ _nested-name-specifier_ `template`(opt)
_simple-template-id_ `;`

Notably absent from this list is the `enum` form of an
_elaborated-type-specifier_ "`enum` _nested-name-specifier_(opt)
_identifier_", which appears to be intentional per the resolution of
CWG2363.

Most major implementations accept these declarations, so the diagnostic
is a pedantic warning across all C++ versions.

In addition to the trivial cases previously diagnosed in C++98, we now
diagnose cases where the _elaborated-type-specifier_ has a dependent
_nested-name-specifier_:
```
template<typename T>
struct A
{
    enum class E;
};

struct B
{
    template<typename T>
    friend enum A<T>::E; // pedantic warning: elaborated enumeration type cannot be a friend
};

template<typename T>
struct C
{
    friend enum T::E;  // pedantic warning: elaborated enumeration type cannot be a friend
};
```
2024-02-13 14:25:56 -05:00
Vlad Serebrennikov
dfbe2bca1d
[clang][NFC] Refactor Sema::TemplateDeductionResult (#81398)
This patch converts `Sema::TemplateDeductionResult` into a scoped enum
in namespace scope, making it eligible for forward declaring. This is
useful in certain contexts, such as `preferred_type` annotations on
bit-fields.
2024-02-12 21:27:58 +04:00
Mariya Podchishchaeva
c90114c993
[clang] Avoid -Wshadow warning when init-capture named same as class field (#74512)
Shadowing warning doesn't make much sense since field is not available
in lambda's body without capturing this.

Fixes https://github.com/llvm/llvm-project/issues/71976
2024-02-12 10:44:20 +01:00
Krystian Stasiowski
17f0680f69
[Clang][Sema] Abbreviated function templates do not append invented parameters to empty template parameter lists (#80864)
According to [dcl.fct] p23:
> An abbreviated function template can have a _template-head_. The
invented _template-parameters_ are appended to the
_template-parameter-list_ after the explicitly declared
_template-parameters_.

`template<>` is not a _template-head_ -- a _template-head_ must have at
least one _template-parameter_. This patch corrects our current behavior
of appending the invented template parameters to the innermost template
parameter list, regardless of whether it is empty. Example:
```
template<typename T>
struct A 
{ 
    void f(auto); 
};

template<>
void A<int>::f(auto); // ok

template<>
template<> // warning: extraneous template parameter list in template specialization
void A<int>::f(auto);
```
2024-02-08 13:04:10 -05:00
Krystian Stasiowski
51a3019e4d
[Clang][Sema] Implement proposed resolution for CWG2847 (#80899)
Per the approved resolution for CWG2847, [temp.expl.spec] p8 will state:
> An explicit specialization shall not have a trailing _requires-clause_ unless it declares a function template.

We already implement this _partially_ insofar that a diagnostic is issued upon instantiation of `A<int>` in the following example:
```
template<typename>
struct A
{
    template<typename>
    void f();

    template<>
    void f<int>() requires true; // error: non-templated function cannot have a requires clause
};
template struct A<int>;  // note: in instantiation of template class 'A<int>' requested here
```

This patch adds a bespoke diagnostic for such declarations, and moves the point of diagnosis for non-templated functions with trailing requires-clauses from `CheckFunctionDeclaration` to `ActOnFunctionDeclarator` (there is no point in diagnosing this during instantiation since we already have all the necessary information when parsing the declaration).
2024-02-06 16:06:38 -05:00
Krystian Stasiowski
1156bbc5b1
[Clang][Sema] Diagnose use of template keyword after declarative nested-name-specifiers (#78595)
According to [temp.names] p5:
> The keyword template shall not appear immediately after a declarative nested-name-specifier.

[expr.prim.id.qual] p2 defines a declarative nested-name-specifier as follows:
> A nested-name-specifier is declarative if it is part of
> - a class-head-name,
> - an enum-head-name,
> - a qualified-id that is the id-expression of a declarator-id, or
> - a declarative nested-name-specifier.

Note: I believe this definition is defective as it doesn't include _nested-name-specifiers_ appearing in _elaborated-type-specifiers_ that declare partial/explicit specializations and explicit instantiations. See my post to the core reflector. Minus a few bugs that are addressed by this PR, this is how we implement it.

This means that declarations like:
```
template<typename>
struct A
{
    template<typename> 
    struct B
   {
        void f();
   };
};

template<typename T>
template<typename U>
void A<T>::template B<U>::f() { } // error: 'template' cannot be used after a declarative nested name specifier
```
are ill-formed. This PR add diagnostics for such declarations. The name of the diagnostic group is `template-in-declaration-name`.

Regarding the aforementioned "few bugs that are addressed by this PR" in order to correctly implement this:
- `CheckClassTemplate` did not call `diagnoseQualifiedDeclaration` when the semantic context was dependent. This allowed for constructs like:
```
struct A
{
    template<typename T>
    struct B
    {
        template<typename U>
        struct C;
    };
};

template<typename T>
template<typename U>
struct decltype(A())::B<T>::C { };
```
- `ActOnClassTemplateSpecialization` did not call `diagnoseQualifiedDeclaration` at all, allowing for qualified partial/explicit specializations at class scope and other related nonsense
- `TreeTransform::TransformNestedNameSpecifierLoc` would rebuild a `NestedNameSpecifier::TypeSpecWithTemplate` as a `NestedNameSpecifier::TypeSpec`
- `TemplateSpecializationTypeLoc::initializeLocal` would set the `template` keyword `SourceLocation` to the provided `Loc` parameter, which would result in a `TemplateSpecializationTypeLoc` obtained via `ASTContext::getTrivialTypeSourceInfo` being displayed as always having a `template` prefix (since the presence of the keyword is not stored anywhere else).
2024-02-02 13:15:41 -05:00
Krystian Stasiowski
7ecfb66c77
[Clang][Sema] Correctly look up primary template for variable template specializations (#80359)
Consider the following:
```
namespace N0 {
  namespace N1 {
    template<typename T>
    int x1 = 0;
  }
  using namespace N1;
}
template<>
int N0::x1<int>;
```

According to [dcl.meaning.general] p3.3:
> - If the _declarator_ declares an explicit instantiation or a partial
or explicit specialization, the _declarator_ does not bind a name. If it
declares a class member, the terminal name of the _declarator-id_ is not
looked up; otherwise, **only those lookup results that are nominable in
`S` are considered when identifying any function template specialization
being declared**.

In particular, the requirement for lookup results to be nominal in the
lookup context of the terminal name of the _declarator-id_ only applies
to function template specializations -- not variable template
specializations. We currently reject the above declaration, but we do
(correctly) accept it if the using-directive is replaced with a `using`
declaration naming `N0::N1::x1`. This patch makes it so the above
specialization is (correctly) accepted.
2024-02-02 12:53:34 -05:00
Owen Pan
a8279a8bc5
[clang][NFC] Move isSimpleTypeSpecifier() from Sema to Token (#80101)
So that it can be used by clang-format.
2024-01-31 20:16:18 -08:00
Carl Peto
b4d832c77d
[clang] Improved isSimpleTypeSpecifier (#79037)
- Sema::isSimpleTypeSpecifier return true for _Bool in c99 (currently
returns false for _Bool, regardless of C dialect). (Fixes #72203)
- replace the logic with a check for simple types and a proper check for
a valid keyword in the appropriate dialect

Co-authored-by: Carl Peto <CPeto@becrypt.com>
2024-01-30 18:18:49 -08:00
Krystian Stasiowski
a0d266d705
[Clang][Sema] Allow elaborated-type-specifiers that declare member class template explict specializations (#78720)
According to [[dcl.type.elab]
p2](http://eel.is/c++draft/dcl.type.elab#2):
> If an
[elaborated-type-specifier](http://eel.is/c++draft/dcl.type.elab#nt:elaborated-type-specifier)
is the sole constituent of a declaration, the declaration is ill-formed
unless it is an explicit specialization, an explicit instantiation or it
has one of the following forms [...]

Consider the following:
```cpp
template<typename T>
struct A 
{
    template<typename U>
    struct B;
};

template<>
template<typename U>
struct A<int>::B; // #1
```
The _elaborated-type-specifier_ at `#1` declares an explicit
specialization (which is itself a template). We currently (incorrectly)
reject this, and this PR fixes that.

I moved the point at which _elaborated-type-specifiers_ with
_nested-name-specifiers_ are diagnosed from `ParsedFreeStandingDeclSpec`
to `ActOnTag` for two reasons: `ActOnTag` isn't called for explicit
instantiations and partial/explicit specializations, and because it's
where we determine if a member specialization is being declared.

With respect to diagnostics, I am currently issuing the diagnostic
without marking the declaration as invalid or returning early, which
results in more diagnostics that I think is necessary. I would like
feedback regarding what the "correct" behavior should be here.
2024-01-30 08:28:13 -05:00
Andrey Ali Khan Bolshakov
ef67f63fa5
Fix analyzer crash on 'StructuralValue' (#79764)
`OpaqueValueExpr` doesn't necessarily contain a source expression.
Particularly, after #78041, it is used to carry the type and the value
kind of a non-type template argument of floating-point type or referring
to a subobject (those are so called `StructuralValue` arguments).

This fixes #79575.
2024-01-30 13:03:55 +01:00
cor3ntin
ad1a65fcac
[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)
Implements https://isocpp.org/files/papers/P2662R3.pdf

The feature is exposed as an extension in older language modes.
Mangling is not yet supported and that is something we will have to do before release.
2024-01-27 10:23:38 +01:00