3697 Commits

Author SHA1 Message Date
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
Sander de Smalen
1652d44d8d
[Clang] Amend SME attributes with support for ZT0. (#77941)
This patch builds on top of #76971 and implements support for:
* __arm_new("zt0")
* __arm_in("zt0")
* __arm_out("zt0")
* __arm_inout("zt0")
* __arm_preserves("zt0")
2024-01-23 12:35:16 +01:00
Corentin Jabot
8658d15765 Revert "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)"
This reverts commit fc0253264445be7f88d4cf0f9129dcb10c2fb84b.

This errors is disruptive to downstream projects
and should be reintroduced as a separate on-by-default
warning.

https://github.com/llvm/llvm-project/pull/78274
2024-01-22 09:29:01 +01:00
kelbon
818de32f31
Warning for incorrect use of 'pure' attribute (#78200)
This adds a warning when applying the `pure` attribute along with the `const` attribute, or when applying the `pure` attribute to a function with a `void` return type (including constructors and destructors).

Fixes https://github.com/llvm/llvm-project/issues/77482
2024-01-20 12:37:35 -05:00
cor3ntin
e90e43fb9c
[Clang][NFC] Rename CXXMethodDecl::isPure -> is VirtualPure (#78463)
To avoid any possible confusion with the notion of pure function and the
gnu::pure attribute.
2024-01-18 15:30:58 +01:00
Utkarsh Saxena
667e58a72e
[coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures (#77066)
### Problem

```cpp
co_task<int> coro() {
    int a = 1;
    auto lamb = [a]() -> co_task<int> {
        co_return a; // 'a' in the lambda object dies after the iniital_suspend in the lambda coroutine.
    }();
    co_return co_await lamb;
}
```
[use-after-free](https://godbolt.org/z/GWPEovWWc)

Lambda captures (even by value) are prone to use-after-free once the
lambda object dies. In the above example, the lambda object appears only
as a temporary in the call expression. It dies after the first
suspension (`initial_suspend`) in the lambda.
On resumption in `co_await lamb`, the lambda accesses `a` which is part
of the already-dead lambda object.

---

### Solution

This problem can be formulated by saying that the `this` parameter of
the lambda call operator is a lifetimebound parameter. The lambda object
argument should therefore live atleast as long as the return object.
That said, this requirement does not hold if the lambda does not have a
capture list. In principle, the coroutine frame still has a reference to
a dead lambda object, but it is easy to see that the object would not be
used in the lambda-coroutine body due to no capture list.

It is safe to use this pattern inside a`co_await` expression due to the
lifetime extension of temporaries. Example:

```cpp
co_task<int> coro() {
    int a = 1;
    int res = co_await [a]() -> co_task<int> { co_return a; }();
    co_return res;
}
```
---
### Background

This came up in the discussion with seastar folks on
[RFC](https://discourse.llvm.org/t/rfc-lifetime-bound-check-for-parameters-of-coroutines/74253/19?u=usx95).
This is a fairly common pattern in continuation-style-passing (CSP)
async programming involving futures and continuations. Document ["Lambda
coroutine
fiasco"](https://github.com/scylladb/seastar/blob/master/doc/lambda-coroutine-fiasco.md)
by Seastar captures the problem.
This pattern makes the migration from CSP-style async programming to
coroutines very bugprone.


Fixes https://github.com/llvm/llvm-project/issues/76995

---------

Co-authored-by: Chuanqi Xu <yedeng.yd@linux.alibaba.com>
2024-01-18 11:56:55 +01:00
Erich Keane
3db5c058ff
Add Variadic 'dropAttrs' (#78476)
As suggested in https://github.com/llvm/llvm-project/pull/78200

This adds a variadic 'dropAttrs', which drops all attributes of any of
the types specified.
2024-01-17 15:01:53 -08:00
Krystian Stasiowski
fc02532644
[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)
Previously, we skipped through template parameter scopes (until we hit a
declaration scope) prior to redeclaration lookup for declarators. For
template declarations, the meant that their template parameters would
not be found and shadowing would not be diagnosed. With these changes
applied, the following declarations are correctly diagnosed:
```cpp
template<typename T> void T(); // error: declaration of 'T' shadows template parameter
template<typename U> int U; // error: declaration of 'U' shadows template parameter
```

The reason for skipping past non-declaration & template parameter scopes
prior to lookup appears to have been because `GetTypeForDeclarator`
needed this adjusted scope... but it doesn't actually use this parameter
anymore. 

The scope adjustment now happens prior to calling
`ActOnFunctionDeclarator`/`ActOnVariableDeclarator`/`ActOnTypedefDeclarator`
(just in case they depend on this behavior... I didn't check in depth).
2024-01-17 09:13:18 -05:00
Egor Zhdan
77d21e758e
[APINotes] Upstream dependencies of 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 is the largest chunk of the API Notes functionality in the
upstreaming process. I will soon submit a follow-up patch to actually
enable usage of this functionality by having a Clang driver flag that
enables API Notes, along with tests.
2024-01-17 13:13:10 +00:00
Haojian Wu
8f7fdd94ef
[clang][AST] Invalidate DecompositionDecl if it has invalid initializer. (#72428)
Fix #67495, #72198

We build ill-formed AST nodes for invalid structured binding. For case
`int [_, b] = {0, 0};`, the `DecompositionDecl` is valid, and its
children `BindingDecl`s are valid but with a NULL type, this breaks
clang invariants in many places, and using these `BindingDecl`s can lead
to crashes. This patch fixes them by marking the DecompositionDecl and
its children invalid.
2024-01-17 12:11:16 +01:00
Krystian Stasiowski
68ae1e49d2
[Clang][Sema][NFC] Remove unused Scope* parameter from Sema::GetTypeForDeclarator and Sema::ActOnTypeName (#78325)
Split from #78274
2024-01-17 05:47:57 -05:00
antangelo
46a395d8c4
[clang] Emit error for invalid friend functions under [temp.friend]p9 (#78083)
Emits an error for friend FunctionDecls that either:

* are not templates and have a requires clause
* are templates, and have a constrained parameter that depends on a
template parameter from an enclosing template

and are not a definition.

For a non-template friend function with a requires clause, if the
function is not templated then the original error message indicating
that such a function is disallowed is shown instead, as the function
will still be rejected if a definition is added.
2024-01-16 21:06:02 -05:00
Bill Wendling
00b6d032a2 [Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-16 14:26:12 -08:00
Craig Topper
142f270c27 Recommit "[AST] Use APIntStorage to fix memory leak in EnumConstantDecl. (#78311)"
With lldb build fix.

Original message:

EnumConstantDecl is allocated by the ASTContext allocator so the
destructor is never called.

This patch takes a similar approach to IntegerLiteral by using
APIntStorage to allocate large APSInts using the ASTContext allocator as
well.

The downside is that an additional heap allocation and copy of the data
needs to be made when calling getInitValue if the APSInt is large.

Fixes #78160.
2024-01-16 13:52:17 -08:00
Craig Topper
f3d534c425 Revert "[AST] Use APIntStorage to fix memory leak in EnumConstantDecl. (#78311)"
This reverts commit 4737959d91fab7673b1bb642f88658bb2a24d723.

Missed an lldb update.
2024-01-16 12:39:47 -08:00
Craig Topper
4737959d91
[AST] Use APIntStorage to fix memory leak in EnumConstantDecl. (#78311)
EnumConstantDecl is allocated by the ASTContext allocator so the
destructor is never called.

This patch takes a similar approach to IntegerLiteral by using
APIntStorage to allocate large APSInts using the ASTContext allocator as
well.

The downside is that an additional heap allocation and copy of the data
needs to be made when calling getInitValue if the APSInt is large.

Fixes #78160.
2024-01-16 12:10:38 -08:00
Rashmi Mudduluru
a511c1a9ec
Revert "[Clang] Implement the 'counted_by' attribute (#76348)"
This reverts commit 164f85db876e61cf4a3c34493ed11e8f5820f968.
2024-01-15 18:37:52 -08:00
Sander de Smalen
8e7f073eb4
[Clang][AArch64] Change SME attributes for shared/new/preserved state. (#76971)
This patch replaces the `__arm_new_za`, `__arm_shared_za` and
`__arm_preserves_za` attributes in favour of:
* `__arm_new("za")`
* `__arm_in("za")`
* `__arm_out("za")`
* `__arm_inout("za")`
* `__arm_preserves("za")`

As described in https://github.com/ARM-software/acle/pull/276.

One change is that `__arm_in/out/inout/preserves(S)` are all mutually
exclusive, whereas previously it was fine to write `__arm_shared_za
__arm_preserves_za`. This case is now represented with `__arm_in("za")`.

The current implementation uses the same LLVM attributes under the hood,
since `__arm_in/out/inout` are all variations of "shared ZA", so can use
the existing `aarch64_pstate_za_shared` attribute in LLVM.

#77941 will add support for the new "zt0" state as introduced
with SME2.
2024-01-15 09:41:32 +00:00
Bill Wendling
164f85db87 [Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-10 22:20:31 -08:00
Nico Weber
2dce77201c Revert "[Clang] Implement the 'counted_by' attribute (#76348)"
This reverts commit fefdef808c230c79dca2eb504490ad0f17a765a5.

Breaks check-clang, see
https://github.com/llvm/llvm-project/pull/76348#issuecomment-1886029515

Also revert follow-on "[Clang] Update 'counted_by' documentation"

This reverts commit 4a3fb9ce27dda17e97341f28005a28836c909cfc.
2024-01-10 21:05:19 -05:00
Bill Wendling
fefdef808c
[Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-10 15:21:10 -08:00
Krystian Stasiowski
640ef55bbb
Reapply "[Clang][Sema] Diagnose unexpanded packs in the template argument lists of function template specializations" (#76876) (#76915)
This reapplies f034044ad94d6f7ccec13d89f08acac257ed28bb after it was
reverted by 687396b5f4ba0713d103ebd172b308e92eb930cc due to a test
failure in clang-doc.

The test in question declares a partial specialization of a function
template, as well as an explicit specialization of the same function
template. Both declarations are now set as invalid, meaning neither is
emitted by clang-doc.

Since this is the sole test of function template specializations in
clang-doc, I presume the intent is for the partial specialization to
actually be the primary template. Doing so results in the expected
output.
2024-01-04 17:30:48 +01:00
Erich Keane
3f2e670671
Revert "[Clang][Sema] Diagnose unexpanded packs in the template argument lists of function template specializations" (#76876)
Reverts llvm/llvm-project#76677

See discussion here: https://github.com/llvm/llvm-project/pull/76677
2024-01-03 15:16:08 -08:00
Krystian Stasiowski
7fbc1de989
[Clang][Sema] Diagnose unexpanded packs in the template argument lists of function template specializations (#76677)
This diagnoses unexpanded packs in the _unqualified-id_ of a function
template specialization's _declarator-id_. For example:
```cpp
template<typename... Ts>
struct A
{
    template<typename U>
    void f();

    template<>
    void f<Ts>(); // error: explicit specialization contains unexpanded parameter pack 'Ts'
};
```

I moved the handling of template-id's so it happens right after we
determine whether we are declaring a function template/function template
specialization so diagnostics are issued in lexical order.
2024-01-03 11:07:46 -08:00
Utkarsh Saxena
aba40fb34a
[coroutines] Do not check coroutine wrappers for skipped function bodies (#76729)
Without function bodies, we cannot tell whether a function is a
coroutine or not.
The analysis of coroutine wrappers is not useful when this information
is not available.

We therefore now skip this analysis for skipped function bodies.
2024-01-03 12:41:10 +01:00
Haojian Wu
32aa7d823c
[clang] Fix CTAD not work for C++ explicit type conversion (functional annotation). (#75779)
This fixes https://github.com/llvm/llvm-project/issues/64347.

The CTAD for an aggregate class is missing to handle the explicit type
conversion case, e.g. `TemplateFooClass(1, 2);`. Per C++ expr.type.conv
p1, the deduced type is the return type of the deduction guide selected
by the CTAD for the reminder.

In the deduction implementation
`DeduceTemplateSpecializationFromInitializer`, the parenthesized
express-list case relies on the `ParenListExpr` parameter (default is
nullptr), the AST `ParenListExpr` node is not built for all variant
initializer cases (`BuildCXXTypeConstructorExpr`, `BuildCXXNew` etc),
thus the deduction doesn't perform for these cases. This patch fixes it
by removing the `ParenListExpr` and using the `Inits` instead (which
also simplifies the interface and implementation).
2023-12-19 14:35:37 +01:00