aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Sema/SemaDecl.cpp
AgeCommit message (Collapse)AuthorFilesLines
2024-03-29[Clang] [Sema] No longer diagnose type definitions in `offsetof` in C23 mode ↵Sirraide1-1/+3
(#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[NFC] [Decl] Introduce Decl::isFromExplicitGlobalModuleChuanqi Xu1-1/+1
Introduce `Decl::isFromExplicitGlobalModule` to replace the `D->getOwningModule() && D->getOwningModule()->isExplicitGlobalModule()` pattern to save some typings.
2024-03-29Revert "Reapply "[clang][nullability] allow _Nonnull etc on nullable class ↵dyung1-3/+1
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-28Reapply "[clang][nullability] allow _Nonnull etc on nullable class types ↵Sam McCall1-1/+3
(#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-27[Clang][Sema] Allow flexible arrays in unions and alone in structs (#84428)Kees Cook1-6/+2
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[clang][RISCV] Enable RVV with function attribute ↵Brandon Wu1-2/+7
__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-26[NFC] Refactor ConstantArrayType size storage (#85716)Chris B1-1/+1
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[clang] Fix -Wunused-variable in SemaDecl.cpp (NFC)Jie Fu1-1/+1
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[FMV] Allow mixing target_version with target_clones. (#86493)Alexandros Lamprineas1-63/+127
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-25[FMV] Allow multi versioning without default declaration. (#85454)Alexandros Lamprineas1-3/+3
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-21[clang] Accept lambdas in C++03 as an extensions (#73376)Nikolas Klauser1-1/+1
Implements https://discourse.llvm.org/t/rfc-allow-c-11-lambdas-in-c-03-as-an-extension/75262
2024-03-20Turn 'counted_by' into a type attribute and parse it into ↵Yeoul Na1-6/+0
'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-15Revert "[clang][nullability] allow _Nonnull etc on nullable class types ↵Sam McCall1-3/+1
(#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-14[clang][nullability] allow _Nonnull etc on nullable class types (#82705)Sam McCall1-1/+3
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[concepts] Preserve the FoundDecl of ConceptReference properly (#85032)Younan Zhang1-1/+5
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-08Revert "[Clang][Sema] Fix crash when using name of UnresolvedUsingValueDecl ↵Krystian Stasiowski1-4/+1
with template arguments (#83842)" (#84457) This reverts commit a642eb89bdaf10c6b4994fc1187de27b441236ed (see #83842)
2024-03-08[clang] Error on explicit specialization of lambda call operator (#84343)Mariya Podchishchaeva1-7/+15
Fixes https://github.com/llvm/llvm-project/issues/83267
2024-03-07[clang-repl] Names declared in if conditions and for-init statements are ↵Stefan Gränitz1-3/+13
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-06[FMV] Allow target version definitions in any order. (#83887)Alexandros Lamprineas1-3/+12
This patch fixes #71698. It allows defining the default target version prior to other version definitions without raising semantic errors.
2024-03-06[C23] Implement N3018: The constexpr specifier for object definitions (#73099)Mariya Podchishchaeva1-13/+66
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-05[Clang][Sema] Fix crash when using name of UnresolvedUsingValueDecl with ↵Krystian Stasiowski1-1/+4
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-04Reapply "[Clang][Sema] Diagnose function/variable templates that shadow ↵Krystian Stasiowski1-12/+19
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-01[Clang][Sema]: Allow copy constructor side effects (#81127)Vinayak Dev1-1/+2
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-02-26[APINotes] Upstream Sema logic to apply API Notes to declsEgor Zhdan1-0/+4
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-20[Clang][Sema] Diagnose declarative nested-name-specifiers naming alias ↵Krystian Stasiowski1-10/+26
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[C23] No longer assert on huge enumerator values (#81760)Aaron Ballman1-2/+7
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-15[clang] Fix two gcc warnings about unused variables [NFC]Mikael Holmen1-1/+1
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-14[clang][NFC] Use "notable" for "interesting" identifiers in `IdentifierInfo` ↵Vlad Serebrennikov1-7/+7
(#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-13[attributes][analyzer] Generalize [[clang::suppress]] to declarations. (#80371)Artem Dergachev1-0/+3
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[Clang][Sema] Diagnose friend declarations with enum ↵Krystian Stasiowski1-0/+20
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-12[clang][NFC] Refactor `Sema::TemplateDeductionResult` (#81398)Vlad Serebrennikov1-1/+2
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[clang] Avoid -Wshadow warning when init-capture named same as class field ↵Mariya Podchishchaeva1-26/+47
(#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-08[Clang][Sema] Abbreviated function templates do not append invented ↵Krystian Stasiowski1-1/+1
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-06[Clang][Sema] Implement proposed resolution for CWG2847 (#80899)Krystian Stasiowski1-49/+54
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-02[Clang][Sema] Diagnose use of template keyword after declarative ↵Krystian Stasiowski1-10/+39
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[Clang][Sema] Correctly look up primary template for variable template ↵Krystian Stasiowski1-5/+6
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-01-31[clang][NFC] Move isSimpleTypeSpecifier() from Sema to Token (#80101)Owen Pan1-45/+0
So that it can be used by clang-format.
2024-01-30[clang] Improved isSimpleTypeSpecifier (#79037)Carl Peto1-15/+10
- 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[Clang][Sema] Allow elaborated-type-specifiers that declare member class ↵Krystian Stasiowski1-23/+23
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-30Fix analyzer crash on 'StructuralValue' (#79764)Andrey Ali Khan Bolshakov1-1/+2
`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-27[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)cor3ntin1-0/+1
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-23[Clang] Amend SME attributes with support for ZT0. (#77941)Sander de Smalen1-0/+11
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-22Revert "[Clang][Sema] Diagnose function/variable templates that shadow their ↵Corentin Jabot1-6/+6
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-20Warning for incorrect use of 'pure' attribute (#78200)kelbon1-0/+28
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-18[Clang][NFC] Rename CXXMethodDecl::isPure -> is VirtualPure (#78463)cor3ntin1-4/+5
To avoid any possible confusion with the notion of pure function and the gnu::pure attribute.
2024-01-18[coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures ↵Utkarsh Saxena1-3/+16
(#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-17Add Variadic 'dropAttrs' (#78476)Erich Keane1-2/+1
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[Clang][Sema] Diagnose function/variable templates that shadow their own ↵Krystian Stasiowski1-6/+6
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[APINotes] Upstream dependencies of Sema logic to apply API Notes to declsEgor Zhdan1-0/+31
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[clang][AST] Invalidate DecompositionDecl if it has invalid initializer. ↵Haojian Wu1-0/+9
(#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.