aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Sema/SemaTemplateVariadic.cpp
AgeCommit message (Collapse)AuthorFilesLines
2025-08-20[Sema] Fix a warningKazu Hirata1-0/+1
This patch fixes: clang/lib/Sema/SemaTemplateVariadic.cpp:1069:22: error: variable 'TST' set but not used [-Werror,-Wunused-but-set-variable]
2025-08-20[Clang] Add a builtin that deduplicate types into a pack (#106730)Ilya Biryukov1-4/+117
The new builtin `__builtin_dedup_pack` removes duplicates from list of types. The added builtin is special in that they produce an unexpanded pack in the spirit of P3115R0 proposal. Produced packs can be used directly in template argument lists and get immediately expanded as soon as results of the computation are available. It allows to easily combine them, e.g.: ```cpp template <class ...T> struct Normalize { // Note: sort is not included in this PR, it illustrates the idea. using result = std::tuple< __builtin_sort_pack< __builtin_dedup_pack<int, double, T...>... >...>; } ; ``` Limitations: - only supported in template arguments and bases, - can only be used inside the templates, even if non-dependent, - the builtins cannot be assigned to template template parameters. The actual implementation proceeds as follows: - When the compiler encounters a `__builtin_dedup_pack` or other type-producing builtin with dependent arguments, it creates a dependent `TemplateSpecializationType`. - During substitution, if the template arguments are non-dependent, we will produce: a new type `SubstBuiltinTemplatePackType`, which stores an argument pack that needs to be substituted. This type is similar to the existing `SubstTemplateParmPack` in that it carries the argument pack that needs to be expanded further. The relevant code is shared. - On top of that, Clang also wraps the resulting type into `TemplateSpecializationType`, but this time only as a sugar. - To actually expand those packs, we collect the produced `SubstBuiltinTemplatePackType` inside `CollectUnexpandedPacks`. Because we know the size of the produces packs only after the initial substitution, places that do the actual expansion will need to have a second run over the substituted type to finalize the expansions (in this patch we only support this for template arguments, see `ExpandTemplateArgument`). If the expansion are requested in the places we do not currently support, we will produce an error. More follow-up work will be needed to fully shape this: - adding the builtin that sorts types, - remove the restrictions for expansions, - implementing P3115R0 (scheduled for C++29, see https://github.com/cplusplus/papers/issues/2300).
2025-08-09[clang] Improve nested name specifier AST representation (#147835)Matheus Izvekov1-18/+21
This is a major change on how we represent nested name qualifications in the AST. * The nested name specifier itself and how it's stored is changed. The prefixes for types are handled within the type hierarchy, which makes canonicalization for them super cheap, no memory allocation required. Also translating a type into nested name specifier form becomes a no-op. An identifier is stored as a DependentNameType. The nested name specifier gains a lightweight handle class, to be used instead of passing around pointers, which is similar to what is implemented for TemplateName. There is still one free bit available, and this handle can be used within a PointerUnion and PointerIntPair, which should keep bit-packing aficionados happy. * The ElaboratedType node is removed, all type nodes in which it could previously apply to can now store the elaborated keyword and name qualifier, tail allocating when present. * TagTypes can now point to the exact declaration found when producing these, as opposed to the previous situation of there only existing one TagType per entity. This increases the amount of type sugar retained, and can have several applications, for example in tracking module ownership, and other tools which care about source file origins, such as IWYU. These TagTypes are lazily allocated, in order to limit the increase in AST size. This patch offers a great performance benefit. It greatly improves compilation time for [stdexec](https://github.com/NVIDIA/stdexec). For one datapoint, for `test_on2.cpp` in that project, which is the slowest compiling test, this patch improves `-c` compilation time by about 7.2%, with the `-fsyntax-only` improvement being at ~12%. This has great results on compile-time-tracker as well: ![image](https://github.com/user-attachments/assets/700dce98-2cab-4aa8-97d1-b038c0bee831) This patch also further enables other optimziations in the future, and will reduce the performance impact of template specialization resugaring when that lands. It has some other miscelaneous drive-by fixes. About the review: Yes the patch is huge, sorry about that. Part of the reason is that I started by the nested name specifier part, before the ElaboratedType part, but that had a huge performance downside, as ElaboratedType is a big performance hog. I didn't have the steam to go back and change the patch after the fact. There is also a lot of internal API changes, and it made sense to remove ElaboratedType in one go, versus removing it from one type at a time, as that would present much more churn to the users. Also, the nested name specifier having a different API avoids missing changes related to how prefixes work now, which could make existing code compile but not work. How to review: The important changes are all in `clang/include/clang/AST` and `clang/lib/AST`, with also important changes in `clang/lib/Sema/TreeTransform.h`. The rest and bulk of the changes are mostly consequences of the changes in API. PS: TagType::getDecl is renamed to `getOriginalDecl` in this patch, just for easier to rebasing. I plan to rename it back after this lands. Fixes #136624 Fixes https://github.com/llvm/llvm-project/issues/43179 Fixes https://github.com/llvm/llvm-project/issues/68670 Fixes https://github.com/llvm/llvm-project/issues/92757
2025-08-04[Clang] Initial support for P2841 (Variable template and concept template ↵Corentin Jabot1-0/+10
parameters) (#150823) This is a first pass at implementing [P2841R7](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2841r7.pdf). The implementation is far from complete; however, I'm aiming to do that in chunks, to make our lives easier. In particular, this does not implement - Subsumption - Mangling - Satisfaction checking is minimal as we should focus on #141776 first (note that I'm currently very stuck) FTM, release notes, status page, etc, will be updated once the feature is more mature. Given the state of the feature, it is not yet allowed in older language modes. Of note: - Mismatches between template template arguments and template template parameters are a bit wonky. This is addressed by #130603 - We use `UnresolvedLookupExpr` to model template-id. While this is pre-existing, I have been wondering if we want to introduce a different OverloadExpr subclass for that. I did not make the change in this patch.
2025-08-02[clang][diagnostics] Fix fix-it hint parenthesis placement for fold ↵Iris Shi1-1/+2
expressions (#151790) - Closes #151787 Insert the right parenthesis one token later to correctly enclose the expression. --------- Co-authored-by: Corentin Jabot <corentinjabot@gmail.com>
2025-06-13Remove delayed typo expressions (#143423)Aaron Ballman1-11/+1
This removes the delayed typo correction functionality from Clang (regular typo correction still remains) due to fragility of the solution. An RFC was posted here: https://discourse.llvm.org/t/rfc-removing-support-for-delayed-typo-correction/86631 and while that RFC was asking for folks to consider stepping up to be maintainers, and we did have a few new contributors show some interest, experiments show that it's likely worth it to remove this functionality entirely and focus efforts on improving regular typo correction. This removal fixes ~20 open issues (quite possibly more), improves compile time performance by roughly .3-.4% (https://llvm-compile-time-tracker.com/?config=Overview&stat=instructions%3Au&remote=AaronBallman&sortBy=date), and does not appear to regress diagnostic behavior in a way we wouldn't find acceptable. Fixes #142457 Fixes #139913 Fixes #138850 Fixes #137867 Fixes #137860 Fixes #107840 Fixes #93308 Fixes #69470 Fixes #59391 Fixes #58172 Fixes #46215 Fixes #45915 Fixes #45891 Fixes #44490 Fixes #36703 Fixes #32903 Fixes #23312 Fixes #69874
2025-05-02[clang][NFC] Convert `Sema::CCEKind` to scoped enumVlad Serebrennikov1-1/+1
2025-05-02[clang][NFC] Convert `Sema::CorrectTypoKind` to scoped enumVlad Serebrennikov1-1/+1
2025-04-28[clang][NFC] Convert LookupResultKind to scoped enumVlad Serebrennikov1-6/+6
2025-04-27[clang] Use range constructors of *Set (NFC) (#137574)Kazu Hirata1-1/+1
2025-04-17Reland [clang] Unify `SourceLocation` and `IdentifierInfo*` pair-like data ↵yronglin1-5/+5
structures to `IdentifierLoc` (#136077) This PR reland https://github.com/llvm/llvm-project/pull/135808, fixed some missed changes in LLDB. I found this issue when I working on https://github.com/llvm/llvm-project/pull/107168. Currently we have many similiar data structures like: - std::pair<IdentifierInfo *, SourceLocation>. - Element type of ModuleIdPath. - IdentifierLocPair. - IdentifierLoc. This PR unify these data structures to IdentifierLoc, moved IdentifierLoc definition to SourceLocation.h, and deleted other similer data structures. --------- Signed-off-by: yronglin <yronglin777@gmail.com>
2025-04-16Revert "[clang] Unify `SourceLocation` and `IdentifierInfo*` pair-like data ↵Michael Buch1-5/+5
structures to `IdentifierLoc`" (#135974) Reverts llvm/llvm-project#135808 Example from the LLDB macOS CI: https://green.lab.llvm.org/job/llvm.org/view/LLDB/job/as-lldb-cmake/24084/execution/node/54/log/?consoleFull ``` /Users/ec2-user/jenkins/workspace/llvm.org/as-lldb-cmake/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp:360:49: error: no viable conversion from 'std::pair<clang::IdentifierInfo *, clang::SourceLocation>' to 'clang::ModuleIdPath' (aka 'ArrayRef<IdentifierLoc>') clang::Module *top_level_module = DoGetModule(clang_path.front(), false); ^~~~~~~~~~~~~~~~~~ /Users/ec2-user/jenkins/workspace/llvm.org/as-lldb-cmake/llvm-project/llvm/include/llvm/ADT/ArrayRef.h:41:40: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'std::pair<clang::IdentifierInfo *, clang::SourceLocation>' to 'const llvm::ArrayRef<clang::IdentifierLoc> &' for 1st argument class LLVM_GSL_POINTER [[nodiscard]] ArrayRef { ^ /Users/ec2-user/jenkins/workspace/llvm.org/as-lldb-cmake/llvm-project/llvm/include/llvm/ADT/ArrayRef.h:41:40: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'std::pair<clang::IdentifierInfo *, clang::SourceLocation>' to 'llvm::ArrayRef<clang::IdentifierLoc> &&' for 1st argument /Users/ec2-user/jenkins/workspace/llvm.org/as-lldb-cmake/llvm-project/llvm/include/llvm/ADT/ArrayRef.h:70:18: note: candidate constructor not viable: no known conversion from 'std::pair<clang::IdentifierInfo *, clang::SourceLocation>' to 'std::nullopt_t' for 1st argument /*implicit*/ ArrayRef(std::nullopt_t) {} ```
2025-04-16[clang] Unify `SourceLocation` and `IdentifierInfo*` pair-like data ↵yronglin1-5/+5
structures to `IdentifierLoc` (#135808) I found this issue when I working on https://github.com/llvm/llvm-project/pull/107168. Currently we have many similiar data structures like: - `std::pair<IdentifierInfo *, SourceLocation>`. - Element type of `ModuleIdPath`. - `IdentifierLocPair`. - `IdentifierLoc`. This PR unify these data structures to `IdentifierLoc`, moved `IdentifierLoc` definition to SourceLocation.h, and deleted other similer data structures. --------- Signed-off-by: yronglin <yronglin777@gmail.com>
2025-04-12Reland: [clang] Improved canonicalization for template specialization types ↵Matheus Izvekov1-1/+2
(#135414) This relands https://github.com/llvm/llvm-project/pull/135119, after fixing crashes seen in LLDB CI reported here: https://github.com/llvm/llvm-project/pull/135119#issuecomment-2794910840 Fixes https://github.com/llvm/llvm-project/pull/135119 This changes the TemplateArgument representation to hold a flag indicating whether a tempalte argument of expression type is supposed to be canonical or not. This gets one step closer to solving https://github.com/llvm/llvm-project/issues/92292 This still doesn't try to unique as-written TSTs. While this would increase the amount of memory savings and make code dealing with the AST more well-behaved, profiling template argument lists is still too expensive for this to be worthwhile, at least for now. This also fixes the context creation of TSTs, so that they don't in some cases get incorrectly flagged as sugar over their own canonical form. This is captured in the test expectation change of some AST dumps. This fixes some places which were unnecessarily canonicalizing these TSTs.
2025-04-11Revert "[clang] Improved canonicalization for template specialization types" ↵Dmitry Vasilyev1-2/+1
(#135354) Reverts llvm/llvm-project#135119 because of the assert in ASTContext.cpp, line 5619. See #135352 for details.
2025-04-10[clang] Improved canonicalization for template specialization types (#135119)Matheus Izvekov1-1/+2
This changes the TemplateArgument representation to hold a flag indicating whether a template argument of expression type is supposed to be canonical or not. This gets one step closer to solving https://github.com/llvm/llvm-project/issues/92292 This still doesn't try to unique as-written TSTs. While this would increase the amount of memory savings and make code dealing with the AST more well-behaved, profiling template argument lists is still too expensive for this to be worthwhile, at least for now. Without this uniquing, this patch stands neutral in terms of performance impact. This also fixes the context creation of TSTs, so that they don't in some cases get incorrectly flagged as sugar over their own canonical form. This is captured in the test expectation change of some AST dumps. This fixes some places which were unnecessarily canonicalizing these TSTs.
2025-04-07[clang] fix diagnostic printing of expressions ignoring LangOpts (#134693)Matheus Izvekov1-1/+1
Currently when printing a template argument of expression type, the expression is converted immediately into a string to be sent to the diagnostic engine, unsing a fake LangOpts. This makes the expression printing look incorrect for the current language, besides being inneficient, as we don't actually need to print the expression if the diagnostic would be ignored. This fixes a nastiness with the TemplateArgument constructor for expressions being implicit, and all current users just passing an expression to a diagnostic were implicitly going through the template argument path. The expressions are also being printed unquoted. This will be fixed in a subsequent patch, as the test churn is much larger.
2025-04-07[clang] fix partial ordering of NTTP packs (#134461)Matheus Izvekov1-2/+1
This fixes partial ordering of pack expansions of NTTPs, by procedding with the check using the pattern of the NTTP through the rules of the non-pack case. This also unifies almost all of the different versions of FinishTemplateArgumentDeduction (except the function template case). This makes sure they all follow the rules consistently, instantiating the parameters and comparing those with the argument. Fixes #132562
2025-04-03[clang] NFC: introduce UnsignedOrNone as a replacement for ↵Matheus Izvekov1-13/+13
std::optional<unsigned> (#134142) This introduces a new class 'UnsignedOrNone', which models a lite version of `std::optional<unsigned>`, but has the same size as 'unsigned'. This replaces most uses of `std::optional<unsigned>`, and similar schemes utilizing 'int' and '-1' as sentinel. Besides the smaller size advantage, this is simpler to serialize, as its internal representation is a single unsigned int as well.
2025-03-06[Clang][NFC] Change uses of getAs() to castAs() where the target type is ↵Tom Honermann1-1/+1
assured. (#130188) Static analysis identified two uses of `getAs()` for which the result pointer was unconditionally dereferenced. Source code inspection confirmed that the target type is assured by prior checks. This change replaces these uses of `getAs()` with `castAs()`. The first case, in `clang/lib/CodeGen/Targets/AArch64.cpp`, performs a cast to `BuiltinType` following a check for `isBuiltinType()`. The second case, in `clang/lib/Sema/SemaTemplateVariadic.cpp`, performs a cast to `PackExpansionType` on the result of a call to `getAsType()` on an object of type `TemplateArgument` following confirmation that `isPackExpansion()` returned true and that `getKind()` returned `TemplateArgument::Type`. Inspection of `isPackExpansion()` revealed that it only returns true when the template argument kind is `TemplateArgument::Type` if `isa<PackExpansionType>(getAsType())` is true.
2025-02-18[Clang][P1061] Consolidate ResolvedUnpexandedPackExpr into ↵Jason Rice1-38/+10
FunctionParmPackExpr (#125394) This merges the functionality of ResolvedUnexpandedPackExpr into FunctionParmPackExpr. I also added a test to show that https://github.com/llvm/llvm-project/issues/125103 should be fixed with this. I put the removal of ResolvedUnexpandedPackExpr in its own commit. Let me know what you think. Fixes #125103
2025-01-29[Clang][P1061] Add stuctured binding packs (#121417)Jason Rice1-8/+52
This is an implementation of P1061 Structure Bindings Introduce a Pack without the ability to use packs outside of templates. There is a couple of ways the AST could have been sliced so let me know what you think. The only part of this change that I am unsure of is the serialization/deserialization stuff. I followed the implementation of other Exprs, but I do not really know how it is tested. Thank you for your time considering this. --------- Co-authored-by: Yanzuo Liu <zwuis@outlook.com>
2024-12-19[Clang] Don't assume unexpanded PackExpansions' size when expanding packs ↵Younan Zhang1-6/+51
(#120380) CheckParameterPacksForExpansion() previously assumed that template arguments don't include PackExpansion types when attempting another pack expansion (i.e. when NumExpansions is present). However, this assumption doesn't hold for type aliases, whose substitution might involve unexpanded packs. This can lead to incorrect diagnostics during substitution because the pack size is not yet determined. To address this, this patch calculates the minimum pack size (ignoring unexpanded PackExpansionTypes) and compares it to the previously expanded size. If the minimum pack size is smaller, then there's still a chance for future substitution to expand it to a correct size, so we don't diagnose it too eagerly. Fixes #61415 Fixes #32252 Fixes #17042
2024-11-27[Sema] Migrate away from PointerUnion::{is,get} (NFC) (#117498)Kazu Hirata1-10/+10
Note that PointerUnion::{is,get} have been soft deprecated in PointerUnion.h: // FIXME: Replace the uses of is(), get() and dyn_cast() with // isa<T>, cast<T> and the llvm::dyn_cast<T> I'm not touching PointerUnion::dyn_cast for now because it's a bit complicated; we could blindly migrate it to dyn_cast_if_present, but we should probably use dyn_cast when the operand is known to be non-null.
2024-11-25[Clang] Preserve partially substituted pack indexing type/expressions (#116782)Younan Zhang1-7/+9
Substituting into pack indexing types/expressions can still result in unexpanded types/expressions, such as `PackIndexingType` or `PackIndexingExpr`. To handle these cases correctly, we should defer the pack size checks to the next round of transformation, when the patterns can be fully expanded. To that end, the `FullySubstituted` flag is now necessary for computing the dependencies of `PackIndexingExprs`. Conveniently, this flag can also represent the prior `ExpandsToEmpty` status with an additional emptiness check. Therefore, I converted all stored flags to use `FullySubstituted`. Fixes https://github.com/llvm/llvm-project/issues/116105
2024-11-15[Clang] [NFC] Refactor AST visitors in Sema and the static analyser to use ↵Sirraide1-66/+73
DynamicRecursiveASTVisitor (#115144) This pr refactors all recursive AST visitors in `Sema`, `Analyze`, and `StaticAnalysis` to inherit from DRAV instead. This is over half of the visitors that inherit from RAV directly. See also #115132, #110040, #93462 LLVM Compile-Time Tracker link for this branch: https://llvm-compile-time-tracker.com/compare.php?from=5adb5c05a2e9f31385fbba8b0436cbc07d91a44d&to=b58e589a86c06ba28d4d90613864d10be29aa5ba&stat=instructions%3Au
2024-10-22[Clang] Don't assert on substituted-but-yet-expanded packs for nested ↵Younan Zhang1-15/+34
lambdas (#112896) Nested lambdas could refer to outer packs that would be expanded by a larger CXXFoldExpr, in which case that reference could happen to be a full expression containing intermediate types/expressions, e.g. SubstTemplateTypeParmPackType/FunctionParmPackExpr. They are designated as "UnexpandedPack" dependencies but don't introduce new packs anyway. This also handles a missed case for VarDecls, where the flag of ContainsUnexpandedPack was not propagated up to the surrounding lambda. Fixes #112352
2024-10-11[Clang] [Sema] Don't crash on unexpanded pack in invalid block literal (#110762)Sirraide1-16/+26
Consider #109148: ```c++ template <typename ...Ts> void f() { [] { (^Ts); }; } ``` When we encounter `^Ts`, we try to parse a block and subsequently call `DiagnoseUnexpandedParameterPack()` (in `ActOnBlockArguments()`), which sees `Ts` and sets `ContainsUnexpandedParameterPack` to `true` in the `LambdaScopeInfo` of the enclosing lambda. However, the entire block is subsequently discarded entirely because it isn’t even syntactically well-formed. As a result, `ContainsUnexpandedParameterPack` is `true` despite the lambda’s body no longer containing any unexpanded packs, which causes an assertion the next time `DiagnoseUnexpandedParameterPack()` is called. This pr moves handling of unexpanded parameter packs into `CapturingScopeInfo` instead so that the same logic is used for both blocks and lambdas. This fixes this issue since the `ContainsUnexpandedParameterPack` flag is now part of the block (and before that, its `CapturingScopeInfo`) and no longer affects the surrounding lambda directly when the block is parsed. Moreover, this change makes blocks actually usable with pack expansion. This fixes #109148.
2024-09-09[Clang] Don't assert non-empty packs for FunctionParmPackExprs (#107561)Younan Zhang1-9/+29
`FunctionParmPackExpr`s are peculiar in that they have to be of unexpanded dependency while they don't introduce any unexpanded packs. So this patch rules them out in the non-empty pack assertion in `DiagnoseUnexpandedParameterPack()`. There was a fix #69224, but that turned out to be insufficient. I also moved the separate tests to a pre-existing file. Fixes https://github.com/llvm/llvm-project/issues/86361
2024-08-09[Clang] Fix Handling of Init Capture with Parameter Packs in ↵Yupei Liu1-6/+11
LambdaScopeForCallOperatorInstantiationRAII (#100766) This PR addresses issues related to the handling of `init capture` with parameter packs in Clang's `LambdaScopeForCallOperatorInstantiationRAII`. Previously, `addInstantiatedCapturesToScope` would add `init capture` containing packs to the scope using the type of the `init capture` to determine the expanded pack size. However, this approach resulted in a pack size of 0 because `getType()->containsUnexpandedParameterPack()` returns `false`. After extensive testing, it appears that the correct pack size can only be inferred from `getInit`. But `getInit` may reference parameters and `init capture` from an outer lambda, as shown in the following example: ```cpp auto L = [](auto... z) { return [... w = z](auto... y) { // ... }; }; ``` To address this, `addInstantiatedCapturesToScope` in `LambdaScopeForCallOperatorInstantiationRAII` should be called last. Additionally, `addInstantiatedCapturesToScope` has been modified to only add `init capture` to the scope. The previous implementation incorrectly called `MakeInstantiatedLocalArgPack` for other non-init captures containing packs, resulting in a pack size of 0. ### Impact This patch affects scenarios where `LambdaScopeForCallOperatorInstantiationRAII` is passed with `ShouldAddDeclsFromParentScope = false`, preventing the correct addition of the current lambda's `init capture` to the scope. There are two main scenarios for `ShouldAddDeclsFromParentScope = false`: 1. **Constraints**: Sometimes constraints are instantiated in place rather than delayed. In this case, `LambdaScopeForCallOperatorInstantiationRAII` does not need to add `init capture` to the scope. 2. **`noexcept` Expressions**: The expressions inside `noexcept` have already been transformed, and the packs referenced within have been expanded. Only `RebuildLambdaInfo` needs to add the expanded captures to the scope, without requiring `addInstantiatedCapturesToScope` from `LambdaScopeForCallOperatorInstantiationRAII`. ### Considerations An alternative approach could involve adding a data structure within the lambda to record the expanded size of the `init capture` pack. However, this would increase the lambda's size and require extensive modifications. This PR is a prerequisite for implmenting https://github.com/llvm/llvm-project/issues/61426
2024-08-05[HLSL] Implement intangible AST type (#97362)Helena Kotas1-0/+2
HLSL has a set of intangible types which are described in in the [draft HLSL Specification (**[Basic.types]**)](https://microsoft.github.io/hlsl-specs/specs/hlsl.pdf): There are special implementation-defined types such as handle types, which fall into a category of standard intangible types. Intangible types are types that have no defined object representation or value representation, as such the size is unknown at compile time. A class type T is an intangible class type if it contains an base classes or members of intangible class type, standard intangible type, or arrays of such types. Standard intangible types and intangible class types are collectively called intangible types([9](https://microsoft.github.io/hlsl-specs/specs/hlsl.html#Intangible)). This PR implements one standard intangible type `__hlsl_resource_t` and sets up the infrastructure that will make it easier to add more in the future, such as samplers or raytracing payload handles. The HLSL intangible types are declared in `clang/include/clang/Basic/HLSLIntangibleTypes.def` and this file is included with related macro definition in most places that require edits when a new type is added. The new types are added as keywords and not typedefs to make sure they cannot be redeclared, and they can only be declared in builtin implicit headers. The `__hlsl_resource_t` type represents a handle to a memory resource and it is going to be used in builtin HLSL buffer types like this: template <typename T> class RWBuffer { [[hlsl::contained_type(T)]] [[hlsl::is_rov(false)]] [[hlsl::resource_class(uav)]] __hlsl_resource_t Handle; }; Part 1/3 of llvm/llvm-project#90631. --------- Co-authored-by: Justin Bogner <mail@justinbogner.com>
2024-07-17Reapply [Clang][C++26] Implement "Ordering of constraints involving fold ↵cor3ntin1-0/+4
expressions (#99022) Implement https://isocpp.org/files/papers/P2963R3.pdf
2024-07-16Revert "[Clang][C++26] Implement "Ordering of constraints involving fold ↵cor3ntin1-4/+0
expressions" (#99007) Reverts llvm/llvm-project#98160 Breaks CI on some architectures
2024-07-16[Clang][C++26] Implement "Ordering of constraints involving fold expressions ↵cor3ntin1-0/+4
(#98160) Implement https://isocpp.org/files/papers/P2963R3.pdf
2024-07-01[clang][NFC] Move documentation of `Sema` functions into `Sema.h`Vlad Serebrennikov1-14/+0
This patch moves documentation of `Sema` functions from `.cpp` files to `Sema.h` when there was no documentation in the latter, or it can be trivially subsumed. More complicated cases when there's less trivial divergence between documentation attached to declaration and the one attached to implementation are left for a later PR that would require review. It appears that doxygen can find the documentation for a function defined out-of-line even if it's attached to an implementation, and not declaration. But other tools, e.g. clangd, are not as powerful. So this patch significantly improves autocompletion experience for (at least) clangd-based IDEs.
2024-05-27[Clang] [Sema] Diagnose unexpanded parameter packs in attributes (#93482)Sirraide1-0/+3
Call `DiagnoseUnexpandedParameterPack` when we parse an expression argument to an attribute and check for implicit code in the `CollectUnexpandedParameterPacksVisitor` so we can actually find unexpanded packs in attributes that end up applied to lambda call operators. This fixes #93269.
2024-05-21[Clang][Sema] Avoid pack expansion for expanded empty PackIndexingExprs (#92385)Younan Zhang1-1/+1
We previously doubled the id-expression expansion, even when the pack was expanded to empty. The previous condition for determining whether we should expand couldn't distinguish between cases where 'the expansion was previously postponed' and 'the expansion occurred but resulted in emptiness.' In the latter scenario, we crash because we have not been examining the current lambda's parent local instantiation scope since [D98068](https://reviews.llvm.org/D98068): Any Decls instantiated in the parent scope are not visible to the generic lambda, and thus any attempt of looking for instantiated Decls in the lambda is capped to the current Lambda's LIS. Fixes https://github.com/llvm/llvm-project/issues/92230
2024-04-21[Clang] Do not try to diagnose parameter packs in invalid pack expressions ↵cor3ntin1-3/+5
(#89257) In a pack expression, if the id-expression is not valid, do no try to detect whether it is a pack as that would lead to a crash trying to print a recovery expression. Fixes #88929
2024-04-10[clang][Sema] Avoid guessing unexpanded packs' size in ↵Younan Zhang1-0/+11
getFullyPackExpandedSize (#87768) There has been an optimization for `SizeOfPackExprs` since c5452ed9, in which we overlooked a case where the template arguments were not yet formed into a `PackExpansionType` at the token annotation stage. This led to a problem in that a template involving such expressions may lose its nature of being dependent, causing some false-positive diagnostics. Fixes https://github.com/llvm/llvm-project/issues/84220
2024-01-27[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)cor3ntin1-2/+70
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-21[c++20] P1907R1: Support for generalized non-type template arguments of ↵Andrey Ali Khan Bolshakov1-0/+2
scalar type. (#78041) Previously committed as 9e08e51a20d0d2b1c5724bb17e969d036fced4cd, and reverted because a dependency commit was reverted, then committed again as 4b574008aef5a7235c1f894ab065fe300d26e786 and reverted again because "dependency commit" 5a391d38ac6c561ba908334d427f26124ed9132e was reverted. But it doesn't seem that 5a391d38ac6c was a real dependency for this. This commit incorporates 4b574008aef5a7235c1f894ab065fe300d26e786 and 18e093faf726d15f210ab4917142beec51848258 by Richard Smith (@zygoloid), with some minor fixes, most notably: - `UncommonValue` renamed to `StructuralValue` - `VK_PRValue` instead of `VK_RValue` as default kind in lvalue and member pointer handling branch in `BuildExpressionFromNonTypeTemplateArgumentValue`; - handling of `StructuralValue` in `IsTypeDeclaredInsideVisitor`; - filling in `SugaredConverted` along with `CanonicalConverted` parameter in `Sema::CheckTemplateArgument`; - minor cleanup in `TemplateInstantiator::transformNonTypeTemplateParmRef`; - `TemplateArgument` constructors refactored; - `ODRHash` calculation for `UncommonValue`; - USR generation for `UncommonValue`; - more correct MS compatibility mangling algorithm (tested on MSVC ver. 19.35; toolset ver. 143); - IR emitting fixed on using a subobject as a template argument when the corresponding template parameter is used in an lvalue context; - `noundef` attribute and opaque pointers in `template-arguments` test; - analysis for C++17 mode is turned off for templates in `warn-bool-conversion` test; in C++17 and C++20 mode, array reference used as a template argument of pointer type produces template argument of UncommonValue type, and `BuildExpressionFromNonTypeTemplateArgumentValue` makes `OpaqueValueExpr` for it, and `DiagnoseAlwaysNonNullPointer` cannot see through it; despite of "These cases should not warn" comment, I'm not sure about correct behavior; I'd expect a suggestion to replace `if` by `if constexpr`; - `temp.arg.nontype/p1.cpp` and `dr18xx.cpp` tests fixed.
2023-11-13[clang][Sema] Avoid non-empty unexpanded pack assertion for ↵Younan Zhang1-0/+7
FunctionParmPackExpr (#69224) Closes https://github.com/llvm/llvm-project/issues/61460. We have FunctionParmPackExpr that serves as the unexpanded expression but from which the visitor collects none, which may lead to assertion failure during the template instantiation.
2023-03-15[SemaCXX]use CorrectDelayedTyposInExpr in ActOnCXXFoldExpr only when DiagCongcong Cai1-2/+3
PR #61326 - fix clang crash when fold expression contains a delayed typos correction. code snippet in `ActOnCXXFoldExpr` ``` if (!LHS || !RHS) { Expr *Pack = LHS ? LHS : RHS; assert(Pack && "fold expression with neither LHS nor RHS"); DiscardOperands(); if (!Pack->containsUnexpandedParameterPack()) return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) << Pack->getSourceRange(); } ``` `DiscardOperands` will be triggered when LHS/RHS is delayed typo correction expression. It will output and clean all diagnose but still return a valid expression. (in else branch) valid expression will be handled in caller function. When caller wants to output the diagnose, the diagnose in delayed typo correction expression has been consumed in `ActOnCXXFoldExpr`. It causes clang crash. Reviewed By: erichkeane Differential Revision: https://reviews.llvm.org/D145892
2023-03-09Revert two patches to fix GH58452 regressionErich Keane1-120/+114
GH58452 is a regression in the 16.0 release branch caused by both: b8a1b698afb2fc84819c7596090aabf4d826b436 and 3a0309c53674be56b5cfce038d78a0c2c6e2a98c This patch reverts both of those to make the 'valid' code stop diagnosing at the expense of crashes on invalid + unclear diagnostics. This patch also adds the tests from GH58452 to prevent any re-application from breaking this again. Revert "[clang] Improve diagnostics for expansion length mismatch" This reverts commit 3a0309c53674be56b5cfce038d78a0c2c6e2a98c. Revert "[clang] fix missing initialization of original number of expansions" This reverts commit b8a1b698afb2fc84819c7596090aabf4d826b436. Differential Revision: https://reviews.llvm.org/D145605
2023-01-14[clang] Use std::optional instead of llvm::Optional (NFC)Kazu Hirata1-16/+15
This patch replaces (llvm::|)Optional< with std::optional<. I'll post a separate patch to remove #include "llvm/ADT/Optional.h". This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2023-01-14[clang] Add #include <optional> (NFC)Kazu Hirata1-0/+1
This patch adds #include <optional> to those files containing llvm::Optional<...> or Optional<...>. I'll post a separate patch to actually replace llvm::Optional with std::optional. This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-12-03[Sema] Use std::nullopt instead of None (NFC)Kazu Hirata1-12/+13
This patch mechanically replaces None with std::nullopt where the compiler would warn if None were deprecated. The intent is to reduce the amount of manual work required in migrating from Optional to std::optional. This is part of an effort to migrate from llvm::Optional to std::optional: https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-10-15[clang] Track the templated entity in type substitution.Matheus Izvekov1-1/+1
This is a change to how we represent type subsitution in the AST. Instead of only storing the replaced type, we track the templated entity we are substituting, plus an index. We modify MLTAL to track the templated entity at each level. Otherwise, it's much more expensive to go from the template parameter back to the templated entity, and not possible to do in some cases, as when we instantiate outer templates, parameters might still reference the original entity. This also allows us to very cheaply lookup the templated entity we saw in the naming context and find the corresponding argument it was replaced from, such as for implementing template specialization resugaring. Signed-off-by: Matheus Izvekov <mizvekov@gmail.com> Differential Revision: https://reviews.llvm.org/D131858
2022-09-28[C2x] implement typeof and typeof_unqualAaron Ballman1-0/+2
This implements WG14 N2927 and WG14 N2930, which together define the feature for typeof and typeof_unqual, which get the type of their argument as either fully qualified or fully unqualified. The argument to either operator is either a type name or an expression. If given a type name, the type information is pulled directly from the given name. If given an expression, the type information is pulled from the expression. Recursive use of these operators is allowed and has the expected behavior (the innermost operator is resolved to a type, and that's used to resolve the next layer of typeof specifier, until a fully resolved type is determined. Note, we already supported typeof in GNU mode as a non-conforming extension and we are *not* exposing typeof_unqual as a non-conforming extension in that mode, nor are we exposing typeof or typeof_unqual as a nonconforming extension in other language modes. The GNU variant of typeof supports a form where the parentheses are elided from the operator when given an expression (e.g., typeof 0 i = 12;). When in C2x mode, we do not support this extension. Differential Revision: https://reviews.llvm.org/D134286
2022-08-30[clang] Improve diagnostics for expansion length mismatchMatheus Izvekov1-114/+120
When checking parameter packs for expansion, instead of basing the diagnostic for length mismatch for outer parameters only on the known number of expansions, we should also analyze SubstTemplateTypeParmPackType and SubstNonTypeTemplateParmPackExpr for unexpanded packs, so we can emit a diagnostic pointing to a concrete outer parameter. Signed-off-by: Matheus Izvekov <mizvekov@gmail.com> Differential Revision: https://reviews.llvm.org/D128095