Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/Template.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
146 return D;
147
148 return nullptr;
149}
150
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
242 if (isa<FunctionTemplateDecl>(FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
281 } else {
282 if (!D) {
284 assert(D && "unambiguous result is not a template name");
285 }
286
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
300 Template);
301 }
302
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
308 } else {
312 TemplateKind =
314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
318 }
319 }
320
322 S->getTemplateParamParent() == nullptr)
323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(Template);
328 return TemplateKind;
329}
330
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
352 if (!TD || !getAsTypeTemplateDecl(TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
358 *Template = TemplateTy::make(Name);
359 }
360 return true;
361}
362
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(IILoc, diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(IILoc, "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
391 bool AllowTypoCorrection) {
392 if (ATK)
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()
412 ->getOriginalDecl()
413 ->isEntityBeingDefined()) &&
414 "Caller should have completed object type");
415
416 // Template names cannot appear inside an Objective-C class or object type
417 // or a vector type.
418 //
419 // FIXME: This is wrong. For example:
420 //
421 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
422 // Vec<int> vi;
423 // vi.Vec<int>::~Vec<int>();
424 //
425 // ... should be accepted but we will not treat 'Vec' as a template name
426 // here. The right thing to do would be to check if the name is a valid
427 // vector component name, and look up a template name if not. And similarly
428 // for lookups into Objective-C class and object types, where the same
429 // problem can arise.
430 if (ObjectType->isObjCObjectOrInterfaceType() ||
431 ObjectType->isVectorType()) {
432 Found.clear();
433 return false;
434 }
435 } else if (SS.isNotEmpty()) {
436 // This nested-name-specifier occurs after another nested-name-specifier,
437 // so long into the context associated with the prior nested-name-specifier.
438 LookupCtx = computeDeclContext(SS, EnteringContext);
439 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
440
441 // The declaration context must be complete.
442 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
443 return true;
444 }
445
446 bool ObjectTypeSearchedInScope = false;
447 bool AllowFunctionTemplatesInLookup = true;
448 if (LookupCtx) {
449 // Perform "qualified" name lookup into the declaration context we
450 // computed, which is either the type of the base of a member access
451 // expression or the declaration context associated with a prior
452 // nested-name-specifier.
453 LookupQualifiedName(Found, LookupCtx);
454
455 // FIXME: The C++ standard does not clearly specify what happens in the
456 // case where the object type is dependent, and implementations vary. In
457 // Clang, we treat a name after a . or -> as a template-name if lookup
458 // finds a non-dependent member or member of the current instantiation that
459 // is a type template, or finds no such members and lookup in the context
460 // of the postfix-expression finds a type template. In the latter case, the
461 // name is nonetheless dependent, and we may resolve it to a member of an
462 // unknown specialization when we come to instantiate the template.
463 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
464 }
465
466 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
467 // C++ [basic.lookup.classref]p1:
468 // In a class member access expression (5.2.5), if the . or -> token is
469 // immediately followed by an identifier followed by a <, the
470 // identifier must be looked up to determine whether the < is the
471 // beginning of a template argument list (14.2) or a less-than operator.
472 // The identifier is first looked up in the class of the object
473 // expression. If the identifier is not found, it is then looked up in
474 // the context of the entire postfix-expression and shall name a class
475 // template.
476 if (S)
477 LookupName(Found, S);
478
479 if (!ObjectType.isNull()) {
480 // FIXME: We should filter out all non-type templates here, particularly
481 // variable templates and concepts. But the exclusion of alias templates
482 // and template template parameters is a wording defect.
483 AllowFunctionTemplatesInLookup = false;
484 ObjectTypeSearchedInScope = true;
485 }
486
487 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
488 }
489
490 if (Found.isAmbiguous())
491 return false;
492
493 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
494 !RequiredTemplate.hasTemplateKeyword()) {
495 // C++2a [temp.names]p2:
496 // A name is also considered to refer to a template if it is an
497 // unqualified-id followed by a < and name lookup finds either one or more
498 // functions or finds nothing.
499 //
500 // To keep our behavior consistent, we apply the "finds nothing" part in
501 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
502 // successfully form a call to an undeclared template-id.
503 bool AllFunctions =
504 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
506 });
507 if (AllFunctions || (Found.empty() && !IsDependent)) {
508 // If lookup found any functions, or if this is a name that can only be
509 // used for a function, then strongly assume this is a function
510 // template-id.
511 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
514 Found.clear();
515 return false;
516 }
517 }
518
519 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
520 // If we did not find any names, and this is not a disambiguation, attempt
521 // to correct any typos.
522 DeclarationName Name = Found.getLookupName();
523 Found.clear();
524 // Simple filter callback that, for keywords, only accepts the C++ *_cast
525 DefaultFilterCCC FilterCCC{};
526 FilterCCC.WantTypeSpecifiers = false;
527 FilterCCC.WantExpressionKeywords = false;
528 FilterCCC.WantRemainingKeywords = false;
529 FilterCCC.WantCXXNamedCasts = true;
530 if (TypoCorrection Corrected = CorrectTypo(
531 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
532 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
533 if (auto *ND = Corrected.getFoundDecl())
534 Found.addDecl(ND);
536 if (Found.isAmbiguous()) {
537 Found.clear();
538 } else if (!Found.empty()) {
539 // Do not erase the typo-corrected result to avoid duplicated
540 // diagnostics.
541 AllowFunctionTemplatesInLookup = true;
542 Found.setLookupName(Corrected.getCorrection());
543 if (LookupCtx) {
544 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
545 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
546 Name.getAsString() == CorrectedStr;
547 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
548 << Name << LookupCtx << DroppedSpecifier
549 << SS.getRange());
550 } else {
551 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
552 }
553 }
554 }
555 }
556
557 NamedDecl *ExampleLookupResult =
558 Found.empty() ? nullptr : Found.getRepresentativeDecl();
559 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
560 if (Found.empty()) {
561 if (IsDependent) {
562 Found.setNotFoundInCurrentInstantiation();
563 return false;
564 }
565
566 // If a 'template' keyword was used, a lookup that finds only non-template
567 // names is an error.
568 if (ExampleLookupResult && RequiredTemplate) {
569 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
570 << Found.getLookupName() << SS.getRange()
571 << RequiredTemplate.hasTemplateKeyword()
572 << RequiredTemplate.getTemplateKeywordLoc();
573 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
574 diag::note_template_kw_refers_to_non_template)
575 << Found.getLookupName();
576 return true;
577 }
578
579 return false;
580 }
581
582 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
584 // C++03 [basic.lookup.classref]p1:
585 // [...] If the lookup in the class of the object expression finds a
586 // template, the name is also looked up in the context of the entire
587 // postfix-expression and [...]
588 //
589 // Note: C++11 does not perform this second lookup.
590 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
592 FoundOuter.setTemplateNameLookup(true);
593 LookupName(FoundOuter, S);
594 // FIXME: We silently accept an ambiguous lookup here, in violation of
595 // [basic.lookup]/1.
596 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
597
598 NamedDecl *OuterTemplate;
599 if (FoundOuter.empty()) {
600 // - if the name is not found, the name found in the class of the
601 // object expression is used, otherwise
602 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
603 !(OuterTemplate =
604 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
605 // - if the name is found in the context of the entire
606 // postfix-expression and does not name a class template, the name
607 // found in the class of the object expression is used, otherwise
608 FoundOuter.clear();
609 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
610 // - if the name found is a class template, it must refer to the same
611 // entity as the one found in the class of the object expression,
612 // otherwise the program is ill-formed.
613 if (!Found.isSingleResult() ||
614 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
615 OuterTemplate->getCanonicalDecl()) {
616 Diag(Found.getNameLoc(),
617 diag::ext_nested_name_member_ref_lookup_ambiguous)
618 << Found.getLookupName()
619 << ObjectType;
620 Diag(Found.getRepresentativeDecl()->getLocation(),
621 diag::note_ambig_member_ref_object_type)
622 << ObjectType;
623 Diag(FoundOuter.getFoundDecl()->getLocation(),
624 diag::note_ambig_member_ref_scope);
625
626 // Recover by taking the template that we found in the object
627 // expression's type.
628 }
629 }
630 }
631
632 return false;
633}
634
638 if (TemplateName.isInvalid())
639 return;
640
641 DeclarationNameInfo NameInfo;
642 CXXScopeSpec SS;
643 LookupNameKind LookupKind;
644
645 DeclContext *LookupCtx = nullptr;
646 NamedDecl *Found = nullptr;
647 bool MissingTemplateKeyword = false;
648
649 // Figure out what name we looked up.
650 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
651 NameInfo = DRE->getNameInfo();
652 SS.Adopt(DRE->getQualifierLoc());
653 LookupKind = LookupOrdinaryName;
654 Found = DRE->getFoundDecl();
655 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
656 NameInfo = ME->getMemberNameInfo();
657 SS.Adopt(ME->getQualifierLoc());
658 LookupKind = LookupMemberName;
659 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
660 Found = ME->getMemberDecl();
661 } else if (auto *DSDRE =
662 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
663 NameInfo = DSDRE->getNameInfo();
664 SS.Adopt(DSDRE->getQualifierLoc());
665 MissingTemplateKeyword = true;
666 } else if (auto *DSME =
667 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
668 NameInfo = DSME->getMemberNameInfo();
669 SS.Adopt(DSME->getQualifierLoc());
670 MissingTemplateKeyword = true;
671 } else {
672 llvm_unreachable("unexpected kind of potential template name");
673 }
674
675 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
676 // was missing.
677 if (MissingTemplateKeyword) {
678 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
679 << NameInfo.getName() << SourceRange(Less, Greater);
680 return;
681 }
682
683 // Try to correct the name by looking for templates and C++ named casts.
684 struct TemplateCandidateFilter : CorrectionCandidateCallback {
685 Sema &S;
686 TemplateCandidateFilter(Sema &S) : S(S) {
687 WantTypeSpecifiers = false;
688 WantExpressionKeywords = false;
689 WantRemainingKeywords = false;
690 WantCXXNamedCasts = true;
691 };
692 bool ValidateCandidate(const TypoCorrection &Candidate) override {
693 if (auto *ND = Candidate.getCorrectionDecl())
694 return S.getAsTemplateNameDecl(ND);
695 return Candidate.isKeyword();
696 }
697
698 std::unique_ptr<CorrectionCandidateCallback> clone() override {
699 return std::make_unique<TemplateCandidateFilter>(*this);
700 }
701 };
702
703 DeclarationName Name = NameInfo.getName();
704 TemplateCandidateFilter CCC(*this);
705 if (TypoCorrection Corrected =
706 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
707 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
708 auto *ND = Corrected.getFoundDecl();
709 if (ND)
710 ND = getAsTemplateNameDecl(ND);
711 if (ND || Corrected.isKeyword()) {
712 if (LookupCtx) {
713 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
714 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
715 Name.getAsString() == CorrectedStr;
716 diagnoseTypo(Corrected,
717 PDiag(diag::err_non_template_in_member_template_id_suggest)
718 << Name << LookupCtx << DroppedSpecifier
719 << SS.getRange(), false);
720 } else {
721 diagnoseTypo(Corrected,
722 PDiag(diag::err_non_template_in_template_id_suggest)
723 << Name, false);
724 }
725 if (Found)
726 Diag(Found->getLocation(),
727 diag::note_non_template_in_template_id_found);
728 return;
729 }
730 }
731
732 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
733 << Name << SourceRange(Less, Greater);
734 if (Found)
735 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
736}
737
740 SourceLocation TemplateKWLoc,
741 const DeclarationNameInfo &NameInfo,
742 bool isAddressOfOperand,
743 const TemplateArgumentListInfo *TemplateArgs) {
744 if (SS.isEmpty()) {
745 // FIXME: This codepath is only used by dependent unqualified names
746 // (e.g. a dependent conversion-function-id, or operator= once we support
747 // it). It doesn't quite do the right thing, and it will silently fail if
748 // getCurrentThisType() returns null.
749 QualType ThisType = getCurrentThisType();
750 if (ThisType.isNull())
751 return ExprError();
752
754 Context, /*Base=*/nullptr, ThisType,
755 /*IsArrow=*/!Context.getLangOpts().HLSL,
756 /*OperatorLoc=*/SourceLocation(),
757 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
758 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
759 }
760 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
761}
762
765 SourceLocation TemplateKWLoc,
766 const DeclarationNameInfo &NameInfo,
767 const TemplateArgumentListInfo *TemplateArgs) {
768 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
769 if (!SS.isValid())
770 return CreateRecoveryExpr(
771 SS.getBeginLoc(),
772 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
773
775 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
776 TemplateArgs);
777}
778
780 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
782 bool Final) {
783 // The template argument itself might be an expression, in which case we just
784 // return that expression. This happens when substituting into an alias
785 // template.
786 Expr *Replacement;
787 bool refParam = true;
789 Replacement = Arg.getAsExpr();
790 refParam = Replacement->isLValue();
791 if (refParam && Replacement->getType()->isRecordType()) {
792 QualType ParamType =
794 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
795 : NTTP->getType();
796 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))
797 ParamType = PET->getPattern();
798 refParam = ParamType->isReferenceType();
799 }
800 } else {
801 ExprResult result =
802 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
803 if (result.isInvalid())
804 return ExprError();
805 Replacement = result.get();
807 }
808 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
809 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
810 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
811}
812
814 NamedDecl *Instantiation,
815 bool InstantiatedFromMember,
816 const NamedDecl *Pattern,
817 const NamedDecl *PatternDef,
819 bool Complain, bool *Unreachable) {
820 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
821 isa<VarDecl>(Instantiation));
822
823 bool IsEntityBeingDefined = false;
824 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
825 IsEntityBeingDefined = TD->isBeingDefined();
826
827 if (PatternDef && !IsEntityBeingDefined) {
828 NamedDecl *SuggestedDef = nullptr;
829 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
830 &SuggestedDef,
831 /*OnlyNeedComplete*/ false)) {
832 if (Unreachable)
833 *Unreachable = true;
834 // If we're allowed to diagnose this and recover, do so.
835 bool Recover = Complain && !isSFINAEContext();
836 if (Complain)
837 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
839 return !Recover;
840 }
841 return false;
842 }
843
844 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
845 return true;
846
847 CanQualType InstantiationTy;
848 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
849 InstantiationTy = Context.getCanonicalTagType(TD);
850 if (PatternDef) {
851 Diag(PointOfInstantiation,
852 diag::err_template_instantiate_within_definition)
853 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
854 << InstantiationTy;
855 // Not much point in noting the template declaration here, since
856 // we're lexically inside it.
857 Instantiation->setInvalidDecl();
858 } else if (InstantiatedFromMember) {
859 if (isa<FunctionDecl>(Instantiation)) {
860 Diag(PointOfInstantiation,
861 diag::err_explicit_instantiation_undefined_member)
862 << /*member function*/ 1 << Instantiation->getDeclName()
863 << Instantiation->getDeclContext();
864 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
865 } else {
866 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
867 Diag(PointOfInstantiation,
868 diag::err_implicit_instantiate_member_undefined)
869 << InstantiationTy;
870 Diag(Pattern->getLocation(), diag::note_member_declared_at);
871 }
872 } else {
873 if (isa<FunctionDecl>(Instantiation)) {
874 Diag(PointOfInstantiation,
875 diag::err_explicit_instantiation_undefined_func_template)
876 << Pattern;
877 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
878 } else if (isa<TagDecl>(Instantiation)) {
879 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
880 << (TSK != TSK_ImplicitInstantiation)
881 << InstantiationTy;
882 NoteTemplateLocation(*Pattern);
883 } else {
884 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
885 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
886 Diag(PointOfInstantiation,
887 diag::err_explicit_instantiation_undefined_var_template)
888 << Instantiation;
889 Instantiation->setInvalidDecl();
890 } else
891 Diag(PointOfInstantiation,
892 diag::err_explicit_instantiation_undefined_member)
893 << /*static data member*/ 2 << Instantiation->getDeclName()
894 << Instantiation->getDeclContext();
895 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
896 }
897 }
898
899 // In general, Instantiation isn't marked invalid to get more than one
900 // error for multiple undefined instantiations. But the code that does
901 // explicit declaration -> explicit definition conversion can't handle
902 // invalid declarations, so mark as invalid in that case.
904 Instantiation->setInvalidDecl();
905 return true;
906}
907
909 bool SupportedForCompatibility) {
910 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
911
912 // C++23 [temp.local]p6:
913 // The name of a template-parameter shall not be bound to any following.
914 // declaration whose locus is contained by the scope to which the
915 // template-parameter belongs.
916 //
917 // When MSVC compatibility is enabled, the diagnostic is always a warning
918 // by default. Otherwise, it an error unless SupportedForCompatibility is
919 // true, in which case it is a default-to-error warning.
920 unsigned DiagId =
921 getLangOpts().MSVCCompat
922 ? diag::ext_template_param_shadow
923 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
924 : diag::err_template_param_shadow);
925 const auto *ND = cast<NamedDecl>(PrevDecl);
926 Diag(Loc, DiagId) << ND->getDeclName();
928}
929
931 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
932 D = Temp->getTemplatedDecl();
933 return Temp;
934 }
935 return nullptr;
936}
937
939 SourceLocation EllipsisLoc) const {
940 assert(Kind == Template &&
941 "Only template template arguments can be pack expansions here");
942 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
943 "Template template argument pack expansion without packs");
945 Result.EllipsisLoc = EllipsisLoc;
946 return Result;
947}
948
950 const ParsedTemplateArgument &Arg) {
951
952 switch (Arg.getKind()) {
954 TypeSourceInfo *DI;
955 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
956 if (!DI)
957 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
959 }
960
962 Expr *E = Arg.getAsExpr();
963 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
964 }
965
968 TemplateArgument TArg;
969 if (Arg.getEllipsisLoc().isValid())
970 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
971 else
972 TArg = Template;
973 return TemplateArgumentLoc(
974 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
976 Arg.getNameLoc(), Arg.getEllipsisLoc());
977 }
978 }
979
980 llvm_unreachable("Unhandled parsed template argument");
981}
982
984 TemplateArgumentListInfo &TemplateArgs) {
985 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
986 TemplateArgs.addArgument(translateTemplateArgument(*this,
987 TemplateArgsIn[I]));
988}
989
991 SourceLocation Loc,
992 const IdentifierInfo *Name) {
993 NamedDecl *PrevDecl =
994 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
996 if (PrevDecl && PrevDecl->isTemplateParameter())
997 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
998}
999
1001 TypeSourceInfo *TInfo;
1002 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1003 if (T.isNull())
1004 return ParsedTemplateArgument();
1005 assert(TInfo && "template argument with no location");
1006
1007 // If we might have formed a deduced template specialization type, convert
1008 // it to a template template argument.
1009 if (getLangOpts().CPlusPlus17) {
1010 TypeLoc TL = TInfo->getTypeLoc();
1011 SourceLocation EllipsisLoc;
1012 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1013 EllipsisLoc = PET.getEllipsisLoc();
1014 TL = PET.getPatternLoc();
1015 }
1016
1017 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1018 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1019 CXXScopeSpec SS;
1020 SS.Adopt(DTST.getQualifierLoc());
1021 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1022 TemplateTy::make(Name),
1023 DTST.getTemplateNameLoc());
1024 if (EllipsisLoc.isValid())
1025 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1026 return Result;
1027 }
1028 }
1029
1030 // This is a normal type template argument. Note, if the type template
1031 // argument is an injected-class-name for a template, it has a dual nature
1032 // and can be used as either a type or a template. We handle that in
1033 // convertTypeTemplateArgumentToTemplate.
1035 ParsedType.get().getAsOpaquePtr(),
1036 TInfo->getTypeLoc().getBeginLoc());
1037}
1038
1040 SourceLocation EllipsisLoc,
1041 SourceLocation KeyLoc,
1042 IdentifierInfo *ParamName,
1043 SourceLocation ParamNameLoc,
1044 unsigned Depth, unsigned Position,
1045 SourceLocation EqualLoc,
1046 ParsedType DefaultArg,
1047 bool HasTypeConstraint) {
1048 assert(S->isTemplateParamScope() &&
1049 "Template type parameter not in template parameter scope!");
1050
1051 bool IsParameterPack = EllipsisLoc.isValid();
1053 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1054 KeyLoc, ParamNameLoc, Depth, Position,
1055 ParamName, Typename, IsParameterPack,
1056 HasTypeConstraint);
1057 Param->setAccess(AS_public);
1058
1059 if (Param->isParameterPack())
1060 if (auto *CSI = getEnclosingLambdaOrBlock())
1061 CSI->LocalPacks.push_back(Param);
1062
1063 if (ParamName) {
1064 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1065
1066 // Add the template parameter into the current scope.
1067 S->AddDecl(Param);
1068 IdResolver.AddDecl(Param);
1069 }
1070
1071 // C++0x [temp.param]p9:
1072 // A default template-argument may be specified for any kind of
1073 // template-parameter that is not a template parameter pack.
1074 if (DefaultArg && IsParameterPack) {
1075 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1076 DefaultArg = nullptr;
1077 }
1078
1079 // Handle the default argument, if provided.
1080 if (DefaultArg) {
1081 TypeSourceInfo *DefaultTInfo;
1082 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1083
1084 assert(DefaultTInfo && "expected source information for type");
1085
1086 // Check for unexpanded parameter packs.
1087 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1089 return Param;
1090
1091 // Check the template argument itself.
1092 if (CheckTemplateArgument(DefaultTInfo)) {
1093 Param->setInvalidDecl();
1094 return Param;
1095 }
1096
1097 Param->setDefaultArgument(
1098 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1099 }
1100
1101 return Param;
1102}
1103
1104/// Convert the parser's template argument list representation into our form.
1107 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1108 TemplateId.RAngleLoc);
1109 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1110 TemplateId.NumArgs);
1111 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1112 return TemplateArgs;
1113}
1114
1116
1117 TemplateName TN = TypeConstr->Template.get();
1118 NamedDecl *CD = nullptr;
1119 bool IsTypeConcept = false;
1120 bool RequiresArguments = false;
1121 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1122 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1123 RequiresArguments =
1124 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1125 CD = TTP;
1126 } else {
1127 CD = TN.getAsTemplateDecl();
1128 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1129 RequiresArguments = cast<ConceptDecl>(CD)
1130 ->getTemplateParameters()
1131 ->getMinRequiredArguments() > 1;
1132 }
1133
1134 // C++2a [temp.param]p4:
1135 // [...] The concept designated by a type-constraint shall be a type
1136 // concept ([temp.concept]).
1137 if (!IsTypeConcept) {
1138 Diag(TypeConstr->TemplateNameLoc,
1139 diag::err_type_constraint_non_type_concept);
1140 return true;
1141 }
1142
1143 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1144 return true;
1145
1146 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1147
1148 if (!WereArgsSpecified && RequiresArguments) {
1149 Diag(TypeConstr->TemplateNameLoc,
1150 diag::err_type_constraint_missing_arguments)
1151 << CD;
1152 return true;
1153 }
1154 return false;
1155}
1156
1158 TemplateIdAnnotation *TypeConstr,
1159 TemplateTypeParmDecl *ConstrainedParameter,
1160 SourceLocation EllipsisLoc) {
1161 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1162 false);
1163}
1164
1166 TemplateIdAnnotation *TypeConstr,
1167 TemplateTypeParmDecl *ConstrainedParameter,
1168 SourceLocation EllipsisLoc,
1169 bool AllowUnexpandedPack) {
1170
1171 if (CheckTypeConstraint(TypeConstr))
1172 return true;
1173
1174 TemplateName TN = TypeConstr->Template.get();
1177
1178 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1179 TypeConstr->TemplateNameLoc);
1180
1181 TemplateArgumentListInfo TemplateArgs;
1182 if (TypeConstr->LAngleLoc.isValid()) {
1183 TemplateArgs =
1184 makeTemplateArgumentListInfo(*this, *TypeConstr);
1185
1186 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1187 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1189 return true;
1190 }
1191 }
1192 }
1193 return AttachTypeConstraint(
1195 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1196 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1197 ConstrainedParameter, EllipsisLoc);
1198}
1199
1200template <typename ArgumentLocAppender>
1203 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1204 SourceLocation RAngleLoc, QualType ConstrainedType,
1205 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1206 SourceLocation EllipsisLoc) {
1207
1208 TemplateArgumentListInfo ConstraintArgs;
1209 ConstraintArgs.addArgument(
1211 /*NTTPType=*/QualType(), ParamNameLoc));
1212
1213 ConstraintArgs.setRAngleLoc(RAngleLoc);
1214 ConstraintArgs.setLAngleLoc(LAngleLoc);
1215 Appender(ConstraintArgs);
1216
1217 // C++2a [temp.param]p4:
1218 // [...] This constraint-expression E is called the immediately-declared
1219 // constraint of T. [...]
1220 CXXScopeSpec SS;
1221 SS.Adopt(NS);
1222 ExprResult ImmediatelyDeclaredConstraint;
1223 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1224 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1225 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1226 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1227 /*DoCheckConstraintSatisfaction=*/
1229 }
1230 // We have a template template parameter
1231 else {
1232 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1233 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1234 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1235 }
1236 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1237 return ImmediatelyDeclaredConstraint;
1238
1239 // C++2a [temp.param]p4:
1240 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1241 //
1242 // We have the following case:
1243 //
1244 // template<typename T> concept C1 = true;
1245 // template<C1... T> struct s1;
1246 //
1247 // The constraint: (C1<T> && ...)
1248 //
1249 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1250 // any unqualified lookups for 'operator&&' here.
1251 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1252 /*LParenLoc=*/SourceLocation(),
1253 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1254 EllipsisLoc, /*RHS=*/nullptr,
1255 /*RParenLoc=*/SourceLocation(),
1256 /*NumExpansions=*/std::nullopt);
1257}
1258
1260 DeclarationNameInfo NameInfo,
1261 TemplateDecl *NamedConcept,
1262 NamedDecl *FoundDecl,
1263 const TemplateArgumentListInfo *TemplateArgs,
1264 TemplateTypeParmDecl *ConstrainedParameter,
1265 SourceLocation EllipsisLoc) {
1266 // C++2a [temp.param]p4:
1267 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1268 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1269 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1271 *TemplateArgs) : nullptr;
1272
1273 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1274
1275 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1276 *this, NS, NameInfo, NamedConcept, FoundDecl,
1277 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1278 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1279 ParamAsArgument, ConstrainedParameter->getLocation(),
1280 [&](TemplateArgumentListInfo &ConstraintArgs) {
1281 if (TemplateArgs)
1282 for (const auto &ArgLoc : TemplateArgs->arguments())
1283 ConstraintArgs.addArgument(ArgLoc);
1284 },
1285 EllipsisLoc);
1286 if (ImmediatelyDeclaredConstraint.isInvalid())
1287 return true;
1288
1289 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1290 /*TemplateKWLoc=*/SourceLocation{},
1291 /*ConceptNameInfo=*/NameInfo,
1292 /*FoundDecl=*/FoundDecl,
1293 /*NamedConcept=*/NamedConcept,
1294 /*ArgsWritten=*/ArgsAsWritten);
1295 ConstrainedParameter->setTypeConstraint(
1296 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1297 return false;
1298}
1299
1301 NonTypeTemplateParmDecl *NewConstrainedParm,
1302 NonTypeTemplateParmDecl *OrigConstrainedParm,
1303 SourceLocation EllipsisLoc) {
1304 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1306 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1307 diag::err_unsupported_placeholder_constraint)
1308 << NewConstrainedParm->getTypeSourceInfo()
1309 ->getTypeLoc()
1310 .getSourceRange();
1311 return true;
1312 }
1313 // FIXME: Concepts: This should be the type of the placeholder, but this is
1314 // unclear in the wording right now.
1315 DeclRefExpr *Ref =
1316 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1317 VK_PRValue, OrigConstrainedParm->getLocation());
1318 if (!Ref)
1319 return true;
1320 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1322 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1324 OrigConstrainedParm->getLocation(),
1325 [&](TemplateArgumentListInfo &ConstraintArgs) {
1326 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1327 ConstraintArgs.addArgument(TL.getArgLoc(I));
1328 },
1329 EllipsisLoc);
1330 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1331 !ImmediatelyDeclaredConstraint.isUsable())
1332 return true;
1333
1334 NewConstrainedParm->setPlaceholderTypeConstraint(
1335 ImmediatelyDeclaredConstraint.get());
1336 return false;
1337}
1338
1340 SourceLocation Loc) {
1341 if (TSI->getType()->isUndeducedType()) {
1342 // C++17 [temp.dep.expr]p3:
1343 // An id-expression is type-dependent if it contains
1344 // - an identifier associated by name lookup with a non-type
1345 // template-parameter declared with a type that contains a
1346 // placeholder type (7.1.7.4),
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1351}
1352
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(SubLoc, diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 // C++ [temp.param]p4:
1463 //
1464 // A non-type template-parameter shall have one of the following
1465 // (optionally cv-qualified) types:
1466 //
1467 // -- integral or enumeration type,
1468 if (T->isIntegralOrEnumerationType() ||
1469 // -- pointer to object or pointer to function,
1470 T->isPointerType() ||
1471 // -- lvalue reference to object or lvalue reference to function,
1472 T->isLValueReferenceType() ||
1473 // -- pointer to member,
1474 T->isMemberPointerType() ||
1475 // -- std::nullptr_t, or
1476 T->isNullPtrType() ||
1477 // -- a type that contains a placeholder type.
1478 T->isUndeducedType()) {
1479 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1480 // are ignored when determining its type.
1481 return T.getUnqualifiedType();
1482 }
1483
1484 // C++ [temp.param]p8:
1485 //
1486 // A non-type template-parameter of type "array of T" or
1487 // "function returning T" is adjusted to be of type "pointer to
1488 // T" or "pointer to function returning T", respectively.
1489 if (T->isArrayType() || T->isFunctionType())
1490 return Context.getDecayedType(T);
1491
1492 // If T is a dependent type, we can't do the check now, so we
1493 // assume that it is well-formed. Note that stripping off the
1494 // qualifiers here is not really correct if T turns out to be
1495 // an array type, but we'll recompute the type everywhere it's
1496 // used during instantiation, so that should be OK. (Using the
1497 // qualified type is equally wrong.)
1498 if (T->isDependentType())
1499 return T.getUnqualifiedType();
1500
1501 // C++20 [temp.param]p6:
1502 // -- a structural type
1503 if (RequireStructuralType(T, Loc))
1504 return QualType();
1505
1506 if (!getLangOpts().CPlusPlus20) {
1507 // FIXME: Consider allowing structural types as an extension in C++17. (In
1508 // earlier language modes, the template argument evaluation rules are too
1509 // inflexible.)
1510 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1511 return QualType();
1512 }
1513
1514 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1515 return T.getUnqualifiedType();
1516}
1517
1519 unsigned Depth,
1520 unsigned Position,
1521 SourceLocation EqualLoc,
1522 Expr *Default) {
1524
1525 // Check that we have valid decl-specifiers specified.
1526 auto CheckValidDeclSpecifiers = [this, &D] {
1527 // C++ [temp.param]
1528 // p1
1529 // template-parameter:
1530 // ...
1531 // parameter-declaration
1532 // p2
1533 // ... A storage class shall not be specified in a template-parameter
1534 // declaration.
1535 // [dcl.typedef]p1:
1536 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1537 // of a parameter-declaration
1538 const DeclSpec &DS = D.getDeclSpec();
1539 auto EmitDiag = [this](SourceLocation Loc) {
1540 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1542 };
1544 EmitDiag(DS.getStorageClassSpecLoc());
1545
1547 EmitDiag(DS.getThreadStorageClassSpecLoc());
1548
1549 // [dcl.inline]p1:
1550 // The inline specifier can be applied only to the declaration or
1551 // definition of a variable or function.
1552
1553 if (DS.isInlineSpecified())
1554 EmitDiag(DS.getInlineSpecLoc());
1555
1556 // [dcl.constexpr]p1:
1557 // The constexpr specifier shall be applied only to the definition of a
1558 // variable or variable template or the declaration of a function or
1559 // function template.
1560
1561 if (DS.hasConstexprSpecifier())
1562 EmitDiag(DS.getConstexprSpecLoc());
1563
1564 // [dcl.fct.spec]p1:
1565 // Function-specifiers can be used only in function declarations.
1566
1567 if (DS.isVirtualSpecified())
1568 EmitDiag(DS.getVirtualSpecLoc());
1569
1570 if (DS.hasExplicitSpecifier())
1571 EmitDiag(DS.getExplicitSpecLoc());
1572
1573 if (DS.isNoreturnSpecified())
1574 EmitDiag(DS.getNoreturnSpecLoc());
1575 };
1576
1577 CheckValidDeclSpecifiers();
1578
1579 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1580 if (isa<AutoType>(T))
1582 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1583 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1584
1585 assert(S->isTemplateParamScope() &&
1586 "Non-type template parameter not in template parameter scope!");
1587 bool Invalid = false;
1588
1590 if (T.isNull()) {
1591 T = Context.IntTy; // Recover with an 'int' type.
1592 Invalid = true;
1593 }
1594
1596
1597 const IdentifierInfo *ParamName = D.getIdentifier();
1598 bool IsParameterPack = D.hasEllipsis();
1600 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1601 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1602 TInfo);
1603 Param->setAccess(AS_public);
1604
1606 if (TL.isConstrained()) {
1607 if (D.getEllipsisLoc().isInvalid() &&
1608 T->containsUnexpandedParameterPack()) {
1609 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1610 for (auto &Loc :
1611 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1614 }
1615 if (!Invalid &&
1616 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1617 Invalid = true;
1618 }
1619
1620 if (Invalid)
1621 Param->setInvalidDecl();
1622
1623 if (Param->isParameterPack())
1624 if (auto *CSI = getEnclosingLambdaOrBlock())
1625 CSI->LocalPacks.push_back(Param);
1626
1627 if (ParamName) {
1629 ParamName);
1630
1631 // Add the template parameter into the current scope.
1632 S->AddDecl(Param);
1633 IdResolver.AddDecl(Param);
1634 }
1635
1636 // C++0x [temp.param]p9:
1637 // A default template-argument may be specified for any kind of
1638 // template-parameter that is not a template parameter pack.
1639 if (Default && IsParameterPack) {
1640 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1641 Default = nullptr;
1642 }
1643
1644 // Check the well-formedness of the default template argument, if provided.
1645 if (Default) {
1646 // Check for unexpanded parameter packs.
1648 return Param;
1649
1650 Param->setDefaultArgument(
1652 TemplateArgument(Default, /*IsCanonical=*/false),
1653 QualType(), SourceLocation()));
1654 }
1655
1656 return Param;
1657}
1658
1659/// ActOnTemplateTemplateParameter - Called when a C++ template template
1660/// parameter (e.g. T in template <template <typename> class T> class array)
1661/// has been parsed. S is the current scope.
1663 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1664 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1665 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1666 unsigned Position, SourceLocation EqualLoc,
1668 assert(S->isTemplateParamScope() &&
1669 "Template template parameter not in template parameter scope!");
1670
1671 bool IsParameterPack = EllipsisLoc.isValid();
1672
1673 bool Invalid = false;
1675 Params,
1676 /*OldParams=*/nullptr,
1677 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1678 Invalid = true;
1679
1680 // Construct the parameter object.
1682 Context, Context.getTranslationUnitDecl(),
1683 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1684 Name, Kind, Typename, Params);
1685 Param->setAccess(AS_public);
1686
1687 if (Param->isParameterPack())
1688 if (auto *LSI = getEnclosingLambdaOrBlock())
1689 LSI->LocalPacks.push_back(Param);
1690
1691 // If the template template parameter has a name, then link the identifier
1692 // into the scope and lookup mechanisms.
1693 if (Name) {
1694 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1695
1696 S->AddDecl(Param);
1697 IdResolver.AddDecl(Param);
1698 }
1699
1700 if (Params->size() == 0) {
1701 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1702 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1703 Invalid = true;
1704 }
1705
1706 if (Invalid)
1707 Param->setInvalidDecl();
1708
1709 // C++0x [temp.param]p9:
1710 // A default template-argument may be specified for any kind of
1711 // template-parameter that is not a template parameter pack.
1712 if (IsParameterPack && !Default.isInvalid()) {
1713 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1715 }
1716
1717 if (!Default.isInvalid()) {
1718 // Check only that we have a template template argument. We don't want to
1719 // try to check well-formedness now, because our template template parameter
1720 // might have dependent types in its template parameters, which we wouldn't
1721 // be able to match now.
1722 //
1723 // If none of the template template parameter's template arguments mention
1724 // other template parameters, we could actually perform more checking here.
1725 // However, it isn't worth doing.
1727 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1728 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1729 << DefaultArg.getSourceRange();
1730 return Param;
1731 }
1732
1733 TemplateName Name =
1736 if (Template &&
1738 return Param;
1739 }
1740
1741 // Check for unexpanded parameter packs.
1743 DefaultArg.getArgument().getAsTemplate(),
1745 return Param;
1746
1747 Param->setDefaultArgument(Context, DefaultArg);
1748 }
1749
1750 return Param;
1751}
1752
1753namespace {
1754class ConstraintRefersToContainingTemplateChecker
1756 using inherited = ConstDynamicRecursiveASTVisitor;
1757 bool Result = false;
1758 const FunctionDecl *Friend = nullptr;
1759 unsigned TemplateDepth = 0;
1760
1761 // Check a record-decl that we've seen to see if it is a lexical parent of the
1762 // Friend, likely because it was referred to without its template arguments.
1763 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1764 CheckingRD = CheckingRD->getMostRecentDecl();
1765 if (!CheckingRD->isTemplated())
1766 return true;
1767
1768 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1769 DC && !DC->isFileContext(); DC = DC->getParent())
1770 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1771 if (CheckingRD == RD->getMostRecentDecl()) {
1772 Result = true;
1773 return false;
1774 }
1775
1776 return true;
1777 }
1778
1779 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1780 if (D->getDepth() < TemplateDepth)
1781 Result = true;
1782
1783 // Necessary because the type of the NTTP might be what refers to the parent
1784 // constriant.
1785 return TraverseType(D->getType());
1786 }
1787
1788public:
1789 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1790 unsigned TemplateDepth)
1791 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1792
1793 bool getResult() const { return Result; }
1794
1795 // This should be the only template parm type that we have to deal with.
1796 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1797 // FunctionParmPackExpr are all partially substituted, which cannot happen
1798 // with concepts at this point in translation.
1799 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1800 if (Type->getDecl()->getDepth() < TemplateDepth) {
1801 Result = true;
1802 return false;
1803 }
1804 return true;
1805 }
1806
1807 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1808 return TraverseDecl(E->getDecl());
1809 }
1810
1811 bool TraverseTypedefType(const TypedefType *TT,
1812 bool /*TraverseQualifier*/) override {
1813 return TraverseType(TT->desugar());
1814 }
1815
1816 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1817 // We don't care about TypeLocs. So traverse Types instead.
1818 return TraverseType(TL.getType(), TraverseQualifier);
1819 }
1820
1821 bool VisitTagType(const TagType *T) override {
1822 return TraverseDecl(T->getOriginalDecl());
1823 }
1824
1825 bool TraverseDecl(const Decl *D) override {
1826 assert(D);
1827 // FIXME : This is possibly an incomplete list, but it is unclear what other
1828 // Decl kinds could be used to refer to the template parameters. This is a
1829 // best guess so far based on examples currently available, but the
1830 // unreachable should catch future instances/cases.
1831 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1832 return TraverseType(TD->getUnderlyingType());
1833 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1834 return CheckNonTypeTemplateParmDecl(NTTPD);
1835 if (auto *VD = dyn_cast<ValueDecl>(D))
1836 return TraverseType(VD->getType());
1837 if (isa<TemplateDecl>(D))
1838 return true;
1839 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1840 return CheckIfContainingRecord(RD);
1841
1843 // No direct types to visit here I believe.
1844 } else
1845 llvm_unreachable("Don't know how to handle this declaration type yet");
1846 return true;
1847 }
1848};
1849} // namespace
1850
1852 const FunctionDecl *Friend, unsigned TemplateDepth,
1853 const Expr *Constraint) {
1854 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1855 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1856 Checker.TraverseStmt(Constraint);
1857 return Checker.getResult();
1858}
1859
1862 SourceLocation ExportLoc,
1863 SourceLocation TemplateLoc,
1864 SourceLocation LAngleLoc,
1865 ArrayRef<NamedDecl *> Params,
1866 SourceLocation RAngleLoc,
1867 Expr *RequiresClause) {
1868 if (ExportLoc.isValid())
1869 Diag(ExportLoc, diag::warn_template_export_unsupported);
1870
1871 for (NamedDecl *P : Params)
1873
1874 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1875 llvm::ArrayRef(Params), RAngleLoc,
1876 RequiresClause);
1877}
1878
1880 const CXXScopeSpec &SS) {
1881 if (SS.isSet())
1882 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1883}
1884
1885// Returns the template parameter list with all default template argument
1886// information.
1888 // Make sure we get the template parameter list from the most
1889 // recent declaration, since that is the only one that is guaranteed to
1890 // have all the default template argument information.
1891 Decl *D = TD->getMostRecentDecl();
1892 // C++11 N3337 [temp.param]p12:
1893 // A default template argument shall not be specified in a friend class
1894 // template declaration.
1895 //
1896 // Skip past friend *declarations* because they are not supposed to contain
1897 // default template arguments. Moreover, these declarations may introduce
1898 // template parameters living in different template depths than the
1899 // corresponding template parameters in TD, causing unmatched constraint
1900 // substitution.
1901 //
1902 // FIXME: Diagnose such cases within a class template:
1903 // template <class T>
1904 // struct S {
1905 // template <class = void> friend struct C;
1906 // };
1907 // template struct S<int>;
1909 D->getPreviousDecl())
1910 D = D->getPreviousDecl();
1911 return cast<TemplateDecl>(D)->getTemplateParameters();
1912}
1913
1915 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1916 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1917 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1918 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1919 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1920 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1921 assert(TemplateParams && TemplateParams->size() > 0 &&
1922 "No template parameters");
1923 assert(TUK != TagUseKind::Reference &&
1924 "Can only declare or define class templates");
1925 bool Invalid = false;
1926
1927 // Check that we can declare a template here.
1928 if (CheckTemplateDeclScope(S, TemplateParams))
1929 return true;
1930
1932 assert(Kind != TagTypeKind::Enum &&
1933 "can't build template of enumerated type");
1934
1935 // There is no such thing as an unnamed class template.
1936 if (!Name) {
1937 Diag(KWLoc, diag::err_template_unnamed_class);
1938 return true;
1939 }
1940
1941 // Find any previous declaration with this name. For a friend with no
1942 // scope explicitly specified, we only look for tag declarations (per
1943 // C++11 [basic.lookup.elab]p2).
1944 DeclContext *SemanticContext;
1945 LookupResult Previous(*this, Name, NameLoc,
1946 (SS.isEmpty() && TUK == TagUseKind::Friend)
1950 if (SS.isNotEmpty() && !SS.isInvalid()) {
1951 SemanticContext = computeDeclContext(SS, true);
1952 if (!SemanticContext) {
1953 // FIXME: Horrible, horrible hack! We can't currently represent this
1954 // in the AST, and historically we have just ignored such friend
1955 // class templates, so don't complain here.
1956 Diag(NameLoc, TUK == TagUseKind::Friend
1957 ? diag::warn_template_qualified_friend_ignored
1958 : diag::err_template_qualified_declarator_no_match)
1959 << SS.getScopeRep() << SS.getRange();
1960 return TUK != TagUseKind::Friend;
1961 }
1962
1963 if (RequireCompleteDeclContext(SS, SemanticContext))
1964 return true;
1965
1966 // If we're adding a template to a dependent context, we may need to
1967 // rebuilding some of the types used within the template parameter list,
1968 // now that we know what the current instantiation is.
1969 if (SemanticContext->isDependentContext()) {
1970 ContextRAII SavedContext(*this, SemanticContext);
1972 Invalid = true;
1973 }
1974
1975 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1976 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1977 /*TemplateId-*/ nullptr,
1978 /*IsMemberSpecialization*/ false);
1979
1980 LookupQualifiedName(Previous, SemanticContext);
1981 } else {
1982 SemanticContext = CurContext;
1983
1984 // C++14 [class.mem]p14:
1985 // If T is the name of a class, then each of the following shall have a
1986 // name different from T:
1987 // -- every member template of class T
1988 if (TUK != TagUseKind::Friend &&
1989 DiagnoseClassNameShadow(SemanticContext,
1990 DeclarationNameInfo(Name, NameLoc)))
1991 return true;
1992
1993 LookupName(Previous, S);
1994 }
1995
1996 if (Previous.isAmbiguous())
1997 return true;
1998
1999 // Let the template parameter scope enter the lookup chain of the current
2000 // class template. For example, given
2001 //
2002 // namespace ns {
2003 // template <class> bool Param = false;
2004 // template <class T> struct N;
2005 // }
2006 //
2007 // template <class Param> struct ns::N { void foo(Param); };
2008 //
2009 // When we reference Param inside the function parameter list, our name lookup
2010 // chain for it should be like:
2011 // FunctionScope foo
2012 // -> RecordScope N
2013 // -> TemplateParamScope (where we will find Param)
2014 // -> NamespaceScope ns
2015 //
2016 // See also CppLookupName().
2017 if (S->isTemplateParamScope())
2018 EnterTemplatedContext(S, SemanticContext);
2019
2020 NamedDecl *PrevDecl = nullptr;
2021 if (Previous.begin() != Previous.end())
2022 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2023
2024 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2025 // Maybe we will complain about the shadowed template parameter.
2026 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2027 // Just pretend that we didn't see the previous declaration.
2028 PrevDecl = nullptr;
2029 }
2030
2031 // If there is a previous declaration with the same name, check
2032 // whether this is a valid redeclaration.
2033 ClassTemplateDecl *PrevClassTemplate =
2034 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2035
2036 // We may have found the injected-class-name of a class template,
2037 // class template partial specialization, or class template specialization.
2038 // In these cases, grab the template that is being defined or specialized.
2039 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2040 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2041 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2042 PrevClassTemplate
2043 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2044 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2045 PrevClassTemplate
2047 ->getSpecializedTemplate();
2048 }
2049 }
2050
2051 if (TUK == TagUseKind::Friend) {
2052 // C++ [namespace.memdef]p3:
2053 // [...] When looking for a prior declaration of a class or a function
2054 // declared as a friend, and when the name of the friend class or
2055 // function is neither a qualified name nor a template-id, scopes outside
2056 // the innermost enclosing namespace scope are not considered.
2057 if (!SS.isSet()) {
2058 DeclContext *OutermostContext = CurContext;
2059 while (!OutermostContext->isFileContext())
2060 OutermostContext = OutermostContext->getLookupParent();
2061
2062 if (PrevDecl &&
2063 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2064 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2065 SemanticContext = PrevDecl->getDeclContext();
2066 } else {
2067 // Declarations in outer scopes don't matter. However, the outermost
2068 // context we computed is the semantic context for our new
2069 // declaration.
2070 PrevDecl = PrevClassTemplate = nullptr;
2071 SemanticContext = OutermostContext;
2072
2073 // Check that the chosen semantic context doesn't already contain a
2074 // declaration of this name as a non-tag type.
2076 DeclContext *LookupContext = SemanticContext;
2077 while (LookupContext->isTransparentContext())
2078 LookupContext = LookupContext->getLookupParent();
2079 LookupQualifiedName(Previous, LookupContext);
2080
2081 if (Previous.isAmbiguous())
2082 return true;
2083
2084 if (Previous.begin() != Previous.end())
2085 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2086 }
2087 }
2088 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2089 SemanticContext, S, SS.isValid()))
2090 PrevDecl = PrevClassTemplate = nullptr;
2091
2092 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2093 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2094 if (SS.isEmpty() &&
2095 !(PrevClassTemplate &&
2096 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2097 SemanticContext->getRedeclContext()))) {
2098 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2099 Diag(Shadow->getTargetDecl()->getLocation(),
2100 diag::note_using_decl_target);
2101 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2102 // Recover by ignoring the old declaration.
2103 PrevDecl = PrevClassTemplate = nullptr;
2104 }
2105 }
2106
2107 if (PrevClassTemplate) {
2108 // Ensure that the template parameter lists are compatible. Skip this check
2109 // for a friend in a dependent context: the template parameter list itself
2110 // could be dependent.
2111 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2113 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2114 : CurContext,
2115 CurContext, KWLoc),
2116 TemplateParams, PrevClassTemplate,
2117 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2119 return true;
2120
2121 // C++ [temp.class]p4:
2122 // In a redeclaration, partial specialization, explicit
2123 // specialization or explicit instantiation of a class template,
2124 // the class-key shall agree in kind with the original class
2125 // template declaration (7.1.5.3).
2126 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2128 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2129 Diag(KWLoc, diag::err_use_with_wrong_tag)
2130 << Name
2131 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2132 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2133 Kind = PrevRecordDecl->getTagKind();
2134 }
2135
2136 // Check for redefinition of this class template.
2137 if (TUK == TagUseKind::Definition) {
2138 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2139 // If we have a prior definition that is not visible, treat this as
2140 // simply making that previous definition visible.
2141 NamedDecl *Hidden = nullptr;
2142 bool HiddenDefVisible = false;
2143 if (SkipBody &&
2144 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2145 SkipBody->ShouldSkip = true;
2146 SkipBody->Previous = Def;
2147 if (!HiddenDefVisible && Hidden) {
2148 auto *Tmpl =
2149 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2150 assert(Tmpl && "original definition of a class template is not a "
2151 "class template?");
2154 }
2155 } else {
2156 Diag(NameLoc, diag::err_redefinition) << Name;
2157 Diag(Def->getLocation(), diag::note_previous_definition);
2158 // FIXME: Would it make sense to try to "forget" the previous
2159 // definition, as part of error recovery?
2160 return true;
2161 }
2162 }
2163 }
2164 } else if (PrevDecl) {
2165 // C++ [temp]p5:
2166 // A class template shall not have the same name as any other
2167 // template, class, function, object, enumeration, enumerator,
2168 // namespace, or type in the same scope (3.3), except as specified
2169 // in (14.5.4).
2170 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2171 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2172 return true;
2173 }
2174
2175 // Check the template parameter list of this declaration, possibly
2176 // merging in the template parameter list from the previous class
2177 // template declaration. Skip this check for a friend in a dependent
2178 // context, because the template parameter list might be dependent.
2179 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2181 TemplateParams,
2182 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2183 : nullptr,
2184 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2185 SemanticContext->isDependentContext())
2188 : TPC_Other,
2189 SkipBody))
2190 Invalid = true;
2191
2192 if (SS.isSet()) {
2193 // If the name of the template was qualified, we must be defining the
2194 // template out-of-line.
2195 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2196 Diag(NameLoc, TUK == TagUseKind::Friend
2197 ? diag::err_friend_decl_does_not_match
2198 : diag::err_member_decl_does_not_match)
2199 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2200 Invalid = true;
2201 }
2202 }
2203
2204 // If this is a templated friend in a dependent context we should not put it
2205 // on the redecl chain. In some cases, the templated friend can be the most
2206 // recent declaration tricking the template instantiator to make substitutions
2207 // there.
2208 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2209 bool ShouldAddRedecl =
2210 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2211
2213 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2214 PrevClassTemplate && ShouldAddRedecl
2215 ? PrevClassTemplate->getTemplatedDecl()
2216 : nullptr);
2217 SetNestedNameSpecifier(*this, NewClass, SS);
2218 if (NumOuterTemplateParamLists > 0)
2220 Context,
2221 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2222
2223 // Add alignment attributes if necessary; these attributes are checked when
2224 // the ASTContext lays out the structure.
2225 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2226 if (LangOpts.HLSL)
2227 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2230 }
2231
2232 ClassTemplateDecl *NewTemplate
2233 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2234 DeclarationName(Name), TemplateParams,
2235 NewClass);
2236
2237 if (ShouldAddRedecl)
2238 NewTemplate->setPreviousDecl(PrevClassTemplate);
2239
2240 NewClass->setDescribedClassTemplate(NewTemplate);
2241
2242 if (ModulePrivateLoc.isValid())
2243 NewTemplate->setModulePrivate();
2244
2245 // If we are providing an explicit specialization of a member that is a
2246 // class template, make a note of that.
2247 if (PrevClassTemplate &&
2248 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2249 PrevClassTemplate->setMemberSpecialization();
2250
2251 // Set the access specifier.
2252 if (!Invalid && TUK != TagUseKind::Friend &&
2253 NewTemplate->getDeclContext()->isRecord())
2254 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2255
2256 // Set the lexical context of these templates
2258 NewTemplate->setLexicalDeclContext(CurContext);
2259
2260 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2261 NewClass->startDefinition();
2262
2263 ProcessDeclAttributeList(S, NewClass, Attr);
2264
2265 if (PrevClassTemplate)
2266 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2267
2271
2272 if (TUK != TagUseKind::Friend) {
2273 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2274 Scope *Outer = S;
2275 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2276 Outer = Outer->getParent();
2277 PushOnScopeChains(NewTemplate, Outer);
2278 } else {
2279 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2280 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2281 NewClass->setAccess(PrevClassTemplate->getAccess());
2282 }
2283
2284 NewTemplate->setObjectOfFriendDecl();
2285
2286 // Friend templates are visible in fairly strange ways.
2287 if (!CurContext->isDependentContext()) {
2288 DeclContext *DC = SemanticContext->getRedeclContext();
2289 DC->makeDeclVisibleInContext(NewTemplate);
2290 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2291 PushOnScopeChains(NewTemplate, EnclosingScope,
2292 /* AddToContext = */ false);
2293 }
2294
2296 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2297 Friend->setAccess(AS_public);
2298 CurContext->addDecl(Friend);
2299 }
2300
2301 if (PrevClassTemplate)
2302 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2303
2304 if (Invalid) {
2305 NewTemplate->setInvalidDecl();
2306 NewClass->setInvalidDecl();
2307 }
2308
2309 ActOnDocumentableDecl(NewTemplate);
2310
2311 if (SkipBody && SkipBody->ShouldSkip)
2312 return SkipBody->Previous;
2313
2314 return NewTemplate;
2315}
2316
2317/// Diagnose the presence of a default template argument on a
2318/// template parameter, which is ill-formed in certain contexts.
2319///
2320/// \returns true if the default template argument should be dropped.
2323 SourceLocation ParamLoc,
2324 SourceRange DefArgRange) {
2325 switch (TPC) {
2326 case Sema::TPC_Other:
2328 return false;
2329
2332 // C++ [temp.param]p9:
2333 // A default template-argument shall not be specified in a
2334 // function template declaration or a function template
2335 // definition [...]
2336 // If a friend function template declaration specifies a default
2337 // template-argument, that declaration shall be a definition and shall be
2338 // the only declaration of the function template in the translation unit.
2339 // (C++98/03 doesn't have this wording; see DR226).
2340 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2341 << DefArgRange;
2342 return false;
2343
2345 // C++0x [temp.param]p9:
2346 // A default template-argument shall not be specified in the
2347 // template-parameter-lists of the definition of a member of a
2348 // class template that appears outside of the member's class.
2349 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2350 << DefArgRange;
2351 return true;
2352
2355 // C++ [temp.param]p9:
2356 // A default template-argument shall not be specified in a
2357 // friend template declaration.
2358 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2359 << DefArgRange;
2360 return true;
2361
2362 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2363 // for friend function templates if there is only a single
2364 // declaration (and it is a definition). Strange!
2365 }
2366
2367 llvm_unreachable("Invalid TemplateParamListContext!");
2368}
2369
2370/// Check for unexpanded parameter packs within the template parameters
2371/// of a template template parameter, recursively.
2374 // A template template parameter which is a parameter pack is also a pack
2375 // expansion.
2376 if (TTP->isParameterPack())
2377 return false;
2378
2380 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2381 NamedDecl *P = Params->getParam(I);
2382 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2383 if (!TTP->isParameterPack())
2384 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2385 if (TC->hasExplicitTemplateArgs())
2386 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2389 return true;
2390 continue;
2391 }
2392
2393 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2394 if (!NTTP->isParameterPack() &&
2395 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2396 NTTP->getTypeSourceInfo(),
2398 return true;
2399
2400 continue;
2401 }
2402
2403 if (TemplateTemplateParmDecl *InnerTTP
2404 = dyn_cast<TemplateTemplateParmDecl>(P))
2405 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2406 return true;
2407 }
2408
2409 return false;
2410}
2411
2413 TemplateParameterList *OldParams,
2415 SkipBodyInfo *SkipBody) {
2416 bool Invalid = false;
2417
2418 // C++ [temp.param]p10:
2419 // The set of default template-arguments available for use with a
2420 // template declaration or definition is obtained by merging the
2421 // default arguments from the definition (if in scope) and all
2422 // declarations in scope in the same way default function
2423 // arguments are (8.3.6).
2424 bool SawDefaultArgument = false;
2425 SourceLocation PreviousDefaultArgLoc;
2426
2427 // Dummy initialization to avoid warnings.
2428 TemplateParameterList::iterator OldParam = NewParams->end();
2429 if (OldParams)
2430 OldParam = OldParams->begin();
2431
2432 bool RemoveDefaultArguments = false;
2433 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2434 NewParamEnd = NewParams->end();
2435 NewParam != NewParamEnd; ++NewParam) {
2436 // Whether we've seen a duplicate default argument in the same translation
2437 // unit.
2438 bool RedundantDefaultArg = false;
2439 // Whether we've found inconsis inconsitent default arguments in different
2440 // translation unit.
2441 bool InconsistentDefaultArg = false;
2442 // The name of the module which contains the inconsistent default argument.
2443 std::string PrevModuleName;
2444
2445 SourceLocation OldDefaultLoc;
2446 SourceLocation NewDefaultLoc;
2447
2448 // Variable used to diagnose missing default arguments
2449 bool MissingDefaultArg = false;
2450
2451 // Variable used to diagnose non-final parameter packs
2452 bool SawParameterPack = false;
2453
2454 if (TemplateTypeParmDecl *NewTypeParm
2455 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2456 // Check the presence of a default argument here.
2457 if (NewTypeParm->hasDefaultArgument() &&
2459 *this, TPC, NewTypeParm->getLocation(),
2460 NewTypeParm->getDefaultArgument().getSourceRange()))
2461 NewTypeParm->removeDefaultArgument();
2462
2463 // Merge default arguments for template type parameters.
2464 TemplateTypeParmDecl *OldTypeParm
2465 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2466 if (NewTypeParm->isParameterPack()) {
2467 assert(!NewTypeParm->hasDefaultArgument() &&
2468 "Parameter packs can't have a default argument!");
2469 SawParameterPack = true;
2470 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2471 NewTypeParm->hasDefaultArgument() &&
2472 (!SkipBody || !SkipBody->ShouldSkip)) {
2473 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2474 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2475 SawDefaultArgument = true;
2476
2477 if (!OldTypeParm->getOwningModule())
2478 RedundantDefaultArg = true;
2479 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2480 NewTypeParm)) {
2481 InconsistentDefaultArg = true;
2482 PrevModuleName =
2484 }
2485 PreviousDefaultArgLoc = NewDefaultLoc;
2486 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2487 // Merge the default argument from the old declaration to the
2488 // new declaration.
2489 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2490 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2491 } else if (NewTypeParm->hasDefaultArgument()) {
2492 SawDefaultArgument = true;
2493 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2494 } else if (SawDefaultArgument)
2495 MissingDefaultArg = true;
2496 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2497 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2498 // Check for unexpanded parameter packs, except in a template template
2499 // parameter pack, as in those any unexpanded packs should be expanded
2500 // along with the parameter itself.
2502 !NewNonTypeParm->isParameterPack() &&
2503 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2504 NewNonTypeParm->getTypeSourceInfo(),
2506 Invalid = true;
2507 continue;
2508 }
2509
2510 // Check the presence of a default argument here.
2511 if (NewNonTypeParm->hasDefaultArgument() &&
2513 *this, TPC, NewNonTypeParm->getLocation(),
2514 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2515 NewNonTypeParm->removeDefaultArgument();
2516 }
2517
2518 // Merge default arguments for non-type template parameters
2519 NonTypeTemplateParmDecl *OldNonTypeParm
2520 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2521 if (NewNonTypeParm->isParameterPack()) {
2522 assert(!NewNonTypeParm->hasDefaultArgument() &&
2523 "Parameter packs can't have a default argument!");
2524 if (!NewNonTypeParm->isPackExpansion())
2525 SawParameterPack = true;
2526 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2527 NewNonTypeParm->hasDefaultArgument() &&
2528 (!SkipBody || !SkipBody->ShouldSkip)) {
2529 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2530 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2531 SawDefaultArgument = true;
2532 if (!OldNonTypeParm->getOwningModule())
2533 RedundantDefaultArg = true;
2534 else if (!getASTContext().isSameDefaultTemplateArgument(
2535 OldNonTypeParm, NewNonTypeParm)) {
2536 InconsistentDefaultArg = true;
2537 PrevModuleName =
2538 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2539 }
2540 PreviousDefaultArgLoc = NewDefaultLoc;
2541 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2542 // Merge the default argument from the old declaration to the
2543 // new declaration.
2544 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2545 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2546 } else if (NewNonTypeParm->hasDefaultArgument()) {
2547 SawDefaultArgument = true;
2548 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2549 } else if (SawDefaultArgument)
2550 MissingDefaultArg = true;
2551 } else {
2552 TemplateTemplateParmDecl *NewTemplateParm
2553 = cast<TemplateTemplateParmDecl>(*NewParam);
2554
2555 // Check for unexpanded parameter packs, recursively.
2556 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2557 Invalid = true;
2558 continue;
2559 }
2560
2561 // Check the presence of a default argument here.
2562 if (NewTemplateParm->hasDefaultArgument() &&
2564 NewTemplateParm->getLocation(),
2565 NewTemplateParm->getDefaultArgument().getSourceRange()))
2566 NewTemplateParm->removeDefaultArgument();
2567
2568 // Merge default arguments for template template parameters
2569 TemplateTemplateParmDecl *OldTemplateParm
2570 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2571 if (NewTemplateParm->isParameterPack()) {
2572 assert(!NewTemplateParm->hasDefaultArgument() &&
2573 "Parameter packs can't have a default argument!");
2574 if (!NewTemplateParm->isPackExpansion())
2575 SawParameterPack = true;
2576 } else if (OldTemplateParm &&
2577 hasVisibleDefaultArgument(OldTemplateParm) &&
2578 NewTemplateParm->hasDefaultArgument() &&
2579 (!SkipBody || !SkipBody->ShouldSkip)) {
2580 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2581 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2582 SawDefaultArgument = true;
2583 if (!OldTemplateParm->getOwningModule())
2584 RedundantDefaultArg = true;
2585 else if (!getASTContext().isSameDefaultTemplateArgument(
2586 OldTemplateParm, NewTemplateParm)) {
2587 InconsistentDefaultArg = true;
2588 PrevModuleName =
2589 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2590 }
2591 PreviousDefaultArgLoc = NewDefaultLoc;
2592 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2593 // Merge the default argument from the old declaration to the
2594 // new declaration.
2595 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2596 PreviousDefaultArgLoc
2597 = OldTemplateParm->getDefaultArgument().getLocation();
2598 } else if (NewTemplateParm->hasDefaultArgument()) {
2599 SawDefaultArgument = true;
2600 PreviousDefaultArgLoc
2601 = NewTemplateParm->getDefaultArgument().getLocation();
2602 } else if (SawDefaultArgument)
2603 MissingDefaultArg = true;
2604 }
2605
2606 // C++11 [temp.param]p11:
2607 // If a template parameter of a primary class template or alias template
2608 // is a template parameter pack, it shall be the last template parameter.
2609 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2610 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2611 Diag((*NewParam)->getLocation(),
2612 diag::err_template_param_pack_must_be_last_template_parameter);
2613 Invalid = true;
2614 }
2615
2616 // [basic.def.odr]/13:
2617 // There can be more than one definition of a
2618 // ...
2619 // default template argument
2620 // ...
2621 // in a program provided that each definition appears in a different
2622 // translation unit and the definitions satisfy the [same-meaning
2623 // criteria of the ODR].
2624 //
2625 // Simply, the design of modules allows the definition of template default
2626 // argument to be repeated across translation unit. Note that the ODR is
2627 // checked elsewhere. But it is still not allowed to repeat template default
2628 // argument in the same translation unit.
2629 if (RedundantDefaultArg) {
2630 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2631 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2632 Invalid = true;
2633 } else if (InconsistentDefaultArg) {
2634 // We could only diagnose about the case that the OldParam is imported.
2635 // The case NewParam is imported should be handled in ASTReader.
2636 Diag(NewDefaultLoc,
2637 diag::err_template_param_default_arg_inconsistent_redefinition);
2638 Diag(OldDefaultLoc,
2639 diag::note_template_param_prev_default_arg_in_other_module)
2640 << PrevModuleName;
2641 Invalid = true;
2642 } else if (MissingDefaultArg &&
2643 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2644 TPC == TPC_FriendClassTemplate)) {
2645 // C++ 23[temp.param]p14:
2646 // If a template-parameter of a class template, variable template, or
2647 // alias template has a default template argument, each subsequent
2648 // template-parameter shall either have a default template argument
2649 // supplied or be a template parameter pack.
2650 Diag((*NewParam)->getLocation(),
2651 diag::err_template_param_default_arg_missing);
2652 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2653 Invalid = true;
2654 RemoveDefaultArguments = true;
2655 }
2656
2657 // If we have an old template parameter list that we're merging
2658 // in, move on to the next parameter.
2659 if (OldParams)
2660 ++OldParam;
2661 }
2662
2663 // We were missing some default arguments at the end of the list, so remove
2664 // all of the default arguments.
2665 if (RemoveDefaultArguments) {
2666 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2667 NewParamEnd = NewParams->end();
2668 NewParam != NewParamEnd; ++NewParam) {
2669 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2670 TTP->removeDefaultArgument();
2671 else if (NonTypeTemplateParmDecl *NTTP
2672 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2673 NTTP->removeDefaultArgument();
2674 else
2675 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2676 }
2677 }
2678
2679 return Invalid;
2680}
2681
2682namespace {
2683
2684/// A class which looks for a use of a certain level of template
2685/// parameter.
2686struct DependencyChecker : DynamicRecursiveASTVisitor {
2687 unsigned Depth;
2688
2689 // Whether we're looking for a use of a template parameter that makes the
2690 // overall construct type-dependent / a dependent type. This is strictly
2691 // best-effort for now; we may fail to match at all for a dependent type
2692 // in some cases if this is set.
2693 bool IgnoreNonTypeDependent;
2694
2695 bool Match;
2696 SourceLocation MatchLoc;
2697
2698 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2699 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2700 Match(false) {}
2701
2702 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2703 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2704 NamedDecl *ND = Params->getParam(0);
2705 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2706 Depth = PD->getDepth();
2707 } else if (NonTypeTemplateParmDecl *PD =
2708 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2709 Depth = PD->getDepth();
2710 } else {
2711 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2712 }
2713 }
2714
2715 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2716 if (ParmDepth >= Depth) {
2717 Match = true;
2718 MatchLoc = Loc;
2719 return true;
2720 }
2721 return false;
2722 }
2723
2724 bool TraverseStmt(Stmt *S) override {
2725 // Prune out non-type-dependent expressions if requested. This can
2726 // sometimes result in us failing to find a template parameter reference
2727 // (if a value-dependent expression creates a dependent type), but this
2728 // mode is best-effort only.
2729 if (auto *E = dyn_cast_or_null<Expr>(S))
2730 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2731 return true;
2733 }
2734
2735 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2736 if (IgnoreNonTypeDependent && !TL.isNull() &&
2737 !TL.getType()->isDependentType())
2738 return true;
2739 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2740 }
2741
2742 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2743 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2744 }
2745
2746 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2747 // For a best-effort search, keep looking until we find a location.
2748 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2749 }
2750
2751 bool TraverseTemplateName(TemplateName N) override {
2752 if (TemplateTemplateParmDecl *PD =
2753 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2754 if (Matches(PD->getDepth()))
2755 return false;
2757 }
2758
2759 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2760 if (NonTypeTemplateParmDecl *PD =
2761 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2762 if (Matches(PD->getDepth(), E->getExprLoc()))
2763 return false;
2764 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2765 }
2766
2767 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2768 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2769 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2770 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2771 return false;
2772 }
2773 for (auto &TLoc : ULE->template_arguments())
2775 }
2776 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2777 }
2778
2779 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2780 return TraverseType(T->getReplacementType());
2781 }
2782
2783 bool VisitSubstTemplateTypeParmPackType(
2784 SubstTemplateTypeParmPackType *T) override {
2785 return TraverseTemplateArgument(T->getArgumentPack());
2786 }
2787
2788 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2789 bool TraverseQualifier) override {
2790 // An InjectedClassNameType will never have a dependent template name,
2791 // so no need to traverse it.
2792 return TraverseTemplateArguments(
2793 T->getTemplateArgs(T->getOriginalDecl()->getASTContext()));
2794 }
2795};
2796} // end anonymous namespace
2797
2798/// Determines whether a given type depends on the given parameter
2799/// list.
2800static bool
2802 if (!Params->size())
2803 return false;
2804
2805 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2806 Checker.TraverseType(T);
2807 return Checker.Match;
2808}
2809
2810// Find the source range corresponding to the named type in the given
2811// nested-name-specifier, if any.
2813 QualType T,
2814 const CXXScopeSpec &SS) {
2816 for (;;) {
2819 break;
2820 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2821 return NNSLoc.castAsTypeLoc().getSourceRange();
2822 // FIXME: This will always be empty.
2823 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2824 }
2825
2826 return SourceRange();
2827}
2828
2830 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2831 TemplateIdAnnotation *TemplateId,
2832 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2833 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2834 IsMemberSpecialization = false;
2835 Invalid = false;
2836
2837 // The sequence of nested types to which we will match up the template
2838 // parameter lists. We first build this list by starting with the type named
2839 // by the nested-name-specifier and walking out until we run out of types.
2840 SmallVector<QualType, 4> NestedTypes;
2841 QualType T;
2842 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2843 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2844 if (CXXRecordDecl *Record =
2845 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2846 T = Context.getCanonicalTagType(Record);
2847 else
2848 T = QualType(Qualifier.getAsType(), 0);
2849 }
2850
2851 // If we found an explicit specialization that prevents us from needing
2852 // 'template<>' headers, this will be set to the location of that
2853 // explicit specialization.
2854 SourceLocation ExplicitSpecLoc;
2855
2856 while (!T.isNull()) {
2857 NestedTypes.push_back(T);
2858
2859 // Retrieve the parent of a record type.
2860 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2861 // If this type is an explicit specialization, we're done.
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2865 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2866 ExplicitSpecLoc = Spec->getLocation();
2867 break;
2868 }
2869 } else if (Record->getTemplateSpecializationKind()
2871 ExplicitSpecLoc = Record->getLocation();
2872 break;
2873 }
2874
2875 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2876 T = Context.getTypeDeclType(Parent);
2877 else
2878 T = QualType();
2879 continue;
2880 }
2881
2882 if (const TemplateSpecializationType *TST
2883 = T->getAs<TemplateSpecializationType>()) {
2884 TemplateName Name = TST->getTemplateName();
2885 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2886 // Look one step prior in a dependent template specialization type.
2887 if (NestedNameSpecifier NNS = DTS->getQualifier();
2889 T = QualType(NNS.getAsType(), 0);
2890 else
2891 T = QualType();
2892 continue;
2893 }
2894 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2895 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2896 T = Context.getTypeDeclType(Parent);
2897 else
2898 T = QualType();
2899 continue;
2900 }
2901 }
2902
2903 // Look one step prior in a dependent name type.
2904 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2905 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2907 T = QualType(NNS.getAsType(), 0);
2908 else
2909 T = QualType();
2910 continue;
2911 }
2912
2913 // Retrieve the parent of an enumeration type.
2914 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2915 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2916 // check here.
2917 EnumDecl *Enum = EnumT->getOriginalDecl();
2918
2919 // Get to the parent type.
2920 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2921 T = Context.getCanonicalTypeDeclType(Parent);
2922 else
2923 T = QualType();
2924 continue;
2925 }
2926
2927 T = QualType();
2928 }
2929 // Reverse the nested types list, since we want to traverse from the outermost
2930 // to the innermost while checking template-parameter-lists.
2931 std::reverse(NestedTypes.begin(), NestedTypes.end());
2932
2933 // C++0x [temp.expl.spec]p17:
2934 // A member or a member template may be nested within many
2935 // enclosing class templates. In an explicit specialization for
2936 // such a member, the member declaration shall be preceded by a
2937 // template<> for each enclosing class template that is
2938 // explicitly specialized.
2939 bool SawNonEmptyTemplateParameterList = false;
2940
2941 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2942 if (SawNonEmptyTemplateParameterList) {
2943 if (!SuppressDiagnostic)
2944 Diag(DeclLoc, diag::err_specialize_member_of_template)
2945 << !Recovery << Range;
2946 Invalid = true;
2947 IsMemberSpecialization = false;
2948 return true;
2949 }
2950
2951 return false;
2952 };
2953
2954 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2955 // Check that we can have an explicit specialization here.
2956 if (CheckExplicitSpecialization(Range, true))
2957 return true;
2958
2959 // We don't have a template header, but we should.
2960 SourceLocation ExpectedTemplateLoc;
2961 if (!ParamLists.empty())
2962 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2963 else
2964 ExpectedTemplateLoc = DeclStartLoc;
2965
2966 if (!SuppressDiagnostic)
2967 Diag(DeclLoc, diag::err_template_spec_needs_header)
2968 << Range
2969 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2970 return false;
2971 };
2972
2973 unsigned ParamIdx = 0;
2974 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2975 ++TypeIdx) {
2976 T = NestedTypes[TypeIdx];
2977
2978 // Whether we expect a 'template<>' header.
2979 bool NeedEmptyTemplateHeader = false;
2980
2981 // Whether we expect a template header with parameters.
2982 bool NeedNonemptyTemplateHeader = false;
2983
2984 // For a dependent type, the set of template parameters that we
2985 // expect to see.
2986 TemplateParameterList *ExpectedTemplateParams = nullptr;
2987
2988 // C++0x [temp.expl.spec]p15:
2989 // A member or a member template may be nested within many enclosing
2990 // class templates. In an explicit specialization for such a member, the
2991 // member declaration shall be preceded by a template<> for each
2992 // enclosing class template that is explicitly specialized.
2993 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2996 ExpectedTemplateParams = Partial->getTemplateParameters();
2997 NeedNonemptyTemplateHeader = true;
2998 } else if (Record->isDependentType()) {
2999 if (Record->getDescribedClassTemplate()) {
3000 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3001 ->getTemplateParameters();
3002 NeedNonemptyTemplateHeader = true;
3003 }
3004 } else if (ClassTemplateSpecializationDecl *Spec
3005 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3006 // C++0x [temp.expl.spec]p4:
3007 // Members of an explicitly specialized class template are defined
3008 // in the same manner as members of normal classes, and not using
3009 // the template<> syntax.
3010 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3011 NeedEmptyTemplateHeader = true;
3012 else
3013 continue;
3014 } else if (Record->getTemplateSpecializationKind()) {
3015 if (Record->getTemplateSpecializationKind()
3017 TypeIdx == NumTypes - 1)
3018 IsMemberSpecialization = true;
3019
3020 continue;
3021 }
3022 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3023 TemplateName Name = TST->getTemplateName();
3024 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3025 ExpectedTemplateParams = Template->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 } else if (Name.getAsDeducedTemplateName()) {
3028 // FIXME: We actually could/should check the template arguments here
3029 // against the corresponding template parameter list.
3030 NeedNonemptyTemplateHeader = false;
3031 }
3032 }
3033
3034 // C++ [temp.expl.spec]p16:
3035 // In an explicit specialization declaration for a member of a class
3036 // template or a member template that appears in namespace scope, the
3037 // member template and some of its enclosing class templates may remain
3038 // unspecialized, except that the declaration shall not explicitly
3039 // specialize a class member template if its enclosing class templates
3040 // are not explicitly specialized as well.
3041 if (ParamIdx < ParamLists.size()) {
3042 if (ParamLists[ParamIdx]->size() == 0) {
3043 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3044 false))
3045 return nullptr;
3046 } else
3047 SawNonEmptyTemplateParameterList = true;
3048 }
3049
3050 if (NeedEmptyTemplateHeader) {
3051 // If we're on the last of the types, and we need a 'template<>' header
3052 // here, then it's a member specialization.
3053 if (TypeIdx == NumTypes - 1)
3054 IsMemberSpecialization = true;
3055
3056 if (ParamIdx < ParamLists.size()) {
3057 if (ParamLists[ParamIdx]->size() > 0) {
3058 // The header has template parameters when it shouldn't. Complain.
3059 if (!SuppressDiagnostic)
3060 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3061 diag::err_template_param_list_matches_nontemplate)
3062 << T
3063 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3064 ParamLists[ParamIdx]->getRAngleLoc())
3066 Invalid = true;
3067 return nullptr;
3068 }
3069
3070 // Consume this template header.
3071 ++ParamIdx;
3072 continue;
3073 }
3074
3075 if (!IsFriend)
3076 if (DiagnoseMissingExplicitSpecialization(
3078 return nullptr;
3079
3080 continue;
3081 }
3082
3083 if (NeedNonemptyTemplateHeader) {
3084 // In friend declarations we can have template-ids which don't
3085 // depend on the corresponding template parameter lists. But
3086 // assume that empty parameter lists are supposed to match this
3087 // template-id.
3088 if (IsFriend && T->isDependentType()) {
3089 if (ParamIdx < ParamLists.size() &&
3091 ExpectedTemplateParams = nullptr;
3092 else
3093 continue;
3094 }
3095
3096 if (ParamIdx < ParamLists.size()) {
3097 // Check the template parameter list, if we can.
3098 if (ExpectedTemplateParams &&
3100 ExpectedTemplateParams,
3101 !SuppressDiagnostic, TPL_TemplateMatch))
3102 Invalid = true;
3103
3104 if (!Invalid &&
3105 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3107 Invalid = true;
3108
3109 ++ParamIdx;
3110 continue;
3111 }
3112
3113 if (!SuppressDiagnostic)
3114 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3115 << T
3117 Invalid = true;
3118 continue;
3119 }
3120 }
3121
3122 // If there were at least as many template-ids as there were template
3123 // parameter lists, then there are no template parameter lists remaining for
3124 // the declaration itself.
3125 if (ParamIdx >= ParamLists.size()) {
3126 if (TemplateId && !IsFriend) {
3127 // We don't have a template header for the declaration itself, but we
3128 // should.
3129 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3130 TemplateId->RAngleLoc));
3131
3132 // Fabricate an empty template parameter list for the invented header.
3134 SourceLocation(), {},
3135 SourceLocation(), nullptr);
3136 }
3137
3138 return nullptr;
3139 }
3140
3141 // If there were too many template parameter lists, complain about that now.
3142 if (ParamIdx < ParamLists.size() - 1) {
3143 bool HasAnyExplicitSpecHeader = false;
3144 bool AllExplicitSpecHeaders = true;
3145 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3146 if (ParamLists[I]->size() == 0)
3147 HasAnyExplicitSpecHeader = true;
3148 else
3149 AllExplicitSpecHeaders = false;
3150 }
3151
3152 if (!SuppressDiagnostic)
3153 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3154 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3155 : diag::err_template_spec_extra_headers)
3156 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3157 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3158
3159 // If there was a specialization somewhere, such that 'template<>' is
3160 // not required, and there were any 'template<>' headers, note where the
3161 // specialization occurred.
3162 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3163 !SuppressDiagnostic)
3164 Diag(ExplicitSpecLoc,
3165 diag::note_explicit_template_spec_does_not_need_header)
3166 << NestedTypes.back();
3167
3168 // We have a template parameter list with no corresponding scope, which
3169 // means that the resulting template declaration can't be instantiated
3170 // properly (we'll end up with dependent nodes when we shouldn't).
3171 if (!AllExplicitSpecHeaders)
3172 Invalid = true;
3173 }
3174
3175 // C++ [temp.expl.spec]p16:
3176 // In an explicit specialization declaration for a member of a class
3177 // template or a member template that ap- pears in namespace scope, the
3178 // member template and some of its enclosing class templates may remain
3179 // unspecialized, except that the declaration shall not explicitly
3180 // specialize a class member template if its en- closing class templates
3181 // are not explicitly specialized as well.
3182 if (ParamLists.back()->size() == 0 &&
3183 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3184 false))
3185 return nullptr;
3186
3187 // Return the last template parameter list, which corresponds to the
3188 // entity being declared.
3189 return ParamLists.back();
3190}
3191
3193 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3194 Diag(Template->getLocation(), diag::note_template_declared_here)
3196 ? 0
3198 ? 1
3200 ? 2
3202 << Template->getDeclName();
3203 return;
3204 }
3205
3207 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3208 IEnd = OST->end();
3209 I != IEnd; ++I)
3210 Diag((*I)->getLocation(), diag::note_template_declared_here)
3211 << 0 << (*I)->getDeclName();
3212
3213 return;
3214 }
3215}
3216
3218 TemplateName BaseTemplate,
3219 SourceLocation TemplateLoc,
3221 auto lookUpCommonType = [&](TemplateArgument T1,
3222 TemplateArgument T2) -> QualType {
3223 // Don't bother looking for other specializations if both types are
3224 // builtins - users aren't allowed to specialize for them
3225 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3226 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3227 {T1, T2});
3228
3232 Args.addArgument(TemplateArgumentLoc(
3233 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3234
3235 EnterExpressionEvaluationContext UnevaluatedContext(
3237 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3239
3240 QualType BaseTemplateInst = S.CheckTemplateIdType(
3241 Keyword, BaseTemplate, TemplateLoc, Args,
3242 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3243
3244 if (SFINAE.hasErrorOccurred())
3245 return QualType();
3246
3247 return BaseTemplateInst;
3248 };
3249
3250 // Note A: For the common_type trait applied to a template parameter pack T of
3251 // types, the member type shall be either defined or not present as follows:
3252 switch (Ts.size()) {
3253
3254 // If sizeof...(T) is zero, there shall be no member type.
3255 case 0:
3256 return QualType();
3257
3258 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3259 // pack T. The member typedef-name type shall denote the same type, if any, as
3260 // common_type_t<T0, T0>; otherwise there shall be no member type.
3261 case 1:
3262 return lookUpCommonType(Ts[0], Ts[0]);
3263
3264 // If sizeof...(T) is two, let the first and second types constituting T be
3265 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3266 // as decay_t<T1> and decay_t<T2>, respectively.
3267 case 2: {
3268 QualType T1 = Ts[0].getAsType();
3269 QualType T2 = Ts[1].getAsType();
3270 QualType D1 = S.BuiltinDecay(T1, {});
3271 QualType D2 = S.BuiltinDecay(T2, {});
3272
3273 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3274 // the same type, if any, as common_type_t<D1, D2>.
3275 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3276 return lookUpCommonType(D1, D2);
3277
3278 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3279 // denotes a valid type, let C denote that type.
3280 {
3281 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3282 EnterExpressionEvaluationContext UnevaluatedContext(
3284 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3286
3287 // false
3289 VK_PRValue);
3290 ExprResult Cond = &CondExpr;
3291
3292 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3293 if (ConstRefQual) {
3294 D1.addConst();
3295 D2.addConst();
3296 }
3297
3298 // declval<D1>()
3299 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3300 ExprResult LHS = &LHSExpr;
3301
3302 // declval<D2>()
3303 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3304 ExprResult RHS = &RHSExpr;
3305
3308
3309 // decltype(false ? declval<D1>() : declval<D2>())
3310 QualType Result =
3311 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3312
3313 if (Result.isNull() || SFINAE.hasErrorOccurred())
3314 return QualType();
3315
3316 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3317 return S.BuiltinDecay(Result, TemplateLoc);
3318 };
3319
3320 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3321 return Res;
3322
3323 // Let:
3324 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3325 // COND-RES(X, Y) be
3326 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3327
3328 // C++20 only
3329 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3330 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3331 if (!S.Context.getLangOpts().CPlusPlus20)
3332 return QualType();
3333 return CheckConditionalOperands(true);
3334 }
3335 }
3336
3337 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3338 // denote the first, second, and (pack of) remaining types constituting T. Let
3339 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3340 // a type C, the member typedef-name type shall denote the same type, if any,
3341 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3342 default: {
3343 QualType Result = Ts.front().getAsType();
3344 for (auto T : llvm::drop_begin(Ts)) {
3345 Result = lookUpCommonType(Result, T.getAsType());
3346 if (Result.isNull())
3347 return QualType();
3348 }
3349 return Result;
3350 }
3351 }
3352}
3353
3354static bool isInVkNamespace(const RecordType *RT) {
3355 DeclContext *DC = RT->getOriginalDecl()->getDeclContext();
3356 if (!DC)
3357 return false;
3358
3359 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3360 if (!ND)
3361 return false;
3362
3363 return ND->getQualifiedNameAsString() == "hlsl::vk";
3364}
3365
3366static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3367 QualType OperandArg,
3368 SourceLocation Loc) {
3369 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3370 bool Literal = false;
3371 SourceLocation LiteralLoc;
3372 if (isInVkNamespace(RT) && RT->getOriginalDecl()->getName() == "Literal") {
3373 auto SpecDecl =
3374 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3375 assert(SpecDecl);
3376
3377 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3378 QualType ConstantType = LiteralArgs[0].getAsType();
3379 RT = ConstantType->getAsCanonical<RecordType>();
3380 Literal = true;
3381 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3382 }
3383
3384 if (RT && isInVkNamespace(RT) &&
3385 RT->getOriginalDecl()->getName() == "integral_constant") {
3386 auto SpecDecl =
3387 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3388 assert(SpecDecl);
3389
3390 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3391
3392 QualType ConstantType = ConstantArgs[0].getAsType();
3393 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3394
3395 if (Literal)
3396 return SpirvOperand::createLiteral(Value);
3397 return SpirvOperand::createConstant(ConstantType, Value);
3398 } else if (Literal) {
3399 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3400 return SpirvOperand();
3401 }
3402 }
3403 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3404 diag::err_call_incomplete_argument))
3405 return SpirvOperand();
3406 return SpirvOperand::createType(OperandArg);
3407}
3408
3411 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3412 TemplateArgumentListInfo &TemplateArgs) {
3413 ASTContext &Context = SemaRef.getASTContext();
3414
3415 switch (BTD->getBuiltinTemplateKind()) {
3416 case BTK__make_integer_seq: {
3417 // Specializations of __make_integer_seq<S, T, N> are treated like
3418 // S<T, 0, ..., N-1>.
3419
3420 QualType OrigType = Converted[1].getAsType();
3421 // C++14 [inteseq.intseq]p1:
3422 // T shall be an integer type.
3423 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3424 SemaRef.Diag(TemplateArgs[1].getLocation(),
3425 diag::err_integer_sequence_integral_element_type);
3426 return QualType();
3427 }
3428
3429 TemplateArgument NumArgsArg = Converted[2];
3430 if (NumArgsArg.isDependent())
3431 return QualType();
3432
3433 TemplateArgumentListInfo SyntheticTemplateArgs;
3434 // The type argument, wrapped in substitution sugar, gets reused as the
3435 // first template argument in the synthetic template argument list.
3436 SyntheticTemplateArgs.addArgument(
3439 OrigType, TemplateArgs[1].getLocation())));
3440
3441 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3442 // Expand N into 0 ... N-1.
3443 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3444 I < NumArgs; ++I) {
3445 TemplateArgument TA(Context, I, OrigType);
3446 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3447 TA, OrigType, TemplateArgs[2].getLocation()));
3448 }
3449 } else {
3450 // C++14 [inteseq.make]p1:
3451 // If N is negative the program is ill-formed.
3452 SemaRef.Diag(TemplateArgs[2].getLocation(),
3453 diag::err_integer_sequence_negative_length);
3454 return QualType();
3455 }
3456
3457 // The first template argument will be reused as the template decl that
3458 // our synthetic template arguments will be applied to.
3459 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3460 TemplateLoc, SyntheticTemplateArgs,
3461 /*Scope=*/nullptr,
3462 /*ForNestedNameSpecifier=*/false);
3463 }
3464
3465 case BTK__type_pack_element: {
3466 // Specializations of
3467 // __type_pack_element<Index, T_1, ..., T_N>
3468 // are treated like T_Index.
3469 assert(Converted.size() == 2 &&
3470 "__type_pack_element should be given an index and a parameter pack");
3471
3472 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3473 if (IndexArg.isDependent() || Ts.isDependent())
3474 return QualType();
3475
3476 llvm::APSInt Index = IndexArg.getAsIntegral();
3477 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3478 "type std::size_t, and hence be non-negative");
3479 // If the Index is out of bounds, the program is ill-formed.
3480 if (Index >= Ts.pack_size()) {
3481 SemaRef.Diag(TemplateArgs[0].getLocation(),
3482 diag::err_type_pack_element_out_of_bounds);
3483 return QualType();
3484 }
3485
3486 // We simply return the type at index `Index`.
3487 int64_t N = Index.getExtValue();
3488 return Ts.getPackAsArray()[N].getAsType();
3489 }
3490
3491 case BTK__builtin_common_type: {
3492 assert(Converted.size() == 4);
3493 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3494 return QualType();
3495
3496 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3497 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3498 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3499 TemplateLoc, Ts);
3500 !CT.isNull()) {
3504 CT, TemplateArgs[1].getLocation())));
3505 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3506 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3507 TAs, /*Scope=*/nullptr,
3508 /*ForNestedNameSpecifier=*/false);
3509 }
3510 QualType HasNoTypeMember = Converted[2].getAsType();
3511 return HasNoTypeMember;
3512 }
3513
3514 case BTK__hlsl_spirv_type: {
3515 assert(Converted.size() == 4);
3516
3517 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3518 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3519 }
3520
3521 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3522 return QualType();
3523
3524 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3525 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3526 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3527
3528 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3529
3531
3532 for (auto &OperandTA : OperandArgs) {
3533 QualType OperandArg = OperandTA.getAsType();
3534 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3535 TemplateArgs[3].getLocation());
3536 if (!Operand.isValid())
3537 return QualType();
3538 Operands.push_back(Operand);
3539 }
3540
3541 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3542 }
3543 case BTK__builtin_dedup_pack: {
3544 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3545 "a parameter pack");
3546 TemplateArgument Ts = Converted[0];
3547 // Delay the computation until we can compute the final result. We choose
3548 // not to remove the duplicates upfront before substitution to keep the code
3549 // simple.
3550 if (Ts.isDependent())
3551 return QualType();
3552 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3554 llvm::SmallDenseSet<QualType> Seen;
3555 // Synthesize a new template argument list, removing duplicates.
3556 for (auto T : Ts.getPackAsArray()) {
3557 assert(T.getKind() == clang::TemplateArgument::Type);
3558 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3559 continue;
3560 OutArgs.push_back(T);
3561 }
3562 return Context.getSubstBuiltinTemplatePack(
3563 TemplateArgument::CreatePackCopy(Context, OutArgs));
3564 }
3565 }
3566 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3567}
3568
3569/// Determine whether this alias template is "enable_if_t".
3570/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3572 return AliasTemplate->getName() == "enable_if_t" ||
3573 AliasTemplate->getName() == "__enable_if_t";
3574}
3575
3576/// Collect all of the separable terms in the given condition, which
3577/// might be a conjunction.
3578///
3579/// FIXME: The right answer is to convert the logical expression into
3580/// disjunctive normal form, so we can find the first failed term
3581/// within each possible clause.
3582static void collectConjunctionTerms(Expr *Clause,
3583 SmallVectorImpl<Expr *> &Terms) {
3584 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3585 if (BinOp->getOpcode() == BO_LAnd) {
3586 collectConjunctionTerms(BinOp->getLHS(), Terms);
3587 collectConjunctionTerms(BinOp->getRHS(), Terms);
3588 return;
3589 }
3590 }
3591
3592 Terms.push_back(Clause);
3593}
3594
3595// The ranges-v3 library uses an odd pattern of a top-level "||" with
3596// a left-hand side that is value-dependent but never true. Identify
3597// the idiom and ignore that term.
3599 // Top-level '||'.
3600 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3601 if (!BinOp) return Cond;
3602
3603 if (BinOp->getOpcode() != BO_LOr) return Cond;
3604
3605 // With an inner '==' that has a literal on the right-hand side.
3606 Expr *LHS = BinOp->getLHS();
3607 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3608 if (!InnerBinOp) return Cond;
3609
3610 if (InnerBinOp->getOpcode() != BO_EQ ||
3611 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3612 return Cond;
3613
3614 // If the inner binary operation came from a macro expansion named
3615 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3616 // of the '||', which is the real, user-provided condition.
3617 SourceLocation Loc = InnerBinOp->getExprLoc();
3618 if (!Loc.isMacroID()) return Cond;
3619
3620 StringRef MacroName = PP.getImmediateMacroName(Loc);
3621 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3622 return BinOp->getRHS();
3623
3624 return Cond;
3625}
3626
3627namespace {
3628
3629// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3630// within failing boolean expression, such as substituting template parameters
3631// for actual types.
3632class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3633public:
3634 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3635 : Policy(P) {}
3636
3637 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3638 const auto *DR = dyn_cast<DeclRefExpr>(E);
3639 if (DR && DR->getQualifier()) {
3640 // If this is a qualified name, expand the template arguments in nested
3641 // qualifiers.
3642 DR->getQualifier().print(OS, Policy, true);
3643 // Then print the decl itself.
3644 const ValueDecl *VD = DR->getDecl();
3645 OS << VD->getName();
3646 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3647 // This is a template variable, print the expanded template arguments.
3648 printTemplateArgumentList(
3649 OS, IV->getTemplateArgs().asArray(), Policy,
3650 IV->getSpecializedTemplate()->getTemplateParameters());
3651 }
3652 return true;
3653 }
3654 return false;
3655 }
3656
3657private:
3658 const PrintingPolicy Policy;
3659};
3660
3661} // end anonymous namespace
3662
3663std::pair<Expr *, std::string>
3666
3667 // Separate out all of the terms in a conjunction.
3670
3671 // Determine which term failed.
3672 Expr *FailedCond = nullptr;
3673 for (Expr *Term : Terms) {
3674 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3675
3676 // Literals are uninteresting.
3677 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3678 isa<IntegerLiteral>(TermAsWritten))
3679 continue;
3680
3681 // The initialization of the parameter from the argument is
3682 // a constant-evaluated context.
3685
3686 bool Succeeded;
3687 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3688 !Succeeded) {
3689 FailedCond = TermAsWritten;
3690 break;
3691 }
3692 }
3693 if (!FailedCond)
3694 FailedCond = Cond->IgnoreParenImpCasts();
3695
3696 std::string Description;
3697 {
3698 llvm::raw_string_ostream Out(Description);
3700 Policy.PrintAsCanonical = true;
3701 FailedBooleanConditionPrinterHelper Helper(Policy);
3702 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3703 }
3704 return { FailedCond, Description };
3705}
3706
3707static TemplateName
3709 const AssumedTemplateStorage *ATN,
3710 SourceLocation NameLoc) {
3711 // We assumed this undeclared identifier to be an (ADL-only) function
3712 // template name, but it was used in a context where a type was required.
3713 // Try to typo-correct it now.
3714 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3715 struct CandidateCallback : CorrectionCandidateCallback {
3716 bool ValidateCandidate(const TypoCorrection &TC) override {
3717 return TC.getCorrectionDecl() &&
3719 }
3720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3721 return std::make_unique<CandidateCallback>(*this);
3722 }
3723 } FilterCCC;
3724
3725 TypoCorrection Corrected =
3727 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3728 if (Corrected && Corrected.getFoundDecl()) {
3729 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3730 << ATN->getDeclName());
3732 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3734 }
3735
3736 return TemplateName();
3737}
3738
3740 TemplateName Name,
3741 SourceLocation TemplateLoc,
3742 TemplateArgumentListInfo &TemplateArgs,
3743 Scope *Scope, bool ForNestedNameSpecifier) {
3744 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3745
3746 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3747 if (!Template) {
3748 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3749 Template = S->getParameterPack();
3750 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3751 if (DTN->getName().getIdentifier())
3752 // When building a template-id where the template-name is dependent,
3753 // assume the template is a type template. Either our assumption is
3754 // correct, or the code is ill-formed and will be diagnosed when the
3755 // dependent name is substituted.
3756 return Context.getTemplateSpecializationType(Keyword, Name,
3757 TemplateArgs.arguments(),
3758 /*CanonicalArgs=*/{});
3759 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3761 *this, Scope, ATN, TemplateLoc);
3762 CorrectedName.isNull()) {
3763 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3764 return QualType();
3765 } else {
3766 Name = CorrectedName;
3767 Template = Name.getAsTemplateDecl();
3768 }
3769 }
3770 }
3771 if (!Template ||
3773 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3774 if (ForNestedNameSpecifier)
3775 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3776 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3777 else
3778 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3780 return QualType();
3781 }
3782
3783 // Check that the template argument list is well-formed for this
3784 // template.
3786 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3787 DefaultArgs, /*PartialTemplateArgs=*/false,
3788 CTAI,
3789 /*UpdateArgsWithConversions=*/true))
3790 return QualType();
3791
3792 QualType CanonType;
3793
3795 // We might have a substituted template template parameter pack. If so,
3796 // build a template specialization type for it.
3798 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3799
3800 // C++0x [dcl.type.elab]p2:
3801 // If the identifier resolves to a typedef-name or the simple-template-id
3802 // resolves to an alias template specialization, the
3803 // elaborated-type-specifier is ill-formed.
3806 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3809 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3810 }
3811
3812 // Find the canonical type for this type alias template specialization.
3813 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3814 if (Pattern->isInvalidDecl())
3815 return QualType();
3816
3817 // Only substitute for the innermost template argument list.
3818 MultiLevelTemplateArgumentList TemplateArgLists;
3820 /*Final=*/true);
3821 TemplateArgLists.addOuterRetainedLevels(
3822 AliasTemplate->getTemplateParameters()->getDepth());
3823
3826 *this, /*PointOfInstantiation=*/TemplateLoc,
3827 /*Entity=*/AliasTemplate,
3828 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3829
3830 // Diagnose uses of this alias.
3831 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3832
3833 if (Inst.isInvalid())
3834 return QualType();
3835
3836 std::optional<ContextRAII> SavedContext;
3837 if (!AliasTemplate->getDeclContext()->isFileContext())
3838 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3839
3840 CanonType =
3841 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3842 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3843 if (CanonType.isNull()) {
3844 // If this was enable_if and we failed to find the nested type
3845 // within enable_if in a SFINAE context, dig out the specific
3846 // enable_if condition that failed and present that instead.
3848 if (auto DeductionInfo = isSFINAEContext()) {
3849 if (*DeductionInfo &&
3850 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3851 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3852 diag::err_typename_nested_not_found_enable_if &&
3853 TemplateArgs[0].getArgument().getKind()
3855 Expr *FailedCond;
3856 std::string FailedDescription;
3857 std::tie(FailedCond, FailedDescription) =
3858 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3859
3860 // Remove the old SFINAE diagnostic.
3861 PartialDiagnosticAt OldDiag =
3863 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3864
3865 // Add a new SFINAE diagnostic specifying which condition
3866 // failed.
3867 (*DeductionInfo)->addSFINAEDiagnostic(
3868 OldDiag.first,
3869 PDiag(diag::err_typename_nested_not_found_requirement)
3870 << FailedDescription
3871 << FailedCond->getSourceRange());
3872 }
3873 }
3874 }
3875
3876 return QualType();
3877 }
3878 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3879 CanonType = checkBuiltinTemplateIdType(
3880 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3881 } else if (Name.isDependent() ||
3882 TemplateSpecializationType::anyDependentTemplateArguments(
3883 TemplateArgs, CTAI.CanonicalConverted)) {
3884 // This class template specialization is a dependent
3885 // type. Therefore, its canonical type is another class template
3886 // specialization type that contains all of the converted
3887 // arguments in canonical form. This ensures that, e.g., A<T> and
3888 // A<T, T> have identical types when A is declared as:
3889 //
3890 // template<typename T, typename U = T> struct A;
3891 CanonType = Context.getCanonicalTemplateSpecializationType(
3893 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3894 CTAI.CanonicalConverted);
3895 assert(CanonType->isCanonicalUnqualified());
3896
3897 // This might work out to be a current instantiation, in which
3898 // case the canonical type needs to be the InjectedClassNameType.
3899 //
3900 // TODO: in theory this could be a simple hashtable lookup; most
3901 // changes to CurContext don't change the set of current
3902 // instantiations.
3904 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3905 // If we get out to a namespace, we're done.
3906 if (Ctx->isFileContext()) break;
3907
3908 // If this isn't a record, keep looking.
3909 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3910 if (!Record) continue;
3911
3912 // Look for one of the two cases with InjectedClassNameTypes
3913 // and check whether it's the same template.
3915 !Record->getDescribedClassTemplate())
3916 continue;
3917
3918 // Fetch the injected class name type and check whether its
3919 // injected type is equal to the type we just built.
3920 CanQualType ICNT = Context.getCanonicalTagType(Record);
3921 CanQualType Injected =
3922 Record->getCanonicalTemplateSpecializationType(Context);
3923
3924 if (CanonType != Injected)
3925 continue;
3926
3927 // If so, the canonical type of this TST is the injected
3928 // class name type of the record we just found.
3929 CanonType = ICNT;
3930 break;
3931 }
3932 }
3933 } else if (ClassTemplateDecl *ClassTemplate =
3934 dyn_cast<ClassTemplateDecl>(Template)) {
3935 // Find the class template specialization declaration that
3936 // corresponds to these arguments.
3937 void *InsertPos = nullptr;
3939 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3940 if (!Decl) {
3941 // This is the first time we have referenced this class template
3942 // specialization. Create the canonical declaration and add it to
3943 // the set of specializations.
3945 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3946 ClassTemplate->getDeclContext(),
3947 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3948 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3949 CTAI.StrictPackMatch, nullptr);
3950 ClassTemplate->AddSpecialization(Decl, InsertPos);
3951 if (ClassTemplate->isOutOfLine())
3952 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3953 }
3954
3955 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3956 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3957 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3958 if (!Inst.isInvalid()) {
3960 CTAI.CanonicalConverted,
3961 /*Final=*/false);
3962 InstantiateAttrsForDecl(TemplateArgLists,
3963 ClassTemplate->getTemplatedDecl(), Decl);
3964 }
3965 }
3966
3967 // Diagnose uses of this specialization.
3968 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3969
3970 CanonType = Context.getCanonicalTagType(Decl);
3971 assert(isa<RecordType>(CanonType) &&
3972 "type of non-dependent specialization is not a RecordType");
3973 } else {
3974 llvm_unreachable("Unhandled template kind");
3975 }
3976
3977 // Build the fully-sugared type for this class template
3978 // specialization, which refers back to the class template
3979 // specialization we created or found.
3980 return Context.getTemplateSpecializationType(
3981 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3982 CanonType);
3983}
3984
3986 TemplateNameKind &TNK,
3987 SourceLocation NameLoc,
3988 IdentifierInfo *&II) {
3989 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3990
3991 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
3992 assert(ATN && "not an assumed template name");
3993 II = ATN->getDeclName().getAsIdentifierInfo();
3994
3995 if (TemplateName Name =
3996 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
3997 !Name.isNull()) {
3998 // Resolved to a type template name.
3999 ParsedName = TemplateTy::make(Name);
4000 TNK = TNK_Type_template;
4001 }
4002}
4003
4005 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4006 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4007 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4008 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4009 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4010 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4011 ImplicitTypenameContext AllowImplicitTypename) {
4012 if (SS.isInvalid())
4013 return true;
4014
4015 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4016 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4017
4018 // C++ [temp.res]p3:
4019 // A qualified-id that refers to a type and in which the
4020 // nested-name-specifier depends on a template-parameter (14.6.2)
4021 // shall be prefixed by the keyword typename to indicate that the
4022 // qualified-id denotes a type, forming an
4023 // elaborated-type-specifier (7.1.5.3).
4024 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4025 // C++2a relaxes some of those restrictions in [temp.res]p5.
4026 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4027 SS.getScopeRep(), TemplateII);
4029 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4030 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4031 << NNS;
4032 if (!getLangOpts().CPlusPlus20)
4033 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4034 } else
4035 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4036
4037 // FIXME: This is not quite correct recovery as we don't transform SS
4038 // into the corresponding dependent form (and we don't diagnose missing
4039 // 'template' keywords within SS as a result).
4040 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4041 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4042 TemplateArgsIn, RAngleLoc);
4043 }
4044
4045 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4046 // it's not actually allowed to be used as a type in most cases. Because
4047 // we annotate it before we know whether it's valid, we have to check for
4048 // this case here.
4049 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4050 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4051 Diag(TemplateIILoc,
4052 TemplateKWLoc.isInvalid()
4053 ? diag::err_out_of_line_qualified_id_type_names_constructor
4054 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4055 << TemplateII << 0 /*injected-class-name used as template name*/
4056 << 1 /*if any keyword was present, it was 'template'*/;
4057 }
4058 }
4059
4060 // Translate the parser's template argument list in our AST format.
4061 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4062 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4063
4065 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4066 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4067 if (SpecTy.isNull())
4068 return true;
4069
4070 // Build type-source information.
4071 TypeLocBuilder TLB;
4072 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4073 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4074 TemplateIILoc, TemplateArgs);
4075 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4076}
4077
4079 TypeSpecifierType TagSpec,
4080 SourceLocation TagLoc,
4081 CXXScopeSpec &SS,
4082 SourceLocation TemplateKWLoc,
4083 TemplateTy TemplateD,
4084 SourceLocation TemplateLoc,
4085 SourceLocation LAngleLoc,
4086 ASTTemplateArgsPtr TemplateArgsIn,
4087 SourceLocation RAngleLoc) {
4088 if (SS.isInvalid())
4089 return TypeResult(true);
4090
4091 // Translate the parser's template argument list in our AST format.
4092 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4093 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4094
4095 // Determine the tag kind
4099
4101 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4102 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4103 if (Result.isNull())
4104 return TypeResult(true);
4105
4106 // Check the tag kind
4107 if (const RecordType *RT = Result->getAs<RecordType>()) {
4108 RecordDecl *D = RT->getOriginalDecl();
4109
4110 IdentifierInfo *Id = D->getIdentifier();
4111 assert(Id && "templated class must have an identifier");
4112
4114 TagLoc, Id)) {
4115 Diag(TagLoc, diag::err_use_with_wrong_tag)
4116 << Result
4118 Diag(D->getLocation(), diag::note_previous_use);
4119 }
4120 }
4121
4122 // Provide source-location information for the template specialization.
4123 TypeLocBuilder TLB;
4125 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4126 TemplateArgs);
4128}
4129
4130static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4131 NamedDecl *PrevDecl,
4132 SourceLocation Loc,
4134
4136
4138 unsigned Depth,
4139 unsigned Index) {
4140 switch (Arg.getKind()) {
4148 return false;
4149
4151 QualType Type = Arg.getAsType();
4152 const TemplateTypeParmType *TPT =
4153 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4154 return TPT && !Type.hasQualifiers() &&
4155 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4156 }
4157
4159 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4160 if (!DRE || !DRE->getDecl())
4161 return false;
4162 const NonTypeTemplateParmDecl *NTTP =
4163 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4164 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4165 }
4166
4168 const TemplateTemplateParmDecl *TTP =
4169 dyn_cast_or_null<TemplateTemplateParmDecl>(
4171 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4172 }
4173 llvm_unreachable("unexpected kind of template argument");
4174}
4175
4177 TemplateParameterList *SpecParams,
4179 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4180 return false;
4181
4182 unsigned Depth = Params->getDepth();
4183
4184 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4185 TemplateArgument Arg = Args[I];
4186
4187 // If the parameter is a pack expansion, the argument must be a pack
4188 // whose only element is a pack expansion.
4189 if (Params->getParam(I)->isParameterPack()) {
4190 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4191 !Arg.pack_begin()->isPackExpansion())
4192 return false;
4193 Arg = Arg.pack_begin()->getPackExpansionPattern();
4194 }
4195
4196 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4197 return false;
4198
4199 // For NTTPs further specialization is allowed via deduced types, so
4200 // we need to make sure to only reject here if primary template and
4201 // specialization use the same type for the NTTP.
4202 if (auto *SpecNTTP =
4203 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4204 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4205 if (!NTTP || NTTP->getType().getCanonicalType() !=
4206 SpecNTTP->getType().getCanonicalType())
4207 return false;
4208 }
4209 }
4210
4211 return true;
4212}
4213
4214template<typename PartialSpecDecl>
4215static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4216 if (Partial->getDeclContext()->isDependentContext())
4217 return;
4218
4219 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4220 // for non-substitution-failure issues?
4221 TemplateDeductionInfo Info(Partial->getLocation());
4222 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4223 return;
4224
4225 auto *Template = Partial->getSpecializedTemplate();
4226 S.Diag(Partial->getLocation(),
4227 diag::ext_partial_spec_not_more_specialized_than_primary)
4229
4230 if (Info.hasSFINAEDiagnostic()) {
4234 SmallString<128> SFINAEArgString;
4235 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4236 S.Diag(Diag.first,
4237 diag::note_partial_spec_not_more_specialized_than_primary)
4238 << SFINAEArgString;
4239 }
4240
4242 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4243 Template->getAssociatedConstraints(TemplateAC);
4244 Partial->getAssociatedConstraints(PartialAC);
4246 TemplateAC);
4247}
4248
4249static void
4251 const llvm::SmallBitVector &DeducibleParams) {
4252 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4253 if (!DeducibleParams[I]) {
4254 NamedDecl *Param = TemplateParams->getParam(I);
4255 if (Param->getDeclName())
4256 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4257 << Param->getDeclName();
4258 else
4259 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4260 << "(anonymous)";
4261 }
4262 }
4263}
4264
4265
4266template<typename PartialSpecDecl>
4268 PartialSpecDecl *Partial) {
4269 // C++1z [temp.class.spec]p8: (DR1495)
4270 // - The specialization shall be more specialized than the primary
4271 // template (14.5.5.2).
4273
4274 // C++ [temp.class.spec]p8: (DR1315)
4275 // - Each template-parameter shall appear at least once in the
4276 // template-id outside a non-deduced context.
4277 // C++1z [temp.class.spec.match]p3 (P0127R2)
4278 // If the template arguments of a partial specialization cannot be
4279 // deduced because of the structure of its template-parameter-list
4280 // and the template-id, the program is ill-formed.
4281 auto *TemplateParams = Partial->getTemplateParameters();
4282 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4283 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4284 TemplateParams->getDepth(), DeducibleParams);
4285
4286 if (!DeducibleParams.all()) {
4287 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4288 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4290 << (NumNonDeducible > 1)
4291 << SourceRange(Partial->getLocation(),
4292 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4293 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4294 }
4295}
4296
4301
4306
4308 // C++1z [temp.param]p11:
4309 // A template parameter of a deduction guide template that does not have a
4310 // default-argument shall be deducible from the parameter-type-list of the
4311 // deduction guide template.
4312 auto *TemplateParams = TD->getTemplateParameters();
4313 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4314 MarkDeducedTemplateParameters(TD, DeducibleParams);
4315 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4316 // A parameter pack is deducible (to an empty pack).
4317 auto *Param = TemplateParams->getParam(I);
4318 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4319 DeducibleParams[I] = true;
4320 }
4321
4322 if (!DeducibleParams.all()) {
4323 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4324 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4325 << (NumNonDeducible > 1);
4326 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4327 }
4328}
4329
4332 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4334 // D must be variable template id.
4336 "Variable template specialization is declared with a template id.");
4337
4338 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4339 TemplateArgumentListInfo TemplateArgs =
4340 makeTemplateArgumentListInfo(*this, *TemplateId);
4341 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4342 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4343 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4344
4345 TemplateName Name = TemplateId->Template.get();
4346
4347 // The template-id must name a variable template.
4349 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4350 if (!VarTemplate) {
4351 NamedDecl *FnTemplate;
4352 if (auto *OTS = Name.getAsOverloadedTemplate())
4353 FnTemplate = *OTS->begin();
4354 else
4355 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4356 if (FnTemplate)
4357 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4358 << FnTemplate->getDeclName();
4359 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4361 }
4362
4363 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4364 auto Message = DSA->getMessage();
4365 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4366 << VarTemplate << !Message.empty() << Message;
4367 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4368 }
4369
4370 // Check for unexpanded parameter packs in any of the template arguments.
4371 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4372 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4376 return true;
4377
4378 // Check that the template argument list is well-formed for this
4379 // template.
4381 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4382 /*DefaultArgs=*/{},
4383 /*PartialTemplateArgs=*/false, CTAI,
4384 /*UpdateArgsWithConversions=*/true))
4385 return true;
4386
4387 // Find the variable template (partial) specialization declaration that
4388 // corresponds to these arguments.
4391 TemplateArgs.size(),
4392 CTAI.CanonicalConverted))
4393 return true;
4394
4395 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4396 // we also do them during instantiation.
4397 if (!Name.isDependent() &&
4398 !TemplateSpecializationType::anyDependentTemplateArguments(
4399 TemplateArgs, CTAI.CanonicalConverted)) {
4400 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4401 << VarTemplate->getDeclName();
4403 }
4404
4405 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4406 TemplateParams, CTAI.CanonicalConverted) &&
4407 (!Context.getLangOpts().CPlusPlus20 ||
4408 !TemplateParams->hasAssociatedConstraints())) {
4409 // C++ [temp.class.spec]p9b3:
4410 //
4411 // -- The argument list of the specialization shall not be identical
4412 // to the implicit argument list of the primary template.
4413 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4414 << /*variable template*/ 1
4415 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4416 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4417 // FIXME: Recover from this by treating the declaration as a
4418 // redeclaration of the primary template.
4419 return true;
4420 }
4421 }
4422
4423 void *InsertPos = nullptr;
4424 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4425
4427 PrevDecl = VarTemplate->findPartialSpecialization(
4428 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4429 else
4430 PrevDecl =
4431 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4432
4434
4435 // Check whether we can declare a variable template specialization in
4436 // the current scope.
4437 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4438 TemplateNameLoc,
4440 return true;
4441
4442 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4443 // Since the only prior variable template specialization with these
4444 // arguments was referenced but not declared, reuse that
4445 // declaration node as our own, updating its source location and
4446 // the list of outer template parameters to reflect our new declaration.
4447 Specialization = PrevDecl;
4448 Specialization->setLocation(TemplateNameLoc);
4449 PrevDecl = nullptr;
4450 } else if (IsPartialSpecialization) {
4451 // Create a new class template partial specialization declaration node.
4453 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4456 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4457 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4458 CTAI.CanonicalConverted);
4459 Partial->setTemplateArgsAsWritten(TemplateArgs);
4460
4461 if (!PrevPartial)
4462 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4463 Specialization = Partial;
4464
4465 // If we are providing an explicit specialization of a member variable
4466 // template specialization, make a note of that.
4467 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4468 PrevPartial->setMemberSpecialization();
4469
4471 } else {
4472 // Create a new class template specialization declaration node for
4473 // this explicit specialization or friend declaration.
4475 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4476 VarTemplate, DI->getType(), DI, SC, CTAI.CanonicalConverted);
4477 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4478
4479 if (!PrevDecl)
4480 VarTemplate->AddSpecialization(Specialization, InsertPos);
4481 }
4482
4483 // C++ [temp.expl.spec]p6:
4484 // If a template, a member template or the member of a class template is
4485 // explicitly specialized then that specialization shall be declared
4486 // before the first use of that specialization that would cause an implicit
4487 // instantiation to take place, in every translation unit in which such a
4488 // use occurs; no diagnostic is required.
4489 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4490 bool Okay = false;
4491 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4492 // Is there any previous explicit specialization declaration?
4494 Okay = true;
4495 break;
4496 }
4497 }
4498
4499 if (!Okay) {
4500 SourceRange Range(TemplateNameLoc, RAngleLoc);
4501 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4502 << Name << Range;
4503
4504 Diag(PrevDecl->getPointOfInstantiation(),
4505 diag::note_instantiation_required_here)
4506 << (PrevDecl->getTemplateSpecializationKind() !=
4508 return true;
4509 }
4510 }
4511
4512 Specialization->setLexicalDeclContext(CurContext);
4513
4514 // Add the specialization into its lexical context, so that it can
4515 // be seen when iterating through the list of declarations in that
4516 // context. However, specializations are not found by name lookup.
4517 CurContext->addDecl(Specialization);
4518
4519 // Note that this is an explicit specialization.
4520 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4521
4522 Previous.clear();
4523 if (PrevDecl)
4524 Previous.addDecl(PrevDecl);
4525 else if (Specialization->isStaticDataMember() &&
4526 Specialization->isOutOfLine())
4527 Specialization->setAccess(VarTemplate->getAccess());
4528
4529 return Specialization;
4530}
4531
4532namespace {
4533/// A partial specialization whose template arguments have matched
4534/// a given template-id.
4535struct PartialSpecMatchResult {
4538};
4539
4540// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4541// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4542static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4543 if (Var->getName() != "format_kind" ||
4544 !Var->getDeclContext()->isStdNamespace())
4545 return false;
4546
4547 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4548 // release in which users can access std::format_kind.
4549 // We can use 20250520 as the final date, see the following commits.
4550 // GCC releases/gcc-15 branch:
4551 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4552 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4553 // GCC master branch:
4554 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4555 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4556 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4557}
4558} // end anonymous namespace
4559
4562 SourceLocation TemplateNameLoc,
4563 const TemplateArgumentListInfo &TemplateArgs,
4564 bool SetWrittenArgs) {
4565 assert(Template && "A variable template id without template?");
4566
4567 // Check that the template argument list is well-formed for this template.
4570 Template, TemplateNameLoc,
4571 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4572 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4573 /*UpdateArgsWithConversions=*/true))
4574 return true;
4575
4576 // Produce a placeholder value if the specialization is dependent.
4577 if (Template->getDeclContext()->isDependentContext() ||
4578 TemplateSpecializationType::anyDependentTemplateArguments(
4579 TemplateArgs, CTAI.CanonicalConverted)) {
4580 if (ParsingInitForAutoVars.empty())
4581 return DeclResult();
4582
4583 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4584 const TemplateArgument &Arg2) {
4585 return Context.isSameTemplateArgument(Arg1, Arg2);
4586 };
4587
4588 if (VarDecl *Var = Template->getTemplatedDecl();
4589 ParsingInitForAutoVars.count(Var) &&
4590 // See comments on this function definition
4591 !IsLibstdcxxStdFormatKind(PP, Var) &&
4592 llvm::equal(
4593 CTAI.CanonicalConverted,
4594 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4595 IsSameTemplateArg)) {
4596 Diag(TemplateNameLoc,
4597 diag::err_auto_variable_cannot_appear_in_own_initializer)
4598 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4599 return true;
4600 }
4601
4603 Template->getPartialSpecializations(PartialSpecs);
4604 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4605 if (ParsingInitForAutoVars.count(Partial) &&
4606 llvm::equal(CTAI.CanonicalConverted,
4607 Partial->getTemplateArgs().asArray(),
4608 IsSameTemplateArg)) {
4609 Diag(TemplateNameLoc,
4610 diag::err_auto_variable_cannot_appear_in_own_initializer)
4611 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4612 << Partial->getType();
4613 return true;
4614 }
4615
4616 return DeclResult();
4617 }
4618
4619 // Find the variable template specialization declaration that
4620 // corresponds to these arguments.
4621 void *InsertPos = nullptr;
4623 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4624 checkSpecializationReachability(TemplateNameLoc, Spec);
4625 if (Spec->getType()->isUndeducedType()) {
4626 if (ParsingInitForAutoVars.count(Spec))
4627 Diag(TemplateNameLoc,
4628 diag::err_auto_variable_cannot_appear_in_own_initializer)
4629 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4630 << Spec->getType();
4631 else
4632 // We are substituting the initializer of this variable template
4633 // specialization.
4634 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4635 << Spec << Spec->getType();
4636
4637 return true;
4638 }
4639 // If we already have a variable template specialization, return it.
4640 return Spec;
4641 }
4642
4643 // This is the first time we have referenced this variable template
4644 // specialization. Create the canonical declaration and add it to
4645 // the set of specializations, based on the closest partial specialization
4646 // that it represents. That is,
4647 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4648 const TemplateArgumentList *PartialSpecArgs = nullptr;
4649 bool AmbiguousPartialSpec = false;
4650 typedef PartialSpecMatchResult MatchResult;
4652 SourceLocation PointOfInstantiation = TemplateNameLoc;
4653 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4654 /*ForTakingAddress=*/false);
4655
4656 // 1. Attempt to find the closest partial specialization that this
4657 // specializes, if any.
4658 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4659 // Perhaps better after unification of DeduceTemplateArguments() and
4660 // getMoreSpecializedPartialSpecialization().
4662 Template->getPartialSpecializations(PartialSpecs);
4663
4664 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4665 // C++ [temp.spec.partial.member]p2:
4666 // If the primary member template is explicitly specialized for a given
4667 // (implicit) specialization of the enclosing class template, the partial
4668 // specializations of the member template are ignored for this
4669 // specialization of the enclosing class template. If a partial
4670 // specialization of the member template is explicitly specialized for a
4671 // given (implicit) specialization of the enclosing class template, the
4672 // primary member template and its other partial specializations are still
4673 // considered for this specialization of the enclosing class template.
4674 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4675 !Partial->getMostRecentDecl()->isMemberSpecialization())
4676 continue;
4677
4678 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4679
4681 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4683 // Store the failed-deduction information for use in diagnostics, later.
4684 // TODO: Actually use the failed-deduction info?
4685 FailedCandidates.addCandidate().set(
4688 (void)Result;
4689 } else {
4690 Matched.push_back(PartialSpecMatchResult());
4691 Matched.back().Partial = Partial;
4692 Matched.back().Args = Info.takeSugared();
4693 }
4694 }
4695
4696 if (Matched.size() >= 1) {
4697 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4698 if (Matched.size() == 1) {
4699 // -- If exactly one matching specialization is found, the
4700 // instantiation is generated from that specialization.
4701 // We don't need to do anything for this.
4702 } else {
4703 // -- If more than one matching specialization is found, the
4704 // partial order rules (14.5.4.2) are used to determine
4705 // whether one of the specializations is more specialized
4706 // than the others. If none of the specializations is more
4707 // specialized than all of the other matching
4708 // specializations, then the use of the variable template is
4709 // ambiguous and the program is ill-formed.
4710 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4711 PEnd = Matched.end();
4712 P != PEnd; ++P) {
4713 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4714 PointOfInstantiation) ==
4715 P->Partial)
4716 Best = P;
4717 }
4718
4719 // Determine if the best partial specialization is more specialized than
4720 // the others.
4721 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4722 PEnd = Matched.end();
4723 P != PEnd; ++P) {
4725 P->Partial, Best->Partial,
4726 PointOfInstantiation) != Best->Partial) {
4727 AmbiguousPartialSpec = true;
4728 break;
4729 }
4730 }
4731 }
4732
4733 // Instantiate using the best variable template partial specialization.
4734 InstantiationPattern = Best->Partial;
4735 PartialSpecArgs = Best->Args;
4736 } else {
4737 // -- If no match is found, the instantiation is generated
4738 // from the primary template.
4739 // InstantiationPattern = Template->getTemplatedDecl();
4740 }
4741
4742 // 2. Create the canonical declaration.
4743 // Note that we do not instantiate a definition until we see an odr-use
4744 // in DoMarkVarDeclReferenced().
4745 // FIXME: LateAttrs et al.?
4747 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4748 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4749 if (!Decl)
4750 return true;
4751 if (SetWrittenArgs)
4752 Decl->setTemplateArgsAsWritten(TemplateArgs);
4753
4754 if (AmbiguousPartialSpec) {
4755 // Partial ordering did not produce a clear winner. Complain.
4757 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4758 << Decl;
4759
4760 // Print the matching partial specializations.
4761 for (MatchResult P : Matched)
4762 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4763 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4764 *P.Args);
4765 return true;
4766 }
4767
4769 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4770 Decl->setInstantiationOf(D, PartialSpecArgs);
4771
4772 checkSpecializationReachability(TemplateNameLoc, Decl);
4773
4774 assert(Decl && "No variable template specialization?");
4775 return Decl;
4776}
4777
4779 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4780 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4781 const TemplateArgumentListInfo *TemplateArgs) {
4782
4783 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4784 *TemplateArgs, /*SetWrittenArgs=*/false);
4785 if (Decl.isInvalid())
4786 return ExprError();
4787
4788 if (!Decl.get())
4789 return ExprResult();
4790
4791 VarDecl *Var = cast<VarDecl>(Decl.get());
4794 NameInfo.getLoc());
4795
4796 // Build an ordinary singleton decl ref.
4797 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4798}
4799
4801 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4803 const TemplateArgumentListInfo *TemplateArgs) {
4804 assert(Template && "A variable template id without template?");
4805
4806 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4807 Template->templateParameterKind() !=
4809 return ExprResult();
4810
4811 // Check that the template argument list is well-formed for this template.
4814 Template, TemplateLoc,
4815 // FIXME: TemplateArgs will not be modified because
4816 // UpdateArgsWithConversions is false, however, we should
4817 // CheckTemplateArgumentList to be const-correct.
4818 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4819 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4820 /*UpdateArgsWithConversions=*/false))
4821 return true;
4822
4824 R.addDecl(Template);
4825
4826 // FIXME: We model references to variable template and concept parameters
4827 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4828 // data, can generally be used in the same places and work the same way.
4829 // However, it might be cleaner to use a dedicated AST node in the long run.
4832 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4833 /*KnownDependent=*/false,
4834 /*KnownInstantiationDependent=*/false);
4835}
4836
4838 SourceLocation Loc) {
4839 Diag(Loc, diag::err_template_missing_args)
4840 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4841 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4842 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4843 }
4844}
4845
4847 bool TemplateKeyword,
4848 TemplateDecl *TD,
4849 SourceLocation Loc) {
4850 TemplateName Name = Context.getQualifiedTemplateName(
4851 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4853}
4854
4856 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4857 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4858 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4859 bool DoCheckConstraintSatisfaction) {
4860 assert(NamedConcept && "A concept template id without a template?");
4861
4862 if (NamedConcept->isInvalidDecl())
4863 return ExprError();
4864
4867 NamedConcept, ConceptNameInfo.getLoc(),
4868 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4869 /*DefaultArgs=*/{},
4870 /*PartialTemplateArgs=*/false, CTAI,
4871 /*UpdateArgsWithConversions=*/false))
4872 return ExprError();
4873
4874 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4875
4876 // There's a bug with CTAI.CanonicalConverted.
4877 // If the template argument contains a DependentDecltypeType that includes a
4878 // TypeAliasType, and the same written type had occurred previously in the
4879 // source, then the DependentDecltypeType would be canonicalized to that
4880 // previous type which would mess up the substitution.
4881 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4883 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4884 CTAI.SugaredConverted);
4885 ConstraintSatisfaction Satisfaction;
4886 bool AreArgsDependent =
4887 TemplateSpecializationType::anyDependentTemplateArguments(
4888 *TemplateArgs, CTAI.SugaredConverted);
4889 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4890 /*Final=*/false);
4892 Context,
4894 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4896
4897 bool Error = false;
4898 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4899 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4900 DoCheckConstraintSatisfaction) {
4901
4903
4906
4908 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4909 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4910 TemplateArgs->getRAngleLoc()),
4911 Satisfaction, CL);
4912 Satisfaction.ContainsErrors = Error;
4913 }
4914
4915 if (Error)
4916 return ExprError();
4917
4919 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4920}
4921
4923 SourceLocation TemplateKWLoc,
4924 LookupResult &R,
4925 bool RequiresADL,
4926 const TemplateArgumentListInfo *TemplateArgs) {
4927 // FIXME: Can we do any checking at this point? I guess we could check the
4928 // template arguments that we have against the template name, if the template
4929 // name refers to a single template. That's not a terribly common case,
4930 // though.
4931 // foo<int> could identify a single function unambiguously
4932 // This approach does NOT work, since f<int>(1);
4933 // gets resolved prior to resorting to overload resolution
4934 // i.e., template<class T> void f(double);
4935 // vs template<class T, class U> void f(U);
4936
4937 // These should be filtered out by our callers.
4938 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4939
4940 // Non-function templates require a template argument list.
4941 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4942 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4944 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4945 return ExprError();
4946 }
4947 }
4948 bool KnownDependent = false;
4949 // In C++1y, check variable template ids.
4950 if (R.getAsSingle<VarTemplateDecl>()) {
4953 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4954 if (Res.isInvalid() || Res.isUsable())
4955 return Res;
4956 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4957 KnownDependent = true;
4958 }
4959
4960 // We don't want lookup warnings at this point.
4962
4963 if (R.getAsSingle<ConceptDecl>()) {
4964 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4966 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4967 }
4968
4969 // Check variable template ids (C++17) and concept template parameters
4970 // (C++26).
4975 TemplateKWLoc, TemplateArgs);
4976
4977 // Function templates
4980 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4981 R.begin(), R.end(), KnownDependent,
4982 /*KnownInstantiationDependent=*/false);
4983 // Model the templates with UnresolvedTemplateTy. The expression should then
4984 // either be transformed in an instantiation or be diagnosed in
4985 // CheckPlaceholderExpr.
4986 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4988 ULE->setType(Context.UnresolvedTemplateTy);
4989
4990 return ULE;
4991}
4992
4994 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4995 const DeclarationNameInfo &NameInfo,
4996 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4997 assert(TemplateArgs || TemplateKWLoc.isValid());
4998
4999 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5000 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5001 /*EnteringContext=*/false, TemplateKWLoc))
5002 return ExprError();
5003
5004 if (R.isAmbiguous())
5005 return ExprError();
5006
5008 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5009
5010 if (R.empty()) {
5012 Diag(NameInfo.getLoc(), diag::err_no_member)
5013 << NameInfo.getName() << DC << SS.getRange();
5014 return ExprError();
5015 }
5016
5017 // If necessary, build an implicit class member access.
5018 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5019 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5020 /*S=*/nullptr);
5021
5022 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5023}
5024
5026 CXXScopeSpec &SS,
5027 SourceLocation TemplateKWLoc,
5028 const UnqualifiedId &Name,
5029 ParsedType ObjectType,
5030 bool EnteringContext,
5032 bool AllowInjectedClassName) {
5033 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5034 Diag(TemplateKWLoc,
5036 diag::warn_cxx98_compat_template_outside_of_template :
5037 diag::ext_template_outside_of_template)
5038 << FixItHint::CreateRemoval(TemplateKWLoc);
5039
5040 if (SS.isInvalid())
5041 return TNK_Non_template;
5042
5043 // Figure out where isTemplateName is going to look.
5044 DeclContext *LookupCtx = nullptr;
5045 if (SS.isNotEmpty())
5046 LookupCtx = computeDeclContext(SS, EnteringContext);
5047 else if (ObjectType)
5048 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5049
5050 // C++0x [temp.names]p5:
5051 // If a name prefixed by the keyword template is not the name of
5052 // a template, the program is ill-formed. [Note: the keyword
5053 // template may not be applied to non-template members of class
5054 // templates. -end note ] [ Note: as is the case with the
5055 // typename prefix, the template prefix is allowed in cases
5056 // where it is not strictly necessary; i.e., when the
5057 // nested-name-specifier or the expression on the left of the ->
5058 // or . is not dependent on a template-parameter, or the use
5059 // does not appear in the scope of a template. -end note]
5060 //
5061 // Note: C++03 was more strict here, because it banned the use of
5062 // the "template" keyword prior to a template-name that was not a
5063 // dependent name. C++ DR468 relaxed this requirement (the
5064 // "template" keyword is now permitted). We follow the C++0x
5065 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5066 bool MemberOfUnknownSpecialization;
5067 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5068 ObjectType, EnteringContext, Result,
5069 MemberOfUnknownSpecialization);
5070 if (TNK != TNK_Non_template) {
5071 // We resolved this to a (non-dependent) template name. Return it.
5072 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5073 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5075 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5076 // C++14 [class.qual]p2:
5077 // In a lookup in which function names are not ignored and the
5078 // nested-name-specifier nominates a class C, if the name specified
5079 // [...] is the injected-class-name of C, [...] the name is instead
5080 // considered to name the constructor
5081 //
5082 // We don't get here if naming the constructor would be valid, so we
5083 // just reject immediately and recover by treating the
5084 // injected-class-name as naming the template.
5085 Diag(Name.getBeginLoc(),
5086 diag::ext_out_of_line_qualified_id_type_names_constructor)
5087 << Name.Identifier
5088 << 0 /*injected-class-name used as template name*/
5089 << TemplateKWLoc.isValid();
5090 }
5091 return TNK;
5092 }
5093
5094 if (!MemberOfUnknownSpecialization) {
5095 // Didn't find a template name, and the lookup wasn't dependent.
5096 // Do the lookup again to determine if this is a "nothing found" case or
5097 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5098 // need to do this.
5100 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5102 // Tell LookupTemplateName that we require a template so that it diagnoses
5103 // cases where it finds a non-template.
5104 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5105 ? RequiredTemplateKind(TemplateKWLoc)
5107 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5108 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5109 !R.isAmbiguous()) {
5110 if (LookupCtx)
5111 Diag(Name.getBeginLoc(), diag::err_no_member)
5112 << DNI.getName() << LookupCtx << SS.getRange();
5113 else
5114 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5115 << DNI.getName() << SS.getRange();
5116 }
5117 return TNK_Non_template;
5118 }
5119
5120 NestedNameSpecifier Qualifier = SS.getScopeRep();
5121
5122 switch (Name.getKind()) {
5124 Result = TemplateTy::make(Context.getDependentTemplateName(
5125 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5127
5129 Result = TemplateTy::make(Context.getDependentTemplateName(
5130 {Qualifier, Name.OperatorFunctionId.Operator,
5131 TemplateKWLoc.isValid()}));
5132 return TNK_Function_template;
5133
5135 // This is a kind of template name, but can never occur in a dependent
5136 // scope (literal operators can only be declared at namespace scope).
5137 break;
5138
5139 default:
5140 break;
5141 }
5142
5143 // This name cannot possibly name a dependent template. Diagnose this now
5144 // rather than building a dependent template name that can never be valid.
5145 Diag(Name.getBeginLoc(),
5146 diag::err_template_kw_refers_to_dependent_non_template)
5148 << TemplateKWLoc.isValid() << TemplateKWLoc;
5149 return TNK_Non_template;
5150}
5151
5154 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5155 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5156 const TemplateArgument &Arg = AL.getArgument();
5158 TypeSourceInfo *TSI = nullptr;
5159
5160 // Check template type parameter.
5161 switch(Arg.getKind()) {
5163 // C++ [temp.arg.type]p1:
5164 // A template-argument for a template-parameter which is a
5165 // type shall be a type-id.
5166 ArgType = Arg.getAsType();
5167 TSI = AL.getTypeSourceInfo();
5168 break;
5171 // We have a template type parameter but the template argument
5172 // is a template without any arguments.
5173 SourceRange SR = AL.getSourceRange();
5176 return true;
5177 }
5179 // We have a template type parameter but the template argument is an
5180 // expression; see if maybe it is missing the "typename" keyword.
5181 CXXScopeSpec SS;
5182 DeclarationNameInfo NameInfo;
5183
5184 if (DependentScopeDeclRefExpr *ArgExpr =
5185 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5186 SS.Adopt(ArgExpr->getQualifierLoc());
5187 NameInfo = ArgExpr->getNameInfo();
5188 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5189 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5190 if (ArgExpr->isImplicitAccess()) {
5191 SS.Adopt(ArgExpr->getQualifierLoc());
5192 NameInfo = ArgExpr->getMemberNameInfo();
5193 }
5194 }
5195
5196 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5197 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5198 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5199
5200 if (Result.getAsSingle<TypeDecl>() ||
5201 Result.wasNotFoundInCurrentInstantiation()) {
5202 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5203 // Suggest that the user add 'typename' before the NNS.
5205 Diag(Loc, getLangOpts().MSVCCompat
5206 ? diag::ext_ms_template_type_arg_missing_typename
5207 : diag::err_template_arg_must_be_type_suggest)
5208 << FixItHint::CreateInsertion(Loc, "typename ");
5210
5211 // Recover by synthesizing a type using the location information that we
5212 // already have.
5213 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5214 SS.getScopeRep(), II);
5215 TypeLocBuilder TLB;
5217 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5219 TL.setNameLoc(NameInfo.getLoc());
5220 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5221
5222 // Overwrite our input TemplateArgumentLoc so that we can recover
5223 // properly.
5226
5227 break;
5228 }
5229 }
5230 // fallthrough
5231 [[fallthrough]];
5232 }
5233 default: {
5234 // We allow instantiating a template with template argument packs when
5235 // building deduction guides or mapping constraint template parameters.
5236 if (Arg.getKind() == TemplateArgument::Pack &&
5237 (CodeSynthesisContexts.back().Kind ==
5240 SugaredConverted.push_back(Arg);
5241 CanonicalConverted.push_back(Arg);
5242 return false;
5243 }
5244 // We have a template type parameter but the template argument
5245 // is not a type.
5246 SourceRange SR = AL.getSourceRange();
5247 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5249
5250 return true;
5251 }
5252 }
5253
5254 if (CheckTemplateArgument(TSI))
5255 return true;
5256
5257 // Objective-C ARC:
5258 // If an explicitly-specified template argument type is a lifetime type
5259 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5260 if (getLangOpts().ObjCAutoRefCount &&
5261 ArgType->isObjCLifetimeType() &&
5262 !ArgType.getObjCLifetime()) {
5263 Qualifiers Qs;
5265 ArgType = Context.getQualifiedType(ArgType, Qs);
5266 }
5267
5268 SugaredConverted.push_back(TemplateArgument(ArgType));
5269 CanonicalConverted.push_back(
5270 TemplateArgument(Context.getCanonicalType(ArgType)));
5271 return false;
5272}
5273
5274/// Substitute template arguments into the default template argument for
5275/// the given template type parameter.
5276///
5277/// \param SemaRef the semantic analysis object for which we are performing
5278/// the substitution.
5279///
5280/// \param Template the template that we are synthesizing template arguments
5281/// for.
5282///
5283/// \param TemplateLoc the location of the template name that started the
5284/// template-id we are checking.
5285///
5286/// \param RAngleLoc the location of the right angle bracket ('>') that
5287/// terminates the template-id.
5288///
5289/// \param Param the template template parameter whose default we are
5290/// substituting into.
5291///
5292/// \param Converted the list of template arguments provided for template
5293/// parameters that precede \p Param in the template parameter list.
5294///
5295/// \param Output the resulting substituted template argument.
5296///
5297/// \returns true if an error occurred.
5299 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5300 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5301 ArrayRef<TemplateArgument> SugaredConverted,
5302 ArrayRef<TemplateArgument> CanonicalConverted,
5303 TemplateArgumentLoc &Output) {
5304 Output = Param->getDefaultArgument();
5305
5306 // If the argument type is dependent, instantiate it now based
5307 // on the previously-computed template arguments.
5308 if (Output.getArgument().isInstantiationDependent()) {
5309 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5310 SugaredConverted,
5311 SourceRange(TemplateLoc, RAngleLoc));
5312 if (Inst.isInvalid())
5313 return true;
5314
5315 // Only substitute for the innermost template argument list.
5316 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5317 /*Final=*/true);
5318 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5319 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5320
5321 bool ForLambdaCallOperator = false;
5322 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5323 ForLambdaCallOperator = Rec->isLambda();
5324 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5325 !ForLambdaCallOperator);
5326
5327 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5328 Param->getDefaultArgumentLoc(),
5329 Param->getDeclName()))
5330 return true;
5331 }
5332
5333 return false;
5334}
5335
5336/// Substitute template arguments into the default template argument for
5337/// the given non-type template parameter.
5338///
5339/// \param SemaRef the semantic analysis object for which we are performing
5340/// the substitution.
5341///
5342/// \param Template the template that we are synthesizing template arguments
5343/// for.
5344///
5345/// \param TemplateLoc the location of the template name that started the
5346/// template-id we are checking.
5347///
5348/// \param RAngleLoc the location of the right angle bracket ('>') that
5349/// terminates the template-id.
5350///
5351/// \param Param the non-type template parameter whose default we are
5352/// substituting into.
5353///
5354/// \param Converted the list of template arguments provided for template
5355/// parameters that precede \p Param in the template parameter list.
5356///
5357/// \returns the substituted template argument, or NULL if an error occurred.
5359 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5360 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5361 ArrayRef<TemplateArgument> SugaredConverted,
5362 ArrayRef<TemplateArgument> CanonicalConverted,
5363 TemplateArgumentLoc &Output) {
5364 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5365 SugaredConverted,
5366 SourceRange(TemplateLoc, RAngleLoc));
5367 if (Inst.isInvalid())
5368 return true;
5369
5370 // Only substitute for the innermost template argument list.
5371 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5372 /*Final=*/true);
5373 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5374 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5375
5376 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5377 EnterExpressionEvaluationContext ConstantEvaluated(
5379 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5380 TemplateArgLists, Output);
5381}
5382
5383/// Substitute template arguments into the default template argument for
5384/// the given template template parameter.
5385///
5386/// \param SemaRef the semantic analysis object for which we are performing
5387/// the substitution.
5388///
5389/// \param Template the template that we are synthesizing template arguments
5390/// for.
5391///
5392/// \param TemplateLoc the location of the template name that started the
5393/// template-id we are checking.
5394///
5395/// \param RAngleLoc the location of the right angle bracket ('>') that
5396/// terminates the template-id.
5397///
5398/// \param Param the template template parameter whose default we are
5399/// substituting into.
5400///
5401/// \param Converted the list of template arguments provided for template
5402/// parameters that precede \p Param in the template parameter list.
5403///
5404/// \param QualifierLoc Will be set to the nested-name-specifier (with
5405/// source-location information) that precedes the template name.
5406///
5407/// \returns the substituted template argument, or NULL if an error occurred.
5409 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5410 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5412 ArrayRef<TemplateArgument> SugaredConverted,
5413 ArrayRef<TemplateArgument> CanonicalConverted,
5414 NestedNameSpecifierLoc &QualifierLoc) {
5416 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5417 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5418 if (Inst.isInvalid())
5419 return TemplateName();
5420
5421 // Only substitute for the innermost template argument list.
5422 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5423 /*Final=*/true);
5424 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5425 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5426
5427 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5428
5429 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5430 QualifierLoc = A.getTemplateQualifierLoc();
5431 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5433 A.getTemplateNameLoc(), TemplateArgLists);
5434}
5435
5437 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5438 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5439 ArrayRef<TemplateArgument> SugaredConverted,
5440 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5441 HasDefaultArg = false;
5442
5443 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5444 if (!hasReachableDefaultArgument(TypeParm))
5445 return TemplateArgumentLoc();
5446
5447 HasDefaultArg = true;
5448 TemplateArgumentLoc Output;
5449 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5450 RAngleLoc, TypeParm, SugaredConverted,
5451 CanonicalConverted, Output))
5452 return TemplateArgumentLoc();
5453 return Output;
5454 }
5455
5456 if (NonTypeTemplateParmDecl *NonTypeParm
5457 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5458 if (!hasReachableDefaultArgument(NonTypeParm))
5459 return TemplateArgumentLoc();
5460
5461 HasDefaultArg = true;
5462 TemplateArgumentLoc Output;
5463 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5464 RAngleLoc, NonTypeParm, SugaredConverted,
5465 CanonicalConverted, Output))
5466 return TemplateArgumentLoc();
5467 return Output;
5468 }
5469
5470 TemplateTemplateParmDecl *TempTempParm
5472 if (!hasReachableDefaultArgument(TempTempParm))
5473 return TemplateArgumentLoc();
5474
5475 HasDefaultArg = true;
5476 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5477 NestedNameSpecifierLoc QualifierLoc;
5479 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5480 SugaredConverted, CanonicalConverted, QualifierLoc);
5481 if (TName.isNull())
5482 return TemplateArgumentLoc();
5483
5484 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5485 QualifierLoc, A.getTemplateNameLoc());
5486}
5487
5488/// Convert a template-argument that we parsed as a type into a template, if
5489/// possible. C++ permits injected-class-names to perform dual service as
5490/// template template arguments and as template type arguments.
5493 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5494 if (!TagLoc)
5495 return TemplateArgumentLoc();
5496
5497 // If this type was written as an injected-class-name, it can be used as a
5498 // template template argument.
5499 // If this type was written as an injected-class-name, it may have been
5500 // converted to a RecordType during instantiation. If the RecordType is
5501 // *not* wrapped in a TemplateSpecializationType and denotes a class
5502 // template specialization, it must have come from an injected-class-name.
5503
5504 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5505 if (Name.isNull())
5506 return TemplateArgumentLoc();
5507
5508 return TemplateArgumentLoc(Context, Name,
5509 /*TemplateKWLoc=*/SourceLocation(),
5510 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5511}
5512
5515 SourceLocation TemplateLoc,
5516 SourceLocation RAngleLoc,
5517 unsigned ArgumentPackIndex,
5520 // Check template type parameters.
5521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5522 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5523 CTAI.CanonicalConverted);
5524
5525 const TemplateArgument &Arg = ArgLoc.getArgument();
5526 // Check non-type template parameters.
5527 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5528 // Do substitution on the type of the non-type template parameter
5529 // with the template arguments we've seen thus far. But if the
5530 // template has a dependent context then we cannot substitute yet.
5531 QualType NTTPType = NTTP->getType();
5532 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5533 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5534
5535 if (NTTPType->isInstantiationDependentType()) {
5536 // Do substitution on the type of the non-type template parameter.
5537 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5538 CTAI.SugaredConverted,
5539 SourceRange(TemplateLoc, RAngleLoc));
5540 if (Inst.isInvalid())
5541 return true;
5542
5544 /*Final=*/true);
5545 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5546 // If the parameter is a pack expansion, expand this slice of the pack.
5547 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5548 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5549 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5550 NTTP->getDeclName());
5551 } else {
5552 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5553 NTTP->getDeclName());
5554 }
5555
5556 // If that worked, check the non-type template parameter type
5557 // for validity.
5558 if (!NTTPType.isNull())
5559 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5560 NTTP->getLocation());
5561 if (NTTPType.isNull())
5562 return true;
5563 }
5564
5565 auto checkExpr = [&](Expr *E) -> Expr * {
5566 TemplateArgument SugaredResult, CanonicalResult;
5567 unsigned CurSFINAEErrors = NumSFINAEErrors;
5569 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5570 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5571 // If the current template argument causes an error, give up now.
5572 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5573 return nullptr;
5574 CTAI.SugaredConverted.push_back(SugaredResult);
5575 CTAI.CanonicalConverted.push_back(CanonicalResult);
5576 return Res.get();
5577 };
5578
5579 switch (Arg.getKind()) {
5581 llvm_unreachable("Should never see a NULL template argument here");
5582
5584 Expr *E = Arg.getAsExpr();
5585 Expr *R = checkExpr(E);
5586 if (!R)
5587 return true;
5588 // If the resulting expression is new, then use it in place of the
5589 // old expression in the template argument.
5590 if (R != E) {
5591 TemplateArgument TA(R, /*IsCanonical=*/false);
5592 ArgLoc = TemplateArgumentLoc(TA, R);
5593 }
5594 break;
5595 }
5596
5597 // As for the converted NTTP kinds, they still might need another
5598 // conversion, as the new corresponding parameter might be different.
5599 // Ideally, we would always perform substitution starting with sugared types
5600 // and never need these, as we would still have expressions. Since these are
5601 // needed so rarely, it's probably a better tradeoff to just convert them
5602 // back to expressions.
5607 // FIXME: StructuralValue is untested here.
5608 ExprResult R =
5610 assert(R.isUsable());
5611 if (!checkExpr(R.get()))
5612 return true;
5613 break;
5614 }
5615
5618 // We were given a template template argument. It may not be ill-formed;
5619 // see below.
5622 // We have a template argument such as \c T::template X, which we
5623 // parsed as a template template argument. However, since we now
5624 // know that we need a non-type template argument, convert this
5625 // template name into an expression.
5626
5627 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5628 ArgLoc.getTemplateNameLoc());
5629
5630 CXXScopeSpec SS;
5631 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5632 // FIXME: the template-template arg was a DependentTemplateName,
5633 // so it was provided with a template keyword. However, its source
5634 // location is not stored in the template argument structure.
5635 SourceLocation TemplateKWLoc;
5637 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5638 nullptr);
5639
5640 // If we parsed the template argument as a pack expansion, create a
5641 // pack expansion expression.
5644 if (E.isInvalid())
5645 return true;
5646 }
5647
5648 TemplateArgument SugaredResult, CanonicalResult;
5650 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5651 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5652 if (E.isInvalid())
5653 return true;
5654
5655 CTAI.SugaredConverted.push_back(SugaredResult);
5656 CTAI.CanonicalConverted.push_back(CanonicalResult);
5657 break;
5658 }
5659
5660 // We have a template argument that actually does refer to a class
5661 // template, alias template, or template template parameter, and
5662 // therefore cannot be a non-type template argument.
5663 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5664 << ArgLoc.getSourceRange();
5666
5667 return true;
5668
5670 // We have a non-type template parameter but the template
5671 // argument is a type.
5672
5673 // C++ [temp.arg]p2:
5674 // In a template-argument, an ambiguity between a type-id and
5675 // an expression is resolved to a type-id, regardless of the
5676 // form of the corresponding template-parameter.
5677 //
5678 // We warn specifically about this case, since it can be rather
5679 // confusing for users.
5680 QualType T = Arg.getAsType();
5681 SourceRange SR = ArgLoc.getSourceRange();
5682 if (T->isFunctionType())
5683 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5684 else
5685 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5687 return true;
5688 }
5689
5691 llvm_unreachable("Caller must expand template argument packs");
5692 }
5693
5694 return false;
5695 }
5696
5697
5698 // Check template template parameters.
5700
5701 TemplateParameterList *Params = TempParm->getTemplateParameters();
5702 if (TempParm->isExpandedParameterPack())
5703 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5704
5705 // Substitute into the template parameter list of the template
5706 // template parameter, since previously-supplied template arguments
5707 // may appear within the template template parameter.
5708 //
5709 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5710 {
5711 // Set up a template instantiation context.
5713 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5714 CTAI.SugaredConverted,
5715 SourceRange(TemplateLoc, RAngleLoc));
5716 if (Inst.isInvalid())
5717 return true;
5718
5719 Params = SubstTemplateParams(
5720 Params, CurContext,
5722 /*Final=*/true),
5723 /*EvaluateConstraints=*/false);
5724 if (!Params)
5725 return true;
5726 }
5727
5728 // C++1z [temp.local]p1: (DR1004)
5729 // When [the injected-class-name] is used [...] as a template-argument for
5730 // a template template-parameter [...] it refers to the class template
5731 // itself.
5732 if (Arg.getKind() == TemplateArgument::Type) {
5734 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5735 if (!ConvertedArg.getArgument().isNull())
5736 ArgLoc = ConvertedArg;
5737 }
5738
5739 switch (Arg.getKind()) {
5741 llvm_unreachable("Should never see a NULL template argument here");
5742
5745 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5746 CTAI.PartialOrdering,
5747 &CTAI.StrictPackMatch))
5748 return true;
5749
5750 CTAI.SugaredConverted.push_back(Arg);
5751 CTAI.CanonicalConverted.push_back(
5752 Context.getCanonicalTemplateArgument(Arg));
5753 break;
5754
5757 auto Kind = 0;
5758 switch (TempParm->templateParameterKind()) {
5760 Kind = 1;
5761 break;
5763 Kind = 2;
5764 break;
5765 default:
5766 break;
5767 }
5768
5769 // We have a template template parameter but the template
5770 // argument does not refer to a template.
5771 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5772 << Kind << getLangOpts().CPlusPlus11;
5773 return true;
5774 }
5775
5780 llvm_unreachable("non-type argument with template template parameter");
5781
5783 llvm_unreachable("Caller must expand template argument packs");
5784 }
5785
5786 return false;
5787}
5788
5789/// Diagnose a missing template argument.
5790template<typename TemplateParmDecl>
5792 TemplateDecl *TD,
5793 const TemplateParmDecl *D,
5795 // Dig out the most recent declaration of the template parameter; there may be
5796 // declarations of the template that are more recent than TD.
5798 ->getTemplateParameters()
5799 ->getParam(D->getIndex()));
5800
5801 // If there's a default argument that's not reachable, diagnose that we're
5802 // missing a module import.
5804 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5806 D->getDefaultArgumentLoc(), Modules,
5808 /*Recover*/true);
5809 return true;
5810 }
5811
5812 // FIXME: If there's a more recent default argument that *is* visible,
5813 // diagnose that it was declared too late.
5814
5816
5817 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5818 << /*not enough args*/0
5820 << TD;
5821 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5822 return true;
5823}
5824
5825/// Check that the given template argument list is well-formed
5826/// for specializing the given template.
5828 TemplateDecl *Template, SourceLocation TemplateLoc,
5829 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5830 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5831 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5833 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5834 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5836}
5837
5838/// Check that the given template argument list is well-formed
5839/// for specializing the given template.
5842 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5843 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5844 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5846
5848 *ConstraintsNotSatisfied = false;
5849
5850 // Make a copy of the template arguments for processing. Only make the
5851 // changes at the end when successful in matching the arguments to the
5852 // template.
5853 TemplateArgumentListInfo NewArgs = TemplateArgs;
5854
5855 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5856
5857 // C++23 [temp.arg.general]p1:
5858 // [...] The type and form of each template-argument specified in
5859 // a template-id shall match the type and form specified for the
5860 // corresponding parameter declared by the template in its
5861 // template-parameter-list.
5862 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5863 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5864 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5865 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5866 LocalInstantiationScope InstScope(*this, true);
5867 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5868 ParamEnd = Params->end(),
5869 Param = ParamBegin;
5870 Param != ParamEnd;
5871 /* increment in loop */) {
5872 if (size_t ParamIdx = Param - ParamBegin;
5873 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5874 // All written arguments should have been consumed by this point.
5875 assert(ArgIdx == NumArgs && "bad default argument deduction");
5876 if (ParamIdx == DefaultArgs.StartPos) {
5877 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5878 // Default arguments from a DeducedTemplateName are already converted.
5879 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5880 CTAI.SugaredConverted.push_back(DefArg);
5881 CTAI.CanonicalConverted.push_back(
5882 Context.getCanonicalTemplateArgument(DefArg));
5883 ++Param;
5884 }
5885 continue;
5886 }
5887 }
5888
5889 // If we have an expanded parameter pack, make sure we don't have too
5890 // many arguments.
5891 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5892 if (*Expansions == SugaredArgumentPack.size()) {
5893 // We're done with this parameter pack. Pack up its arguments and add
5894 // them to the list.
5895 CTAI.SugaredConverted.push_back(
5896 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5897 SugaredArgumentPack.clear();
5898
5899 CTAI.CanonicalConverted.push_back(
5900 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5901 CanonicalArgumentPack.clear();
5902
5903 // This argument is assigned to the next parameter.
5904 ++Param;
5905 continue;
5906 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5907 // Not enough arguments for this parameter pack.
5908 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5909 << /*not enough args*/0
5911 << Template;
5913 return true;
5914 }
5915 }
5916
5917 // Check for builtins producing template packs in this context, we do not
5918 // support them yet.
5919 if (const NonTypeTemplateParmDecl *NTTP =
5920 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5921 NTTP && NTTP->isPackExpansion()) {
5922 auto TL = NTTP->getTypeSourceInfo()
5923 ->getTypeLoc()
5926 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5927 for (const auto &UPP : Unexpanded) {
5928 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5929 if (!TST)
5930 continue;
5931 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5932 // Expanding a built-in pack in this context is not yet supported.
5933 Diag(TL.getEllipsisLoc(),
5934 diag::err_unsupported_builtin_template_pack_expansion)
5935 << TST->getTemplateName();
5936 return true;
5937 }
5938 }
5939
5940 if (ArgIdx < NumArgs) {
5941 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5942 bool NonPackParameter =
5943 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5944 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5945
5946 if (ArgIsExpansion && CTAI.MatchingTTP) {
5947 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5948 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5949 ++Param) {
5950 TemplateArgument &Arg = Args[Param - First];
5951 Arg = ArgLoc.getArgument();
5952 if (!(*Param)->isTemplateParameterPack() ||
5953 getExpandedPackSize(*Param))
5954 Arg = Arg.getPackExpansionPattern();
5955 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5956 SaveAndRestore _1(CTAI.PartialOrdering, false);
5957 SaveAndRestore _2(CTAI.MatchingTTP, true);
5958 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5959 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5961 return true;
5962 Arg = NewArgLoc.getArgument();
5963 CTAI.CanonicalConverted.back().setIsDefaulted(
5964 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5965 CTAI.CanonicalConverted,
5966 Params->getDepth()));
5967 }
5968 ArgLoc =
5970 ArgLoc.getLocInfo());
5971 } else {
5972 SaveAndRestore _1(CTAI.PartialOrdering, false);
5973 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5974 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5976 return true;
5977 CTAI.CanonicalConverted.back().setIsDefaulted(
5978 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5979 *Param, CTAI.CanonicalConverted,
5980 Params->getDepth()));
5981 if (ArgIsExpansion && NonPackParameter) {
5982 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5983 // alias template or concept, and it's not part of a parameter pack.
5984 // This can't be canonicalized, so reject it now.
5986 Diag(ArgLoc.getLocation(),
5987 diag::err_template_expansion_into_fixed_list)
5988 << (isa<ConceptDecl>(Template) ? 1 : 0)
5989 << ArgLoc.getSourceRange();
5991 return true;
5992 }
5993 }
5994 }
5995
5996 // We're now done with this argument.
5997 ++ArgIdx;
5998
5999 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6000 // Directly convert the remaining arguments, because we don't know what
6001 // parameters they'll match up with.
6002
6003 if (!SugaredArgumentPack.empty()) {
6004 // If we were part way through filling in an expanded parameter pack,
6005 // fall back to just producing individual arguments.
6006 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6007 SugaredArgumentPack.begin(),
6008 SugaredArgumentPack.end());
6009 SugaredArgumentPack.clear();
6010
6011 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6012 CanonicalArgumentPack.begin(),
6013 CanonicalArgumentPack.end());
6014 CanonicalArgumentPack.clear();
6015 }
6016
6017 while (ArgIdx < NumArgs) {
6018 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6019 CTAI.SugaredConverted.push_back(Arg);
6020 CTAI.CanonicalConverted.push_back(
6021 Context.getCanonicalTemplateArgument(Arg));
6022 ++ArgIdx;
6023 }
6024
6025 return false;
6026 }
6027
6028 if ((*Param)->isTemplateParameterPack()) {
6029 // The template parameter was a template parameter pack, so take the
6030 // deduced argument and place it on the argument pack. Note that we
6031 // stay on the same template parameter so that we can deduce more
6032 // arguments.
6033 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6034 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6035 } else {
6036 // Move to the next template parameter.
6037 ++Param;
6038 }
6039 continue;
6040 }
6041
6042 // If we're checking a partial template argument list, we're done.
6043 if (PartialTemplateArgs) {
6044 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6045 CTAI.SugaredConverted.push_back(
6046 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6047 CTAI.CanonicalConverted.push_back(
6048 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6049 }
6050 return false;
6051 }
6052
6053 // If we have a template parameter pack with no more corresponding
6054 // arguments, just break out now and we'll fill in the argument pack below.
6055 if ((*Param)->isTemplateParameterPack()) {
6056 assert(!getExpandedPackSize(*Param) &&
6057 "Should have dealt with this already");
6058
6059 // A non-expanded parameter pack before the end of the parameter list
6060 // only occurs for an ill-formed template parameter list, unless we've
6061 // got a partial argument list for a function template, so just bail out.
6062 if (Param + 1 != ParamEnd) {
6063 assert(
6064 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6065 "Concept templates must have parameter packs at the end.");
6066 return true;
6067 }
6068
6069 CTAI.SugaredConverted.push_back(
6070 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6071 SugaredArgumentPack.clear();
6072
6073 CTAI.CanonicalConverted.push_back(
6074 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6075 CanonicalArgumentPack.clear();
6076
6077 ++Param;
6078 continue;
6079 }
6080
6081 // Check whether we have a default argument.
6082 bool HasDefaultArg;
6083
6084 // Retrieve the default template argument from the template
6085 // parameter. For each kind of template parameter, we substitute the
6086 // template arguments provided thus far and any "outer" template arguments
6087 // (when the template parameter was part of a nested template) into
6088 // the default argument.
6090 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6091 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6092
6093 if (Arg.getArgument().isNull()) {
6094 if (!HasDefaultArg) {
6095 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6096 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6097 NewArgs);
6098 if (NonTypeTemplateParmDecl *NTTP =
6099 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6100 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6101 NewArgs);
6102 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6104 NewArgs);
6105 }
6106 return true;
6107 }
6108
6109 // Introduce an instantiation record that describes where we are using
6110 // the default template argument. We're not actually instantiating a
6111 // template here, we just create this object to put a note into the
6112 // context stack.
6113 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6114 CTAI.SugaredConverted,
6115 SourceRange(TemplateLoc, RAngleLoc));
6116 if (Inst.isInvalid())
6117 return true;
6118
6119 SaveAndRestore _1(CTAI.PartialOrdering, false);
6120 SaveAndRestore _2(CTAI.MatchingTTP, false);
6121 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6122 // Check the default template argument.
6123 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6124 CTAI, CTAK_Specified))
6125 return true;
6126
6127 CTAI.SugaredConverted.back().setIsDefaulted(true);
6128 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6129
6130 // Core issue 150 (assumed resolution): if this is a template template
6131 // parameter, keep track of the default template arguments from the
6132 // template definition.
6133 if (isTemplateTemplateParameter)
6134 NewArgs.addArgument(Arg);
6135
6136 // Move to the next template parameter and argument.
6137 ++Param;
6138 ++ArgIdx;
6139 }
6140
6141 // If we're performing a partial argument substitution, allow any trailing
6142 // pack expansions; they might be empty. This can happen even if
6143 // PartialTemplateArgs is false (the list of arguments is complete but
6144 // still dependent).
6145 if (CTAI.MatchingTTP ||
6147 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6148 while (ArgIdx < NumArgs &&
6149 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6150 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6151 CTAI.SugaredConverted.push_back(Arg);
6152 CTAI.CanonicalConverted.push_back(
6153 Context.getCanonicalTemplateArgument(Arg));
6154 }
6155 }
6156
6157 // If we have any leftover arguments, then there were too many arguments.
6158 // Complain and fail.
6159 if (ArgIdx < NumArgs) {
6160 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6161 << /*too many args*/1
6163 << Template
6164 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6166 return true;
6167 }
6168
6169 // No problems found with the new argument list, propagate changes back
6170 // to caller.
6171 if (UpdateArgsWithConversions)
6172 TemplateArgs = std::move(NewArgs);
6173
6174 if (!PartialTemplateArgs) {
6175 // Setup the context/ThisScope for the case where we are needing to
6176 // re-instantiate constraints outside of normal instantiation.
6177 DeclContext *NewContext = Template->getDeclContext();
6178
6179 // If this template is in a template, make sure we extract the templated
6180 // decl.
6181 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6182 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6183 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6184
6185 Qualifiers ThisQuals;
6186 if (const auto *Method =
6187 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6188 ThisQuals = Method->getMethodQualifiers();
6189
6190 ContextRAII Context(*this, NewContext);
6191 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6192
6194 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6195 /*RelativeToPrimary=*/true,
6196 /*Pattern=*/nullptr,
6197 /*ForConceptInstantiation=*/true);
6198 if (!isa<ConceptDecl>(Template) &&
6200 Template, MLTAL,
6201 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6204 return true;
6205 }
6206 }
6207
6208 return false;
6209}
6210
6211namespace {
6212 class UnnamedLocalNoLinkageFinder
6213 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6214 {
6215 Sema &S;
6216 SourceRange SR;
6217
6219
6220 public:
6221 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6222
6223 bool Visit(QualType T) {
6224 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6225 }
6226
6227#define TYPE(Class, Parent) \
6228 bool Visit##Class##Type(const Class##Type *);
6229#define ABSTRACT_TYPE(Class, Parent) \
6230 bool Visit##Class##Type(const Class##Type *) { return false; }
6231#define NON_CANONICAL_TYPE(Class, Parent) \
6232 bool Visit##Class##Type(const Class##Type *) { return false; }
6233#include "clang/AST/TypeNodes.inc"
6234
6235 bool VisitTagDecl(const TagDecl *Tag);
6236 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6237 };
6238} // end anonymous namespace
6239
6240bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6241 return false;
6242}
6243
6244bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6245 return Visit(T->getElementType());
6246}
6247
6248bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6249 return Visit(T->getPointeeType());
6250}
6251
6252bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6253 const BlockPointerType* T) {
6254 return Visit(T->getPointeeType());
6255}
6256
6257bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6258 const LValueReferenceType* T) {
6259 return Visit(T->getPointeeType());
6260}
6261
6262bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6263 const RValueReferenceType* T) {
6264 return Visit(T->getPointeeType());
6265}
6266
6267bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6268 const MemberPointerType *T) {
6269 if (Visit(T->getPointeeType()))
6270 return true;
6271 if (auto *RD = T->getMostRecentCXXRecordDecl())
6272 return VisitTagDecl(RD);
6273 return VisitNestedNameSpecifier(T->getQualifier());
6274}
6275
6276bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6277 const ConstantArrayType* T) {
6278 return Visit(T->getElementType());
6279}
6280
6281bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6282 const IncompleteArrayType* T) {
6283 return Visit(T->getElementType());
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6287 const VariableArrayType* T) {
6288 return Visit(T->getElementType());
6289}
6290
6291bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6292 const DependentSizedArrayType* T) {
6293 return Visit(T->getElementType());
6294}
6295
6296bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6298 return Visit(T->getElementType());
6299}
6300
6301bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6302 const DependentSizedMatrixType *T) {
6303 return Visit(T->getElementType());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6308 return Visit(T->getPointeeType());
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6312 return Visit(T->getElementType());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6316 const DependentVectorType *T) {
6317 return Visit(T->getElementType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6321 return Visit(T->getElementType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6325 const ConstantMatrixType *T) {
6326 return Visit(T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6330 const FunctionProtoType* T) {
6331 for (const auto &A : T->param_types()) {
6332 if (Visit(A))
6333 return true;
6334 }
6335
6336 return Visit(T->getReturnType());
6337}
6338
6339bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6340 const FunctionNoProtoType* T) {
6341 return Visit(T->getReturnType());
6342}
6343
6344bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6345 const UnresolvedUsingType*) {
6346 return false;
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6350 return false;
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6354 return Visit(T->getUnmodifiedType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6358 return false;
6359}
6360
6361bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6362 const PackIndexingType *) {
6363 return false;
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6367 const UnaryTransformType*) {
6368 return false;
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6372 return Visit(T->getDeducedType());
6373}
6374
6375bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6376 const DeducedTemplateSpecializationType *T) {
6377 return Visit(T->getDeducedType());
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6381 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6382}
6383
6384bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6385 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6386}
6387
6388bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6389 const TemplateTypeParmType*) {
6390 return false;
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6394 const SubstTemplateTypeParmPackType *) {
6395 return false;
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6399 const SubstBuiltinTemplatePackType *) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6404 const TemplateSpecializationType*) {
6405 return false;
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6409 const InjectedClassNameType* T) {
6410 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6414 const DependentNameType* T) {
6415 return VisitNestedNameSpecifier(T->getQualifier());
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6419 const PackExpansionType* T) {
6420 return Visit(T->getPattern());
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6424 return false;
6425}
6426
6427bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6428 const ObjCInterfaceType *) {
6429 return false;
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6433 const ObjCObjectPointerType *) {
6434 return false;
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6438 return Visit(T->getValueType());
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6442 return false;
6443}
6444
6445bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6446 return false;
6447}
6448
6449bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6450 const ArrayParameterType *T) {
6451 return VisitConstantArrayType(T);
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6455 const DependentBitIntType *T) {
6456 return false;
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6460 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6461 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6462 ? diag::warn_cxx98_compat_template_arg_local_type
6463 : diag::ext_template_arg_local_type)
6464 << S.Context.getCanonicalTagType(Tag) << SR;
6465 return true;
6466 }
6467
6468 if (!Tag->hasNameForLinkage()) {
6469 S.Diag(SR.getBegin(),
6470 S.getLangOpts().CPlusPlus11 ?
6471 diag::warn_cxx98_compat_template_arg_unnamed_type :
6472 diag::ext_template_arg_unnamed_type) << SR;
6473 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6474 return true;
6475 }
6476
6477 return false;
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6481 NestedNameSpecifier NNS) {
6482 switch (NNS.getKind()) {
6487 return false;
6489 return Visit(QualType(NNS.getAsType(), 0));
6490 }
6491 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6495 const HLSLAttributedResourceType *T) {
6496 if (T->hasContainedType() && Visit(T->getContainedType()))
6497 return true;
6498 return Visit(T->getWrappedType());
6499}
6500
6501bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6502 const HLSLInlineSpirvType *T) {
6503 for (auto &Operand : T->getOperands())
6504 if (Operand.isConstant() && Operand.isLiteral())
6505 if (Visit(Operand.getResultType()))
6506 return true;
6507 return false;
6508}
6509
6511 assert(ArgInfo && "invalid TypeSourceInfo");
6512 QualType Arg = ArgInfo->getType();
6513 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6514 QualType CanonArg = Context.getCanonicalType(Arg);
6515
6516 if (CanonArg->isVariablyModifiedType()) {
6517 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6518 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6519 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6520 }
6521
6522 // C++03 [temp.arg.type]p2:
6523 // A local type, a type with no linkage, an unnamed type or a type
6524 // compounded from any of these types shall not be used as a
6525 // template-argument for a template type-parameter.
6526 //
6527 // C++11 allows these, and even in C++03 we allow them as an extension with
6528 // a warning.
6529 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6530 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6531 (void)Finder.Visit(CanonArg);
6532 }
6533
6534 return false;
6535}
6536
6542
6543/// Determine whether the given template argument is a null pointer
6544/// value of the appropriate type.
6547 QualType ParamType, Expr *Arg,
6548 Decl *Entity = nullptr) {
6549 if (Arg->isValueDependent() || Arg->isTypeDependent())
6550 return NPV_NotNullPointer;
6551
6552 // dllimport'd entities aren't constant but are available inside of template
6553 // arguments.
6554 if (Entity && Entity->hasAttr<DLLImportAttr>())
6555 return NPV_NotNullPointer;
6556
6557 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6558 llvm_unreachable(
6559 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6560
6561 if (!S.getLangOpts().CPlusPlus11)
6562 return NPV_NotNullPointer;
6563
6564 // Determine whether we have a constant expression.
6566 if (ArgRV.isInvalid())
6567 return NPV_Error;
6568 Arg = ArgRV.get();
6569
6570 Expr::EvalResult EvalResult;
6572 EvalResult.Diag = &Notes;
6573 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6574 EvalResult.HasSideEffects) {
6575 SourceLocation DiagLoc = Arg->getExprLoc();
6576
6577 // If our only note is the usual "invalid subexpression" note, just point
6578 // the caret at its location rather than producing an essentially
6579 // redundant note.
6580 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6581 diag::note_invalid_subexpr_in_const_expr) {
6582 DiagLoc = Notes[0].first;
6583 Notes.clear();
6584 }
6585
6586 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6587 << Arg->getType() << Arg->getSourceRange();
6588 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6589 S.Diag(Notes[I].first, Notes[I].second);
6590
6592 return NPV_Error;
6593 }
6594
6595 // C++11 [temp.arg.nontype]p1:
6596 // - an address constant expression of type std::nullptr_t
6597 if (Arg->getType()->isNullPtrType())
6598 return NPV_NullPointer;
6599
6600 // - a constant expression that evaluates to a null pointer value (4.10); or
6601 // - a constant expression that evaluates to a null member pointer value
6602 // (4.11); or
6603 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6604 (EvalResult.Val.isMemberPointer() &&
6605 !EvalResult.Val.getMemberPointerDecl())) {
6606 // If our expression has an appropriate type, we've succeeded.
6607 bool ObjCLifetimeConversion;
6608 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6609 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6610 ObjCLifetimeConversion))
6611 return NPV_NullPointer;
6612
6613 // The types didn't match, but we know we got a null pointer; complain,
6614 // then recover as if the types were correct.
6615 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6616 << Arg->getType() << ParamType << Arg->getSourceRange();
6618 return NPV_NullPointer;
6619 }
6620
6621 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6622 // We found a pointer that isn't null, but doesn't refer to an object.
6623 // We could just return NPV_NotNullPointer, but we can print a better
6624 // message with the information we have here.
6625 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6626 << EvalResult.Val.getAsString(S.Context, ParamType);
6628 return NPV_Error;
6629 }
6630
6631 // If we don't have a null pointer value, but we do have a NULL pointer
6632 // constant, suggest a cast to the appropriate type.
6634 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6635 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6636 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6638 ")");
6640 return NPV_NullPointer;
6641 }
6642
6643 // FIXME: If we ever want to support general, address-constant expressions
6644 // as non-type template arguments, we should return the ExprResult here to
6645 // be interpreted by the caller.
6646 return NPV_NotNullPointer;
6647}
6648
6649/// Checks whether the given template argument is compatible with its
6650/// template parameter.
6651static bool
6653 QualType ParamType, Expr *ArgIn,
6654 Expr *Arg, QualType ArgType) {
6655 bool ObjCLifetimeConversion;
6656 if (ParamType->isPointerType() &&
6657 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6658 S.IsQualificationConversion(ArgType, ParamType, false,
6659 ObjCLifetimeConversion)) {
6660 // For pointer-to-object types, qualification conversions are
6661 // permitted.
6662 } else {
6663 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6664 if (!ParamRef->getPointeeType()->isFunctionType()) {
6665 // C++ [temp.arg.nontype]p5b3:
6666 // For a non-type template-parameter of type reference to
6667 // object, no conversions apply. The type referred to by the
6668 // reference may be more cv-qualified than the (otherwise
6669 // identical) type of the template- argument. The
6670 // template-parameter is bound directly to the
6671 // template-argument, which shall be an lvalue.
6672
6673 // FIXME: Other qualifiers?
6674 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6675 unsigned ArgQuals = ArgType.getCVRQualifiers();
6676
6677 if ((ParamQuals | ArgQuals) != ParamQuals) {
6678 S.Diag(Arg->getBeginLoc(),
6679 diag::err_template_arg_ref_bind_ignores_quals)
6680 << ParamType << Arg->getType() << Arg->getSourceRange();
6682 return true;
6683 }
6684 }
6685 }
6686
6687 // At this point, the template argument refers to an object or
6688 // function with external linkage. We now need to check whether the
6689 // argument and parameter types are compatible.
6690 if (!S.Context.hasSameUnqualifiedType(ArgType,
6691 ParamType.getNonReferenceType())) {
6692 // We can't perform this conversion or binding.
6693 if (ParamType->isReferenceType())
6694 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6695 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6696 else
6697 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6698 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6700 return true;
6701 }
6702 }
6703
6704 return false;
6705}
6706
6707/// Checks whether the given template argument is the address
6708/// of an object or function according to C++ [temp.arg.nontype]p1.
6710 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6711 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6712 bool Invalid = false;
6713 Expr *Arg = ArgIn;
6714 QualType ArgType = Arg->getType();
6715
6716 bool AddressTaken = false;
6717 SourceLocation AddrOpLoc;
6718 if (S.getLangOpts().MicrosoftExt) {
6719 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6720 // dereference and address-of operators.
6721 Arg = Arg->IgnoreParenCasts();
6722
6723 bool ExtWarnMSTemplateArg = false;
6724 UnaryOperatorKind FirstOpKind;
6725 SourceLocation FirstOpLoc;
6726 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6727 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6728 if (UnOpKind == UO_Deref)
6729 ExtWarnMSTemplateArg = true;
6730 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6731 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6732 if (!AddrOpLoc.isValid()) {
6733 FirstOpKind = UnOpKind;
6734 FirstOpLoc = UnOp->getOperatorLoc();
6735 }
6736 } else
6737 break;
6738 }
6739 if (FirstOpLoc.isValid()) {
6740 if (ExtWarnMSTemplateArg)
6741 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6742 << ArgIn->getSourceRange();
6743
6744 if (FirstOpKind == UO_AddrOf)
6745 AddressTaken = true;
6746 else if (Arg->getType()->isPointerType()) {
6747 // We cannot let pointers get dereferenced here, that is obviously not a
6748 // constant expression.
6749 assert(FirstOpKind == UO_Deref);
6750 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6751 << Arg->getSourceRange();
6752 }
6753 }
6754 } else {
6755 // See through any implicit casts we added to fix the type.
6756 Arg = Arg->IgnoreImpCasts();
6757
6758 // C++ [temp.arg.nontype]p1:
6759 //
6760 // A template-argument for a non-type, non-template
6761 // template-parameter shall be one of: [...]
6762 //
6763 // -- the address of an object or function with external
6764 // linkage, including function templates and function
6765 // template-ids but excluding non-static class members,
6766 // expressed as & id-expression where the & is optional if
6767 // the name refers to a function or array, or if the
6768 // corresponding template-parameter is a reference; or
6769
6770 // In C++98/03 mode, give an extension warning on any extra parentheses.
6771 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6772 bool ExtraParens = false;
6773 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6774 if (!Invalid && !ExtraParens) {
6775 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6776 << Arg->getSourceRange();
6777 ExtraParens = true;
6778 }
6779
6780 Arg = Parens->getSubExpr();
6781 }
6782
6783 while (SubstNonTypeTemplateParmExpr *subst =
6784 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6785 Arg = subst->getReplacement()->IgnoreImpCasts();
6786
6787 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6788 if (UnOp->getOpcode() == UO_AddrOf) {
6789 Arg = UnOp->getSubExpr();
6790 AddressTaken = true;
6791 AddrOpLoc = UnOp->getOperatorLoc();
6792 }
6793 }
6794
6795 while (SubstNonTypeTemplateParmExpr *subst =
6796 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6797 Arg = subst->getReplacement()->IgnoreImpCasts();
6798 }
6799
6800 ValueDecl *Entity = nullptr;
6801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6802 Entity = DRE->getDecl();
6803 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6804 Entity = CUE->getGuidDecl();
6805
6806 // If our parameter has pointer type, check for a null template value.
6807 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6808 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6809 Entity)) {
6810 case NPV_NullPointer:
6811 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6812 SugaredConverted = TemplateArgument(ParamType,
6813 /*isNullPtr=*/true);
6814 CanonicalConverted =
6816 /*isNullPtr=*/true);
6817 return false;
6818
6819 case NPV_Error:
6820 return true;
6821
6822 case NPV_NotNullPointer:
6823 break;
6824 }
6825 }
6826
6827 // Stop checking the precise nature of the argument if it is value dependent,
6828 // it should be checked when instantiated.
6829 if (Arg->isValueDependent()) {
6830 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6831 CanonicalConverted =
6832 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6833 return false;
6834 }
6835
6836 if (!Entity) {
6837 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6838 << Arg->getSourceRange();
6840 return true;
6841 }
6842
6843 // Cannot refer to non-static data members
6844 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6845 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6846 << Entity << Arg->getSourceRange();
6848 return true;
6849 }
6850
6851 // Cannot refer to non-static member functions
6852 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6853 if (!Method->isStatic()) {
6854 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6855 << Method << Arg->getSourceRange();
6857 return true;
6858 }
6859 }
6860
6861 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6862 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6863 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6864
6865 // A non-type template argument must refer to an object or function.
6866 if (!Func && !Var && !Guid) {
6867 // We found something, but we don't know specifically what it is.
6868 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6869 << Arg->getSourceRange();
6870 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6871 return true;
6872 }
6873
6874 // Address / reference template args must have external linkage in C++98.
6875 if (Entity->getFormalLinkage() == Linkage::Internal) {
6876 S.Diag(Arg->getBeginLoc(),
6877 S.getLangOpts().CPlusPlus11
6878 ? diag::warn_cxx98_compat_template_arg_object_internal
6879 : diag::ext_template_arg_object_internal)
6880 << !Func << Entity << Arg->getSourceRange();
6881 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6882 << !Func;
6883 } else if (!Entity->hasLinkage()) {
6884 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6885 << !Func << Entity << Arg->getSourceRange();
6886 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6887 << !Func;
6888 return true;
6889 }
6890
6891 if (Var) {
6892 // A value of reference type is not an object.
6893 if (Var->getType()->isReferenceType()) {
6894 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6895 << Var->getType() << Arg->getSourceRange();
6897 return true;
6898 }
6899
6900 // A template argument must have static storage duration.
6901 if (Var->getTLSKind()) {
6902 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6903 << Arg->getSourceRange();
6904 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6905 return true;
6906 }
6907 }
6908
6909 if (AddressTaken && ParamType->isReferenceType()) {
6910 // If we originally had an address-of operator, but the
6911 // parameter has reference type, complain and (if things look
6912 // like they will work) drop the address-of operator.
6913 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6914 ParamType.getNonReferenceType())) {
6915 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6916 << ParamType;
6918 return true;
6919 }
6920
6921 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6922 << ParamType
6923 << FixItHint::CreateRemoval(AddrOpLoc);
6925
6926 ArgType = Entity->getType();
6927 }
6928
6929 // If the template parameter has pointer type, either we must have taken the
6930 // address or the argument must decay to a pointer.
6931 if (!AddressTaken && ParamType->isPointerType()) {
6932 if (Func) {
6933 // Function-to-pointer decay.
6934 ArgType = S.Context.getPointerType(Func->getType());
6935 } else if (Entity->getType()->isArrayType()) {
6936 // Array-to-pointer decay.
6937 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6938 } else {
6939 // If the template parameter has pointer type but the address of
6940 // this object was not taken, complain and (possibly) recover by
6941 // taking the address of the entity.
6942 ArgType = S.Context.getPointerType(Entity->getType());
6943 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6944 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6945 << ParamType;
6947 return true;
6948 }
6949
6950 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6951 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6952
6954 }
6955 }
6956
6957 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6958 Arg, ArgType))
6959 return true;
6960
6961 // Create the template argument.
6962 SugaredConverted = TemplateArgument(Entity, ParamType);
6963 CanonicalConverted =
6965 S.Context.getCanonicalType(ParamType));
6966 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6967 return false;
6968}
6969
6970/// Checks whether the given template argument is a pointer to
6971/// member constant according to C++ [temp.arg.nontype]p1.
6973 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6974 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6975 bool Invalid = false;
6976
6977 Expr *Arg = ResultArg;
6978 bool ObjCLifetimeConversion;
6979
6980 // C++ [temp.arg.nontype]p1:
6981 //
6982 // A template-argument for a non-type, non-template
6983 // template-parameter shall be one of: [...]
6984 //
6985 // -- a pointer to member expressed as described in 5.3.1.
6986 DeclRefExpr *DRE = nullptr;
6987
6988 // In C++98/03 mode, give an extension warning on any extra parentheses.
6989 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6990 bool ExtraParens = false;
6991 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6992 if (!Invalid && !ExtraParens) {
6993 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6994 << Arg->getSourceRange();
6995 ExtraParens = true;
6996 }
6997
6998 Arg = Parens->getSubExpr();
6999 }
7000
7001 while (SubstNonTypeTemplateParmExpr *subst =
7002 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7003 Arg = subst->getReplacement()->IgnoreImpCasts();
7004
7005 // A pointer-to-member constant written &Class::member.
7006 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7007 if (UnOp->getOpcode() == UO_AddrOf) {
7008 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7009 if (DRE && !DRE->getQualifier())
7010 DRE = nullptr;
7011 }
7012 }
7013 // A constant of pointer-to-member type.
7014 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7015 ValueDecl *VD = DRE->getDecl();
7016 if (VD->getType()->isMemberPointerType()) {
7018 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7019 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7020 CanonicalConverted =
7021 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7022 } else {
7023 SugaredConverted = TemplateArgument(VD, ParamType);
7024 CanonicalConverted =
7026 S.Context.getCanonicalType(ParamType));
7027 }
7028 return Invalid;
7029 }
7030 }
7031
7032 DRE = nullptr;
7033 }
7034
7035 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7036
7037 // Check for a null pointer value.
7038 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7039 Entity)) {
7040 case NPV_Error:
7041 return true;
7042 case NPV_NullPointer:
7043 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7044 SugaredConverted = TemplateArgument(ParamType,
7045 /*isNullPtr*/ true);
7046 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7047 /*isNullPtr*/ true);
7048 return false;
7049 case NPV_NotNullPointer:
7050 break;
7051 }
7052
7053 if (S.IsQualificationConversion(ResultArg->getType(),
7054 ParamType.getNonReferenceType(), false,
7055 ObjCLifetimeConversion)) {
7056 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7057 ResultArg->getValueKind())
7058 .get();
7059 } else if (!S.Context.hasSameUnqualifiedType(
7060 ResultArg->getType(), ParamType.getNonReferenceType())) {
7061 // We can't perform this conversion.
7062 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7063 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7065 return true;
7066 }
7067
7068 if (!DRE)
7069 return S.Diag(Arg->getBeginLoc(),
7070 diag::err_template_arg_not_pointer_to_member_form)
7071 << Arg->getSourceRange();
7072
7073 if (isa<FieldDecl>(DRE->getDecl()) ||
7075 isa<CXXMethodDecl>(DRE->getDecl())) {
7076 assert((isa<FieldDecl>(DRE->getDecl()) ||
7079 ->isImplicitObjectMemberFunction()) &&
7080 "Only non-static member pointers can make it here");
7081
7082 // Okay: this is the address of a non-static member, and therefore
7083 // a member pointer constant.
7084 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7085 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7086 CanonicalConverted =
7087 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7088 } else {
7089 ValueDecl *D = DRE->getDecl();
7090 SugaredConverted = TemplateArgument(D, ParamType);
7091 CanonicalConverted =
7093 S.Context.getCanonicalType(ParamType));
7094 }
7095 return Invalid;
7096 }
7097
7098 // We found something else, but we don't know specifically what it is.
7099 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7100 << Arg->getSourceRange();
7101 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7102 return true;
7103}
7104
7105/// Check a template argument against its corresponding
7106/// non-type template parameter.
7107///
7108/// This routine implements the semantics of C++ [temp.arg.nontype].
7109/// If an error occurred, it returns ExprError(); otherwise, it
7110/// returns the converted template argument. \p ParamType is the
7111/// type of the non-type template parameter after it has been instantiated.
7113 Expr *Arg,
7114 TemplateArgument &SugaredConverted,
7115 TemplateArgument &CanonicalConverted,
7116 bool StrictCheck,
7118 SourceLocation StartLoc = Arg->getBeginLoc();
7119 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7120 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7121 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7122 DeductionArg = NewDeductionArg;
7123 if (ArgPE) {
7124 // Recreate a pack expansion if we unwrapped one.
7125 Arg = new (Context) PackExpansionExpr(
7126 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7127 } else {
7128 Arg = DeductionArg;
7129 }
7130 };
7131
7132 // If the parameter type somehow involves auto, deduce the type now.
7133 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7134 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7135 if (IsDeduced) {
7136 // When checking a deduced template argument, deduce from its type even if
7137 // the type is dependent, in order to check the types of non-type template
7138 // arguments line up properly in partial ordering.
7139 TypeSourceInfo *TSI =
7140 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7142 InitializedEntity Entity =
7145 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7146 Expr *Inits[1] = {DeductionArg};
7147 ParamType =
7148 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7149 if (ParamType.isNull())
7150 return ExprError();
7151 } else {
7152 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7153 Param->getTemplateDepth() + 1);
7154 ParamType = QualType();
7156 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7157 /*DependentDeduction=*/true,
7158 // We do not check constraints right now because the
7159 // immediately-declared constraint of the auto type is
7160 // also an associated constraint, and will be checked
7161 // along with the other associated constraints after
7162 // checking the template argument list.
7163 /*IgnoreConstraints=*/true);
7165 ParamType = TSI->getType();
7166 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7168 return ExprError();
7169 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7170 Diag(Arg->getExprLoc(),
7171 diag::err_non_type_template_parm_type_deduction_failure)
7172 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7173 << Arg->getSourceRange();
7175 return ExprError();
7176 }
7177 ParamType = SubstAutoTypeDependent(ParamType);
7178 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7179 }
7180 }
7181 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7182 // an error. The error message normally references the parameter
7183 // declaration, but here we'll pass the argument location because that's
7184 // where the parameter type is deduced.
7185 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7186 if (ParamType.isNull()) {
7188 return ExprError();
7189 }
7190 }
7191
7192 // We should have already dropped all cv-qualifiers by now.
7193 assert(!ParamType.hasQualifiers() &&
7194 "non-type template parameter type cannot be qualified");
7195
7196 // If either the parameter has a dependent type or the argument is
7197 // type-dependent, there's nothing we can check now.
7198 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7199 // Force the argument to the type of the parameter to maintain invariants.
7200 if (!IsDeduced) {
7202 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7203 ParamType->isLValueReferenceType() ? VK_LValue
7204 : ParamType->isRValueReferenceType() ? VK_XValue
7205 : VK_PRValue);
7206 if (E.isInvalid())
7207 return ExprError();
7208 setDeductionArg(E.get());
7209 }
7210 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7211 CanonicalConverted = TemplateArgument(
7212 Context.getCanonicalTemplateArgument(SugaredConverted));
7213 return Arg;
7214 }
7215
7216 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7217 if (CTAK == CTAK_Deduced && !StrictCheck &&
7218 (ParamType->isReferenceType()
7219 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7220 DeductionArg->getType())
7221 : !Context.hasSameUnqualifiedType(ParamType,
7222 DeductionArg->getType()))) {
7223 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7224 // we should actually be checking the type of the template argument in P,
7225 // not the type of the template argument deduced from A, against the
7226 // template parameter type.
7227 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7228 << Arg->getType() << ParamType.getUnqualifiedType();
7230 return ExprError();
7231 }
7232
7233 // If the argument is a pack expansion, we don't know how many times it would
7234 // expand. If we continue checking the argument, this will make the template
7235 // definition ill-formed if it would be ill-formed for any number of
7236 // expansions during instantiation time. When partial ordering or matching
7237 // template template parameters, this is exactly what we want. Otherwise, the
7238 // normal template rules apply: we accept the template if it would be valid
7239 // for any number of expansions (i.e. none).
7240 if (ArgPE && !StrictCheck) {
7241 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7242 CanonicalConverted = TemplateArgument(
7243 Context.getCanonicalTemplateArgument(SugaredConverted));
7244 return Arg;
7245 }
7246
7247 // Avoid making a copy when initializing a template parameter of class type
7248 // from a template parameter object of the same type. This is going beyond
7249 // the standard, but is required for soundness: in
7250 // template<A a> struct X { X *p; X<a> *q; };
7251 // ... we need p and q to have the same type.
7252 //
7253 // Similarly, don't inject a call to a copy constructor when initializing
7254 // from a template parameter of the same type.
7255 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7256 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7257 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7258 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7259 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7260
7261 SugaredConverted = TemplateArgument(TPO, ParamType);
7262 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7263 ParamType.getCanonicalType());
7264 return Arg;
7265 }
7267 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7268 CanonicalConverted =
7269 Context.getCanonicalTemplateArgument(SugaredConverted);
7270 return Arg;
7271 }
7272 }
7273
7274 // The initialization of the parameter from the argument is
7275 // a constant-evaluated context.
7278
7279 bool IsConvertedConstantExpression = true;
7280 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7282 StartLoc, /*DirectInit=*/false, DeductionArg);
7283 Expr *Inits[1] = {DeductionArg};
7284 InitializedEntity Entity =
7286 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7287 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7288 if (Result.isInvalid() || !Result.get())
7289 return ExprError();
7291 if (Result.isInvalid() || !Result.get())
7292 return ExprError();
7293 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7294 /*DiscardedValue=*/false,
7295 /*IsConstexpr=*/true,
7296 /*IsTemplateArgument=*/true)
7297 .get());
7298 IsConvertedConstantExpression = false;
7299 }
7300
7301 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7302 // C++17 [temp.arg.nontype]p1:
7303 // A template-argument for a non-type template parameter shall be
7304 // a converted constant expression of the type of the template-parameter.
7305 APValue Value;
7306 ExprResult ArgResult;
7307 if (IsConvertedConstantExpression) {
7309 DeductionArg, ParamType,
7310 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7311 assert(!ArgResult.isUnset());
7312 if (ArgResult.isInvalid()) {
7314 return ExprError();
7315 }
7316 } else {
7317 ArgResult = DeductionArg;
7318 }
7319
7320 // For a value-dependent argument, CheckConvertedConstantExpression is
7321 // permitted (and expected) to be unable to determine a value.
7322 if (ArgResult.get()->isValueDependent()) {
7323 setDeductionArg(ArgResult.get());
7324 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7325 CanonicalConverted =
7326 Context.getCanonicalTemplateArgument(SugaredConverted);
7327 return Arg;
7328 }
7329
7330 APValue PreNarrowingValue;
7332 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7333 false, PreNarrowingValue);
7334 if (ArgResult.isInvalid())
7335 return ExprError();
7336 setDeductionArg(ArgResult.get());
7337
7338 if (Value.isLValue()) {
7339 APValue::LValueBase Base = Value.getLValueBase();
7340 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7341 // For a non-type template-parameter of pointer or reference type,
7342 // the value of the constant expression shall not refer to
7343 assert(ParamType->isPointerOrReferenceType() ||
7344 ParamType->isNullPtrType());
7345 // -- a temporary object
7346 // -- a string literal
7347 // -- the result of a typeid expression, or
7348 // -- a predefined __func__ variable
7349 if (Base &&
7350 (!VD ||
7352 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7353 << Arg->getSourceRange();
7354 return ExprError();
7355 }
7356
7357 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7358 VD->getType()->isArrayType() &&
7359 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7360 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7361 if (ArgPE) {
7362 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7363 CanonicalConverted =
7364 Context.getCanonicalTemplateArgument(SugaredConverted);
7365 } else {
7366 SugaredConverted = TemplateArgument(VD, ParamType);
7367 CanonicalConverted =
7369 ParamType.getCanonicalType());
7370 }
7371 return Arg;
7372 }
7373
7374 // -- a subobject [until C++20]
7375 if (!getLangOpts().CPlusPlus20) {
7376 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7377 Value.isLValueOnePastTheEnd()) {
7378 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7379 << Value.getAsString(Context, ParamType);
7380 return ExprError();
7381 }
7382 assert((VD || !ParamType->isReferenceType()) &&
7383 "null reference should not be a constant expression");
7384 assert((!VD || !ParamType->isNullPtrType()) &&
7385 "non-null value of type nullptr_t?");
7386 }
7387 }
7388
7389 if (Value.isAddrLabelDiff())
7390 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7391
7392 if (ArgPE) {
7393 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7394 CanonicalConverted =
7395 Context.getCanonicalTemplateArgument(SugaredConverted);
7396 } else {
7397 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7398 CanonicalConverted =
7400 }
7401 return Arg;
7402 }
7403
7404 // These should have all been handled above using the C++17 rules.
7405 assert(!ArgPE && !StrictCheck);
7406
7407 // C++ [temp.arg.nontype]p5:
7408 // The following conversions are performed on each expression used
7409 // as a non-type template-argument. If a non-type
7410 // template-argument cannot be converted to the type of the
7411 // corresponding template-parameter then the program is
7412 // ill-formed.
7413 if (ParamType->isIntegralOrEnumerationType()) {
7414 // C++11:
7415 // -- for a non-type template-parameter of integral or
7416 // enumeration type, conversions permitted in a converted
7417 // constant expression are applied.
7418 //
7419 // C++98:
7420 // -- for a non-type template-parameter of integral or
7421 // enumeration type, integral promotions (4.5) and integral
7422 // conversions (4.7) are applied.
7423
7424 if (getLangOpts().CPlusPlus11) {
7425 // C++ [temp.arg.nontype]p1:
7426 // A template-argument for a non-type, non-template template-parameter
7427 // shall be one of:
7428 //
7429 // -- for a non-type template-parameter of integral or enumeration
7430 // type, a converted constant expression of the type of the
7431 // template-parameter; or
7432 llvm::APSInt Value;
7434 Arg, ParamType, Value, CCEKind::TemplateArg);
7435 if (ArgResult.isInvalid())
7436 return ExprError();
7437 Arg = ArgResult.get();
7438
7439 // We can't check arbitrary value-dependent arguments.
7440 if (Arg->isValueDependent()) {
7441 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7442 CanonicalConverted =
7443 Context.getCanonicalTemplateArgument(SugaredConverted);
7444 return Arg;
7445 }
7446
7447 // Widen the argument value to sizeof(parameter type). This is almost
7448 // always a no-op, except when the parameter type is bool. In
7449 // that case, this may extend the argument from 1 bit to 8 bits.
7450 QualType IntegerType = ParamType;
7451 if (const auto *ED = IntegerType->getAsEnumDecl())
7452 IntegerType = ED->getIntegerType();
7453 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7454 ? Context.getIntWidth(IntegerType)
7455 : Context.getTypeSize(IntegerType));
7456
7457 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7458 CanonicalConverted =
7459 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7460 return Arg;
7461 }
7462
7463 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7464 if (ArgResult.isInvalid())
7465 return ExprError();
7466 Arg = ArgResult.get();
7467
7468 QualType ArgType = Arg->getType();
7469
7470 // C++ [temp.arg.nontype]p1:
7471 // A template-argument for a non-type, non-template
7472 // template-parameter shall be one of:
7473 //
7474 // -- an integral constant-expression of integral or enumeration
7475 // type; or
7476 // -- the name of a non-type template-parameter; or
7477 llvm::APSInt Value;
7478 if (!ArgType->isIntegralOrEnumerationType()) {
7479 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7480 << ArgType << Arg->getSourceRange();
7482 return ExprError();
7483 }
7484 if (!Arg->isValueDependent()) {
7485 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7486 QualType T;
7487
7488 public:
7489 TmplArgICEDiagnoser(QualType T) : T(T) { }
7490
7491 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7492 SourceLocation Loc) override {
7493 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7494 }
7495 } Diagnoser(ArgType);
7496
7497 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7498 if (!Arg)
7499 return ExprError();
7500 }
7501
7502 // From here on out, all we care about is the unqualified form
7503 // of the argument type.
7504 ArgType = ArgType.getUnqualifiedType();
7505
7506 // Try to convert the argument to the parameter's type.
7507 if (Context.hasSameType(ParamType, ArgType)) {
7508 // Okay: no conversion necessary
7509 } else if (ParamType->isBooleanType()) {
7510 // This is an integral-to-boolean conversion.
7511 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7512 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7513 !ParamType->isEnumeralType()) {
7514 // This is an integral promotion or conversion.
7515 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7516 } else {
7517 // We can't perform this conversion.
7518 Diag(StartLoc, diag::err_template_arg_not_convertible)
7519 << Arg->getType() << ParamType << Arg->getSourceRange();
7521 return ExprError();
7522 }
7523
7524 // Add the value of this argument to the list of converted
7525 // arguments. We use the bitwidth and signedness of the template
7526 // parameter.
7527 if (Arg->isValueDependent()) {
7528 // The argument is value-dependent. Create a new
7529 // TemplateArgument with the converted expression.
7530 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7531 CanonicalConverted =
7532 Context.getCanonicalTemplateArgument(SugaredConverted);
7533 return Arg;
7534 }
7535
7536 QualType IntegerType = ParamType;
7537 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7538 IntegerType = ED->getIntegerType();
7539 }
7540
7541 if (ParamType->isBooleanType()) {
7542 // Value must be zero or one.
7543 Value = Value != 0;
7544 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7545 if (Value.getBitWidth() != AllowedBits)
7546 Value = Value.extOrTrunc(AllowedBits);
7547 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7548 } else {
7549 llvm::APSInt OldValue = Value;
7550
7551 // Coerce the template argument's value to the value it will have
7552 // based on the template parameter's type.
7553 unsigned AllowedBits = IntegerType->isBitIntType()
7554 ? Context.getIntWidth(IntegerType)
7555 : Context.getTypeSize(IntegerType);
7556 if (Value.getBitWidth() != AllowedBits)
7557 Value = Value.extOrTrunc(AllowedBits);
7558 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7559
7560 // Complain if an unsigned parameter received a negative value.
7561 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7562 (OldValue.isSigned() && OldValue.isNegative())) {
7563 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7564 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7565 << Arg->getSourceRange();
7567 }
7568
7569 // Complain if we overflowed the template parameter's type.
7570 unsigned RequiredBits;
7571 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7572 RequiredBits = OldValue.getActiveBits();
7573 else if (OldValue.isUnsigned())
7574 RequiredBits = OldValue.getActiveBits() + 1;
7575 else
7576 RequiredBits = OldValue.getSignificantBits();
7577 if (RequiredBits > AllowedBits) {
7578 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7579 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7580 << Arg->getSourceRange();
7582 }
7583 }
7584
7585 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7586 SugaredConverted = TemplateArgument(Context, Value, T);
7587 CanonicalConverted =
7588 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7589 return Arg;
7590 }
7591
7592 QualType ArgType = Arg->getType();
7593 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7594
7595 // Handle pointer-to-function, reference-to-function, and
7596 // pointer-to-member-function all in (roughly) the same way.
7597 if (// -- For a non-type template-parameter of type pointer to
7598 // function, only the function-to-pointer conversion (4.3) is
7599 // applied. If the template-argument represents a set of
7600 // overloaded functions (or a pointer to such), the matching
7601 // function is selected from the set (13.4).
7602 (ParamType->isPointerType() &&
7603 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7604 // -- For a non-type template-parameter of type reference to
7605 // function, no conversions apply. If the template-argument
7606 // represents a set of overloaded functions, the matching
7607 // function is selected from the set (13.4).
7608 (ParamType->isReferenceType() &&
7609 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7610 // -- For a non-type template-parameter of type pointer to
7611 // member function, no conversions apply. If the
7612 // template-argument represents a set of overloaded member
7613 // functions, the matching member function is selected from
7614 // the set (13.4).
7615 (ParamType->isMemberPointerType() &&
7616 ParamType->castAs<MemberPointerType>()->getPointeeType()
7617 ->isFunctionType())) {
7618
7619 if (Arg->getType() == Context.OverloadTy) {
7620 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7621 true,
7622 FoundResult)) {
7623 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7624 return ExprError();
7625
7626 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7627 if (Res.isInvalid())
7628 return ExprError();
7629 Arg = Res.get();
7630 ArgType = Arg->getType();
7631 } else
7632 return ExprError();
7633 }
7634
7635 if (!ParamType->isMemberPointerType()) {
7637 *this, Param, ParamType, Arg, SugaredConverted,
7638 CanonicalConverted))
7639 return ExprError();
7640 return Arg;
7641 }
7642
7644 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7645 return ExprError();
7646 return Arg;
7647 }
7648
7649 if (ParamType->isPointerType()) {
7650 // -- for a non-type template-parameter of type pointer to
7651 // object, qualification conversions (4.4) and the
7652 // array-to-pointer conversion (4.2) are applied.
7653 // C++0x also allows a value of std::nullptr_t.
7654 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7655 "Only object pointers allowed here");
7656
7658 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7659 return ExprError();
7660 return Arg;
7661 }
7662
7663 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7664 // -- For a non-type template-parameter of type reference to
7665 // object, no conversions apply. The type referred to by the
7666 // reference may be more cv-qualified than the (otherwise
7667 // identical) type of the template-argument. The
7668 // template-parameter is bound directly to the
7669 // template-argument, which must be an lvalue.
7670 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7671 "Only object references allowed here");
7672
7673 if (Arg->getType() == Context.OverloadTy) {
7675 ParamRefType->getPointeeType(),
7676 true,
7677 FoundResult)) {
7678 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7679 return ExprError();
7680 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7681 if (Res.isInvalid())
7682 return ExprError();
7683 Arg = Res.get();
7684 ArgType = Arg->getType();
7685 } else
7686 return ExprError();
7687 }
7688
7690 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7691 return ExprError();
7692 return Arg;
7693 }
7694
7695 // Deal with parameters of type std::nullptr_t.
7696 if (ParamType->isNullPtrType()) {
7697 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7698 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7699 CanonicalConverted =
7700 Context.getCanonicalTemplateArgument(SugaredConverted);
7701 return Arg;
7702 }
7703
7704 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7705 case NPV_NotNullPointer:
7706 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7707 << Arg->getType() << ParamType;
7709 return ExprError();
7710
7711 case NPV_Error:
7712 return ExprError();
7713
7714 case NPV_NullPointer:
7715 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7716 SugaredConverted = TemplateArgument(ParamType,
7717 /*isNullPtr=*/true);
7718 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7719 /*isNullPtr=*/true);
7720 return Arg;
7721 }
7722 }
7723
7724 // -- For a non-type template-parameter of type pointer to data
7725 // member, qualification conversions (4.4) are applied.
7726 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7727
7729 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7730 return ExprError();
7731 return Arg;
7732}
7733
7737
7740 const TemplateArgumentLoc &Arg) {
7741 // C++0x [temp.arg.template]p1:
7742 // A template-argument for a template template-parameter shall be
7743 // the name of a class template or an alias template, expressed as an
7744 // id-expression. When the template-argument names a class template, only
7745 // primary class templates are considered when matching the
7746 // template template argument with the corresponding parameter;
7747 // partial specializations are not considered even if their
7748 // parameter lists match that of the template template parameter.
7749 //
7750
7752 unsigned DiagFoundKind = 0;
7753
7754 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7755 switch (TTP->templateParameterKind()) {
7757 DiagFoundKind = 3;
7758 break;
7760 DiagFoundKind = 2;
7761 break;
7762 default:
7763 DiagFoundKind = 1;
7764 break;
7765 }
7766 Kind = TTP->templateParameterKind();
7767 } else if (isa<ConceptDecl>(Template)) {
7769 DiagFoundKind = 3;
7770 } else if (isa<FunctionTemplateDecl>(Template)) {
7772 DiagFoundKind = 0;
7773 } else if (isa<VarTemplateDecl>(Template)) {
7775 DiagFoundKind = 2;
7776 } else if (isa<ClassTemplateDecl>(Template) ||
7780 DiagFoundKind = 1;
7781 } else {
7782 assert(false && "Unexpected Decl");
7783 }
7784
7785 if (Kind == Param->templateParameterKind()) {
7786 return true;
7787 }
7788
7789 unsigned DiagKind = 0;
7790 switch (Param->templateParameterKind()) {
7792 DiagKind = 2;
7793 break;
7795 DiagKind = 1;
7796 break;
7797 default:
7798 DiagKind = 0;
7799 break;
7800 }
7801 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7802 << DiagKind;
7803 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7804 << DiagFoundKind << Template;
7805 return false;
7806}
7807
7808/// Check a template argument against its corresponding
7809/// template template parameter.
7810///
7811/// This routine implements the semantics of C++ [temp.arg.template].
7812/// It returns true if an error occurred, and false otherwise.
7814 TemplateParameterList *Params,
7816 bool PartialOrdering,
7817 bool *StrictPackMatch) {
7819 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7820 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7821 if (!Template) {
7822 // FIXME: Handle AssumedTemplateNames
7823 // Any dependent template name is fine.
7824 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7825 return false;
7826 }
7827
7828 if (Template->isInvalidDecl())
7829 return true;
7830
7832 return true;
7833 }
7834
7835 // C++1z [temp.arg.template]p3: (DR 150)
7836 // A template-argument matches a template template-parameter P when P
7837 // is at least as specialized as the template-argument A.
7839 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7840 PartialOrdering, StrictPackMatch))
7841 return true;
7842 // P2113
7843 // C++20[temp.func.order]p2
7844 // [...] If both deductions succeed, the partial ordering selects the
7845 // more constrained template (if one exists) as determined below.
7846 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7847 Params->getAssociatedConstraints(ParamsAC);
7848 // C++20[temp.arg.template]p3
7849 // [...] In this comparison, if P is unconstrained, the constraints on A
7850 // are not considered.
7851 if (ParamsAC.empty())
7852 return false;
7853
7854 Template->getAssociatedConstraints(TemplateAC);
7855
7856 bool IsParamAtLeastAsConstrained;
7857 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7858 IsParamAtLeastAsConstrained))
7859 return true;
7860 if (!IsParamAtLeastAsConstrained) {
7861 Diag(Arg.getLocation(),
7862 diag::err_template_template_parameter_not_at_least_as_constrained)
7863 << Template << Param << Arg.getSourceRange();
7864 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7865 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7867 TemplateAC);
7868 return true;
7869 }
7870 return false;
7871}
7872
7874 unsigned HereDiagID,
7875 unsigned ExternalDiagID) {
7876 if (Decl.getLocation().isValid())
7877 return S.Diag(Decl.getLocation(), HereDiagID);
7878
7879 SmallString<128> Str;
7880 llvm::raw_svector_ostream Out(Str);
7882 PP.TerseOutput = 1;
7883 Decl.print(Out, PP);
7884 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7885}
7886
7888 std::optional<SourceRange> ParamRange) {
7890 noteLocation(*this, Decl, diag::note_template_decl_here,
7891 diag::note_template_decl_external);
7892 if (ParamRange && ParamRange->isValid()) {
7893 assert(Decl.getLocation().isValid() &&
7894 "Parameter range has location when Decl does not");
7895 DB << *ParamRange;
7896 }
7897}
7898
7900 noteLocation(*this, Decl, diag::note_template_param_here,
7901 diag::note_template_param_external);
7902}
7903
7904/// Given a non-type template argument that refers to a
7905/// declaration and the type of its corresponding non-type template
7906/// parameter, produce an expression that properly refers to that
7907/// declaration.
7909 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7911 // C++ [temp.param]p8:
7912 //
7913 // A non-type template-parameter of type "array of T" or
7914 // "function returning T" is adjusted to be of type "pointer to
7915 // T" or "pointer to function returning T", respectively.
7916 if (ParamType->isArrayType())
7917 ParamType = Context.getArrayDecayedType(ParamType);
7918 else if (ParamType->isFunctionType())
7919 ParamType = Context.getPointerType(ParamType);
7920
7921 // For a NULL non-type template argument, return nullptr casted to the
7922 // parameter's type.
7923 if (Arg.getKind() == TemplateArgument::NullPtr) {
7924 return ImpCastExprToType(
7925 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7926 ParamType,
7927 ParamType->getAs<MemberPointerType>()
7928 ? CK_NullToMemberPointer
7929 : CK_NullToPointer);
7930 }
7931 assert(Arg.getKind() == TemplateArgument::Declaration &&
7932 "Only declaration template arguments permitted here");
7933
7934 ValueDecl *VD = Arg.getAsDecl();
7935
7936 CXXScopeSpec SS;
7937 if (ParamType->isMemberPointerType()) {
7938 // If this is a pointer to member, we need to use a qualified name to
7939 // form a suitable pointer-to-member constant.
7940 assert(VD->getDeclContext()->isRecord() &&
7941 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7943 CanQualType ClassType =
7944 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7945 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7946 SS.MakeTrivial(Context, Qualifier, Loc);
7947 }
7948
7950 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7951 if (RefExpr.isInvalid())
7952 return ExprError();
7953
7954 // For a pointer, the argument declaration is the pointee. Take its address.
7955 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7956 if (ParamType->isPointerType() && !ElemT.isNull() &&
7957 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7958 // Decay an array argument if we want a pointer to its first element.
7959 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7960 if (RefExpr.isInvalid())
7961 return ExprError();
7962 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7963 // For any other pointer, take the address (or form a pointer-to-member).
7964 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7965 if (RefExpr.isInvalid())
7966 return ExprError();
7967 } else if (ParamType->isRecordType()) {
7968 assert(isa<TemplateParamObjectDecl>(VD) &&
7969 "arg for class template param not a template parameter object");
7970 // No conversions apply in this case.
7971 return RefExpr;
7972 } else {
7973 assert(ParamType->isReferenceType() &&
7974 "unexpected type for decl template argument");
7975 if (NonTypeTemplateParmDecl *NTTP =
7976 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7977 QualType TemplateParamType = NTTP->getType();
7978 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7979 if (AT && AT->isDecltypeAuto()) {
7981 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7982 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7983 /*PackIndex=*/std::nullopt,
7984 /*RefParam=*/true, /*Final=*/true);
7985 }
7986 }
7987 }
7988
7989 // At this point we should have the right value category.
7990 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7991 "value kind mismatch for non-type template argument");
7992
7993 // The type of the template parameter can differ from the type of the
7994 // argument in various ways; convert it now if necessary.
7995 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7996 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7997 CastKind CK;
7998 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7999 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8000 CK = CK_NoOp;
8001 } else if (ParamType->isVoidPointerType() &&
8002 RefExpr.get()->getType()->isPointerType()) {
8003 CK = CK_BitCast;
8004 } else {
8005 // FIXME: Pointers to members can need conversion derived-to-base or
8006 // base-to-derived conversions. We currently don't retain enough
8007 // information to convert properly (we need to track a cast path or
8008 // subobject number in the template argument).
8009 llvm_unreachable(
8010 "unexpected conversion required for non-type template argument");
8011 }
8012 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8013 RefExpr.get()->getValueKind());
8014 }
8015
8016 return RefExpr;
8017}
8018
8019/// Construct a new expression that refers to the given
8020/// integral template argument with the given source-location
8021/// information.
8022///
8023/// This routine takes care of the mapping from an integral template
8024/// argument (which may have any integral type) to the appropriate
8025/// literal value.
8027 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8028 assert(OrigT->isIntegralOrEnumerationType());
8029
8030 // If this is an enum type that we're instantiating, we need to use an integer
8031 // type the same size as the enumerator. We don't want to build an
8032 // IntegerLiteral with enum type. The integer type of an enum type can be of
8033 // any integral type with C++11 enum classes, make sure we create the right
8034 // type of literal for it.
8035 QualType T = OrigT;
8036 if (const auto *ED = OrigT->getAsEnumDecl())
8037 T = ED->getIntegerType();
8038
8039 Expr *E;
8040 if (T->isAnyCharacterType()) {
8042 if (T->isWideCharType())
8044 else if (T->isChar8Type() && S.getLangOpts().Char8)
8046 else if (T->isChar16Type())
8048 else if (T->isChar32Type())
8050 else
8052
8053 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8054 } else if (T->isBooleanType()) {
8055 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8056 } else {
8057 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8058 }
8059
8060 if (OrigT->isEnumeralType()) {
8061 // FIXME: This is a hack. We need a better way to handle substituted
8062 // non-type template parameters.
8063 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8064 nullptr, S.CurFPFeatureOverrides(),
8065 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8066 Loc, Loc);
8067 }
8068
8069 return E;
8070}
8071
8073 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8074 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8075 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8076 ILE->setType(T);
8077 return ILE;
8078 };
8079
8080 switch (Val.getKind()) {
8082 // This cannot occur in a template argument at all.
8083 case APValue::Array:
8084 case APValue::Struct:
8085 case APValue::Union:
8086 // These can only occur within a template parameter object, which is
8087 // represented as a TemplateArgument::Declaration.
8088 llvm_unreachable("unexpected template argument value");
8089
8090 case APValue::Int:
8092 Loc);
8093
8094 case APValue::Float:
8095 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8096 T, Loc);
8097
8100 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8101 Val.getFixedPoint().getScale());
8102
8103 case APValue::ComplexInt: {
8104 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8106 S, ElemT, Val.getComplexIntReal(), Loc),
8108 S, ElemT, Val.getComplexIntImag(), Loc)});
8109 }
8110
8111 case APValue::ComplexFloat: {
8112 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8113 return MakeInitList(
8115 ElemT, Loc),
8117 ElemT, Loc)});
8118 }
8119
8120 case APValue::Vector: {
8121 QualType ElemT = T->castAs<VectorType>()->getElementType();
8123 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8125 S, ElemT, Val.getVectorElt(I), Loc));
8126 return MakeInitList(Elts);
8127 }
8128
8129 case APValue::None:
8131 llvm_unreachable("Unexpected APValue kind.");
8132 case APValue::LValue:
8134 // There isn't necessarily a valid equivalent source-level syntax for
8135 // these; in particular, a naive lowering might violate access control.
8136 // So for now we lower to a ConstantExpr holding the value, wrapped around
8137 // an OpaqueValueExpr.
8138 // FIXME: We should have a better representation for this.
8140 if (T->isReferenceType()) {
8141 T = T->getPointeeType();
8142 VK = VK_LValue;
8143 }
8144 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8145 return ConstantExpr::Create(S.Context, OVE, Val);
8146 }
8147 llvm_unreachable("Unhandled APValue::ValueKind enum");
8148}
8149
8152 SourceLocation Loc) {
8153 switch (Arg.getKind()) {
8159 llvm_unreachable("not a non-type template argument");
8160
8162 return Arg.getAsExpr();
8163
8167 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8168
8171 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8172
8175 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8176 }
8177 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8178}
8179
8180/// Match two template parameters within template parameter lists.
8182 Sema &S, NamedDecl *New,
8183 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8184 const NamedDecl *OldInstFrom, bool Complain,
8186 // Check the actual kind (type, non-type, template).
8187 if (Old->getKind() != New->getKind()) {
8188 if (Complain) {
8189 unsigned NextDiag = diag::err_template_param_different_kind;
8190 if (TemplateArgLoc.isValid()) {
8191 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8192 NextDiag = diag::note_template_param_different_kind;
8193 }
8194 S.Diag(New->getLocation(), NextDiag)
8195 << (Kind != Sema::TPL_TemplateMatch);
8196 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8197 << (Kind != Sema::TPL_TemplateMatch);
8198 }
8199
8200 return false;
8201 }
8202
8203 // Check that both are parameter packs or neither are parameter packs.
8204 // However, if we are matching a template template argument to a
8205 // template template parameter, the template template parameter can have
8206 // a parameter pack where the template template argument does not.
8207 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8208 if (Complain) {
8209 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8210 if (TemplateArgLoc.isValid()) {
8211 S.Diag(TemplateArgLoc,
8212 diag::err_template_arg_template_params_mismatch);
8213 NextDiag = diag::note_template_parameter_pack_non_pack;
8214 }
8215
8216 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8218 : 2;
8219 S.Diag(New->getLocation(), NextDiag)
8220 << ParamKind << New->isParameterPack();
8221 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8222 << ParamKind << Old->isParameterPack();
8223 }
8224
8225 return false;
8226 }
8227 // For non-type template parameters, check the type of the parameter.
8228 if (NonTypeTemplateParmDecl *OldNTTP =
8229 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8231
8232 // If we are matching a template template argument to a template
8233 // template parameter and one of the non-type template parameter types
8234 // is dependent, then we must wait until template instantiation time
8235 // to actually compare the arguments.
8237 (!OldNTTP->getType()->isDependentType() &&
8238 !NewNTTP->getType()->isDependentType())) {
8239 // C++20 [temp.over.link]p6:
8240 // Two [non-type] template-parameters are equivalent [if] they have
8241 // equivalent types ignoring the use of type-constraints for
8242 // placeholder types
8243 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8244 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8245 if (!S.Context.hasSameType(OldType, NewType)) {
8246 if (Complain) {
8247 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8248 if (TemplateArgLoc.isValid()) {
8249 S.Diag(TemplateArgLoc,
8250 diag::err_template_arg_template_params_mismatch);
8251 NextDiag = diag::note_template_nontype_parm_different_type;
8252 }
8253 S.Diag(NewNTTP->getLocation(), NextDiag)
8254 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8255 S.Diag(OldNTTP->getLocation(),
8256 diag::note_template_nontype_parm_prev_declaration)
8257 << OldNTTP->getType();
8258 }
8259 return false;
8260 }
8261 }
8262 }
8263 // For template template parameters, check the template parameter types.
8264 // The template parameter lists of template template
8265 // parameters must agree.
8266 else if (TemplateTemplateParmDecl *OldTTP =
8267 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8269 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8270 return false;
8272 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8273 OldTTP->getTemplateParameters(), Complain,
8276 : Kind),
8277 TemplateArgLoc))
8278 return false;
8279 }
8280
8284 const Expr *NewC = nullptr, *OldC = nullptr;
8285
8287 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8288 NewC = TC->getImmediatelyDeclaredConstraint();
8289 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8290 OldC = TC->getImmediatelyDeclaredConstraint();
8291 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8292 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8293 ->getPlaceholderTypeConstraint())
8294 NewC = E;
8295 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8296 ->getPlaceholderTypeConstraint())
8297 OldC = E;
8298 } else
8299 llvm_unreachable("unexpected template parameter type");
8300
8301 auto Diagnose = [&] {
8302 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8303 diag::err_template_different_type_constraint);
8304 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8305 diag::note_template_prev_declaration) << /*declaration*/0;
8306 };
8307
8308 if (!NewC != !OldC) {
8309 if (Complain)
8310 Diagnose();
8311 return false;
8312 }
8313
8314 if (NewC) {
8315 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8316 NewC)) {
8317 if (Complain)
8318 Diagnose();
8319 return false;
8320 }
8321 }
8322 }
8323
8324 return true;
8325}
8326
8327/// Diagnose a known arity mismatch when comparing template argument
8328/// lists.
8329static
8334 SourceLocation TemplateArgLoc) {
8335 unsigned NextDiag = diag::err_template_param_list_different_arity;
8336 if (TemplateArgLoc.isValid()) {
8337 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8338 NextDiag = diag::note_template_param_list_different_arity;
8339 }
8340 S.Diag(New->getTemplateLoc(), NextDiag)
8341 << (New->size() > Old->size())
8342 << (Kind != Sema::TPL_TemplateMatch)
8343 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8344 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8345 << (Kind != Sema::TPL_TemplateMatch)
8346 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8347}
8348
8351 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8352 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8353 if (Old->size() != New->size()) {
8354 if (Complain)
8356 TemplateArgLoc);
8357
8358 return false;
8359 }
8360
8361 // C++0x [temp.arg.template]p3:
8362 // A template-argument matches a template template-parameter (call it P)
8363 // when each of the template parameters in the template-parameter-list of
8364 // the template-argument's corresponding class template or alias template
8365 // (call it A) matches the corresponding template parameter in the
8366 // template-parameter-list of P. [...]
8367 TemplateParameterList::iterator NewParm = New->begin();
8368 TemplateParameterList::iterator NewParmEnd = New->end();
8369 for (TemplateParameterList::iterator OldParm = Old->begin(),
8370 OldParmEnd = Old->end();
8371 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8372 if (NewParm == NewParmEnd) {
8373 if (Complain)
8375 TemplateArgLoc);
8376 return false;
8377 }
8378 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8379 OldInstFrom, Complain, Kind,
8380 TemplateArgLoc))
8381 return false;
8382 }
8383
8384 // Make sure we exhausted all of the arguments.
8385 if (NewParm != NewParmEnd) {
8386 if (Complain)
8388 TemplateArgLoc);
8389
8390 return false;
8391 }
8392
8393 if (Kind != TPL_TemplateParamsEquivalent) {
8394 const Expr *NewRC = New->getRequiresClause();
8395 const Expr *OldRC = Old->getRequiresClause();
8396
8397 auto Diagnose = [&] {
8398 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8399 diag::err_template_different_requires_clause);
8400 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8401 diag::note_template_prev_declaration) << /*declaration*/0;
8402 };
8403
8404 if (!NewRC != !OldRC) {
8405 if (Complain)
8406 Diagnose();
8407 return false;
8408 }
8409
8410 if (NewRC) {
8411 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8412 NewRC)) {
8413 if (Complain)
8414 Diagnose();
8415 return false;
8416 }
8417 }
8418 }
8419
8420 return true;
8421}
8422
8423bool
8425 if (!S)
8426 return false;
8427
8428 // Find the nearest enclosing declaration scope.
8429 S = S->getDeclParent();
8430
8431 // C++ [temp.pre]p6: [P2096]
8432 // A template, explicit specialization, or partial specialization shall not
8433 // have C linkage.
8434 DeclContext *Ctx = S->getEntity();
8435 if (Ctx && Ctx->isExternCContext()) {
8436 SourceRange Range =
8437 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8438 ? TemplateParams->getParam(0)->getSourceRange()
8439 : TemplateParams->getSourceRange();
8440 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8441 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8442 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8443 return true;
8444 }
8445 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8446
8447 // C++ [temp]p2:
8448 // A template-declaration can appear only as a namespace scope or
8449 // class scope declaration.
8450 // C++ [temp.expl.spec]p3:
8451 // An explicit specialization may be declared in any scope in which the
8452 // corresponding primary template may be defined.
8453 // C++ [temp.class.spec]p6: [P2096]
8454 // A partial specialization may be declared in any scope in which the
8455 // corresponding primary template may be defined.
8456 if (Ctx) {
8457 if (Ctx->isFileContext())
8458 return false;
8459 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8460 // C++ [temp.mem]p2:
8461 // A local class shall not have member templates.
8462 if (RD->isLocalClass())
8463 return Diag(TemplateParams->getTemplateLoc(),
8464 diag::err_template_inside_local_class)
8465 << TemplateParams->getSourceRange();
8466 else
8467 return false;
8468 }
8469 }
8470
8471 return Diag(TemplateParams->getTemplateLoc(),
8472 diag::err_template_outside_namespace_or_class_scope)
8473 << TemplateParams->getSourceRange();
8474}
8475
8476/// Determine what kind of template specialization the given declaration
8477/// is.
8479 if (!D)
8480 return TSK_Undeclared;
8481
8482 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8483 return Record->getTemplateSpecializationKind();
8484 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8485 return Function->getTemplateSpecializationKind();
8486 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8487 return Var->getTemplateSpecializationKind();
8488
8489 return TSK_Undeclared;
8490}
8491
8492/// Check whether a specialization is well-formed in the current
8493/// context.
8494///
8495/// This routine determines whether a template specialization can be declared
8496/// in the current context (C++ [temp.expl.spec]p2).
8497///
8498/// \param S the semantic analysis object for which this check is being
8499/// performed.
8500///
8501/// \param Specialized the entity being specialized or instantiated, which
8502/// may be a kind of template (class template, function template, etc.) or
8503/// a member of a class template (member function, static data member,
8504/// member class).
8505///
8506/// \param PrevDecl the previous declaration of this entity, if any.
8507///
8508/// \param Loc the location of the explicit specialization or instantiation of
8509/// this entity.
8510///
8511/// \param IsPartialSpecialization whether this is a partial specialization of
8512/// a class template.
8513///
8514/// \returns true if there was an error that we cannot recover from, false
8515/// otherwise.
8517 NamedDecl *Specialized,
8518 NamedDecl *PrevDecl,
8519 SourceLocation Loc,
8521 // Keep these "kind" numbers in sync with the %select statements in the
8522 // various diagnostics emitted by this routine.
8523 int EntityKind = 0;
8524 if (isa<ClassTemplateDecl>(Specialized))
8525 EntityKind = IsPartialSpecialization? 1 : 0;
8526 else if (isa<VarTemplateDecl>(Specialized))
8527 EntityKind = IsPartialSpecialization ? 3 : 2;
8528 else if (isa<FunctionTemplateDecl>(Specialized))
8529 EntityKind = 4;
8530 else if (isa<CXXMethodDecl>(Specialized))
8531 EntityKind = 5;
8532 else if (isa<VarDecl>(Specialized))
8533 EntityKind = 6;
8534 else if (isa<RecordDecl>(Specialized))
8535 EntityKind = 7;
8536 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8537 EntityKind = 8;
8538 else {
8539 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8540 << S.getLangOpts().CPlusPlus11;
8541 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8542 return true;
8543 }
8544
8545 // C++ [temp.expl.spec]p2:
8546 // An explicit specialization may be declared in any scope in which
8547 // the corresponding primary template may be defined.
8549 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8550 << Specialized;
8551 return true;
8552 }
8553
8554 // C++ [temp.class.spec]p6:
8555 // A class template partial specialization may be declared in any
8556 // scope in which the primary template may be defined.
8557 DeclContext *SpecializedContext =
8558 Specialized->getDeclContext()->getRedeclContext();
8560
8561 // Make sure that this redeclaration (or definition) occurs in the same
8562 // scope or an enclosing namespace.
8563 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8564 : DC->Equals(SpecializedContext))) {
8565 if (isa<TranslationUnitDecl>(SpecializedContext))
8566 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8567 << EntityKind << Specialized;
8568 else {
8569 auto *ND = cast<NamedDecl>(SpecializedContext);
8570 int Diag = diag::err_template_spec_redecl_out_of_scope;
8571 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8572 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8573 S.Diag(Loc, Diag) << EntityKind << Specialized
8574 << ND << isa<CXXRecordDecl>(ND);
8575 }
8576
8577 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8578
8579 // Don't allow specializing in the wrong class during error recovery.
8580 // Otherwise, things can go horribly wrong.
8581 if (DC->isRecord())
8582 return true;
8583 }
8584
8585 return false;
8586}
8587
8589 if (!E->isTypeDependent())
8590 return SourceLocation();
8591 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8592 Checker.TraverseStmt(E);
8593 if (Checker.MatchLoc.isInvalid())
8594 return E->getSourceRange();
8595 return Checker.MatchLoc;
8596}
8597
8598static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8599 if (!TL.getType()->isDependentType())
8600 return SourceLocation();
8601 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8602 Checker.TraverseTypeLoc(TL);
8603 if (Checker.MatchLoc.isInvalid())
8604 return TL.getSourceRange();
8605 return Checker.MatchLoc;
8606}
8607
8608/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8609/// that checks non-type template partial specialization arguments.
8611 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8612 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8613 bool HasError = false;
8614 for (unsigned I = 0; I != NumArgs; ++I) {
8615 if (Args[I].getKind() == TemplateArgument::Pack) {
8617 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8618 Args[I].pack_size(), IsDefaultArgument))
8619 return true;
8620
8621 continue;
8622 }
8623
8624 if (Args[I].getKind() != TemplateArgument::Expression)
8625 continue;
8626
8627 Expr *ArgExpr = Args[I].getAsExpr();
8628 if (ArgExpr->containsErrors()) {
8629 HasError = true;
8630 continue;
8631 }
8632
8633 // We can have a pack expansion of any of the bullets below.
8634 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8635 ArgExpr = Expansion->getPattern();
8636
8637 // Strip off any implicit casts we added as part of type checking.
8638 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8639 ArgExpr = ICE->getSubExpr();
8640
8641 // C++ [temp.class.spec]p8:
8642 // A non-type argument is non-specialized if it is the name of a
8643 // non-type parameter. All other non-type arguments are
8644 // specialized.
8645 //
8646 // Below, we check the two conditions that only apply to
8647 // specialized non-type arguments, so skip any non-specialized
8648 // arguments.
8649 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8650 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8651 continue;
8652
8653 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8654 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8655 continue;
8656 }
8657
8658 // C++ [temp.class.spec]p9:
8659 // Within the argument list of a class template partial
8660 // specialization, the following restrictions apply:
8661 // -- A partially specialized non-type argument expression
8662 // shall not involve a template parameter of the partial
8663 // specialization except when the argument expression is a
8664 // simple identifier.
8665 // -- The type of a template parameter corresponding to a
8666 // specialized non-type argument shall not be dependent on a
8667 // parameter of the specialization.
8668 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8669 // We implement a compromise between the original rules and DR1315:
8670 // -- A specialized non-type template argument shall not be
8671 // type-dependent and the corresponding template parameter
8672 // shall have a non-dependent type.
8673 SourceRange ParamUseRange =
8674 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8675 if (ParamUseRange.isValid()) {
8676 if (IsDefaultArgument) {
8677 S.Diag(TemplateNameLoc,
8678 diag::err_dependent_non_type_arg_in_partial_spec);
8679 S.Diag(ParamUseRange.getBegin(),
8680 diag::note_dependent_non_type_default_arg_in_partial_spec)
8681 << ParamUseRange;
8682 } else {
8683 S.Diag(ParamUseRange.getBegin(),
8684 diag::err_dependent_non_type_arg_in_partial_spec)
8685 << ParamUseRange;
8686 }
8687 return true;
8688 }
8689
8690 ParamUseRange = findTemplateParameter(
8691 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8692 if (ParamUseRange.isValid()) {
8693 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8694 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8695 << Param->getType();
8697 return true;
8698 }
8699 }
8700
8701 return HasError;
8702}
8703
8705 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8706 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8707 // We have to be conservative when checking a template in a dependent
8708 // context.
8709 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8710 return false;
8711
8712 TemplateParameterList *TemplateParams =
8713 PrimaryTemplate->getTemplateParameters();
8714 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8716 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8717 if (!Param)
8718 continue;
8719
8720 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8721 Param, &TemplateArgs[I],
8722 1, I >= NumExplicit))
8723 return true;
8724 }
8725
8726 return false;
8727}
8728
8730 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8731 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8733 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8734 assert(TUK != TagUseKind::Reference && "References are not specializations");
8735
8736 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8737 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8738 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8739
8740 // Find the class template we're specializing
8741 TemplateName Name = TemplateId.Template.get();
8743 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8744
8745 if (!ClassTemplate) {
8746 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8747 << (Name.getAsTemplateDecl() &&
8749 return true;
8750 }
8751
8752 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8753 auto Message = DSA->getMessage();
8754 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8755 << ClassTemplate << !Message.empty() << Message;
8756 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8757 }
8758
8759 if (S->isTemplateParamScope())
8760 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8761
8762 DeclContext *DC = ClassTemplate->getDeclContext();
8763
8764 bool isMemberSpecialization = false;
8765 bool isPartialSpecialization = false;
8766
8767 if (SS.isSet()) {
8768 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8769 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8770 TemplateNameLoc, &TemplateId,
8771 /*IsMemberSpecialization=*/false))
8772 return true;
8773 }
8774
8775 // Check the validity of the template headers that introduce this
8776 // template.
8777 // FIXME: We probably shouldn't complain about these headers for
8778 // friend declarations.
8779 bool Invalid = false;
8780 TemplateParameterList *TemplateParams =
8782 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8783 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8784 if (Invalid)
8785 return true;
8786
8787 // Check that we can declare a template specialization here.
8788 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8789 return true;
8790
8791 if (TemplateParams && DC->isDependentContext()) {
8792 ContextRAII SavedContext(*this, DC);
8794 return true;
8795 }
8796
8797 if (TemplateParams && TemplateParams->size() > 0) {
8798 isPartialSpecialization = true;
8799
8800 if (TUK == TagUseKind::Friend) {
8801 Diag(KWLoc, diag::err_partial_specialization_friend)
8802 << SourceRange(LAngleLoc, RAngleLoc);
8803 return true;
8804 }
8805
8806 // C++ [temp.class.spec]p10:
8807 // The template parameter list of a specialization shall not
8808 // contain default template argument values.
8809 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8810 Decl *Param = TemplateParams->getParam(I);
8811 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8812 if (TTP->hasDefaultArgument()) {
8813 Diag(TTP->getDefaultArgumentLoc(),
8814 diag::err_default_arg_in_partial_spec);
8815 TTP->removeDefaultArgument();
8816 }
8817 } else if (NonTypeTemplateParmDecl *NTTP
8818 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8819 if (NTTP->hasDefaultArgument()) {
8820 Diag(NTTP->getDefaultArgumentLoc(),
8821 diag::err_default_arg_in_partial_spec)
8822 << NTTP->getDefaultArgument().getSourceRange();
8823 NTTP->removeDefaultArgument();
8824 }
8825 } else {
8827 if (TTP->hasDefaultArgument()) {
8829 diag::err_default_arg_in_partial_spec)
8831 TTP->removeDefaultArgument();
8832 }
8833 }
8834 }
8835 } else if (TemplateParams) {
8836 if (TUK == TagUseKind::Friend)
8837 Diag(KWLoc, diag::err_template_spec_friend)
8839 SourceRange(TemplateParams->getTemplateLoc(),
8840 TemplateParams->getRAngleLoc()))
8841 << SourceRange(LAngleLoc, RAngleLoc);
8842 } else {
8843 assert(TUK == TagUseKind::Friend &&
8844 "should have a 'template<>' for this decl");
8845 }
8846
8847 // Check that the specialization uses the same tag kind as the
8848 // original template.
8850 assert(Kind != TagTypeKind::Enum &&
8851 "Invalid enum tag in class template spec!");
8852 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8853 TUK == TagUseKind::Definition, KWLoc,
8854 ClassTemplate->getIdentifier())) {
8855 Diag(KWLoc, diag::err_use_with_wrong_tag)
8856 << ClassTemplate
8858 ClassTemplate->getTemplatedDecl()->getKindName());
8859 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8860 diag::note_previous_use);
8861 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8862 }
8863
8864 // Translate the parser's template argument list in our AST format.
8865 TemplateArgumentListInfo TemplateArgs =
8866 makeTemplateArgumentListInfo(*this, TemplateId);
8867
8868 // Check for unexpanded parameter packs in any of the template arguments.
8869 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8870 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8871 isPartialSpecialization
8874 return true;
8875
8876 // Check that the template argument list is well-formed for this
8877 // template.
8879 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8880 /*DefaultArgs=*/{},
8881 /*PartialTemplateArgs=*/false, CTAI,
8882 /*UpdateArgsWithConversions=*/true))
8883 return true;
8884
8885 // Find the class template (partial) specialization declaration that
8886 // corresponds to these arguments.
8887 if (isPartialSpecialization) {
8889 TemplateArgs.size(),
8890 CTAI.CanonicalConverted))
8891 return true;
8892
8893 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8894 // also do it during instantiation.
8895 if (!Name.isDependent() &&
8896 !TemplateSpecializationType::anyDependentTemplateArguments(
8897 TemplateArgs, CTAI.CanonicalConverted)) {
8898 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8899 << ClassTemplate->getDeclName();
8900 isPartialSpecialization = false;
8901 Invalid = true;
8902 }
8903 }
8904
8905 void *InsertPos = nullptr;
8906 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8907
8908 if (isPartialSpecialization)
8909 PrevDecl = ClassTemplate->findPartialSpecialization(
8910 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8911 else
8912 PrevDecl =
8913 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8914
8916
8917 // Check whether we can declare a class template specialization in
8918 // the current scope.
8919 if (TUK != TagUseKind::Friend &&
8921 TemplateNameLoc,
8922 isPartialSpecialization))
8923 return true;
8924
8925 if (!isPartialSpecialization) {
8926 // Create a new class template specialization declaration node for
8927 // this explicit specialization or friend declaration.
8929 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8930 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8931 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8933 if (TemplateParameterLists.size() > 0) {
8934 Specialization->setTemplateParameterListsInfo(Context,
8935 TemplateParameterLists);
8936 }
8937
8938 if (!PrevDecl)
8939 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8940 } else {
8942 Context.getCanonicalTemplateSpecializationType(
8944 TemplateName(ClassTemplate->getCanonicalDecl()),
8945 CTAI.CanonicalConverted));
8946 if (Context.hasSameType(
8947 CanonType,
8948 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8949 (!Context.getLangOpts().CPlusPlus20 ||
8950 !TemplateParams->hasAssociatedConstraints())) {
8951 // C++ [temp.class.spec]p9b3:
8952 //
8953 // -- The argument list of the specialization shall not be identical
8954 // to the implicit argument list of the primary template.
8955 //
8956 // This rule has since been removed, because it's redundant given DR1495,
8957 // but we keep it because it produces better diagnostics and recovery.
8958 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8959 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8960 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8961 return CheckClassTemplate(
8962 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8963 TemplateNameLoc, Attr, TemplateParams, AS_none,
8964 /*ModulePrivateLoc=*/SourceLocation(),
8965 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8966 TemplateParameterLists.data());
8967 }
8968
8969 // Create a new class template partial specialization declaration node.
8971 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8974 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8975 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8976 Partial->setTemplateArgsAsWritten(TemplateArgs);
8977 SetNestedNameSpecifier(*this, Partial, SS);
8978 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8980 Context, TemplateParameterLists.drop_back(1));
8981 }
8982
8983 if (!PrevPartial)
8984 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8985 Specialization = Partial;
8986
8987 // If we are providing an explicit specialization of a member class
8988 // template specialization, make a note of that.
8989 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8990 PrevPartial->setMemberSpecialization();
8991
8993 }
8994
8995 // C++ [temp.expl.spec]p6:
8996 // If a template, a member template or the member of a class template is
8997 // explicitly specialized then that specialization shall be declared
8998 // before the first use of that specialization that would cause an implicit
8999 // instantiation to take place, in every translation unit in which such a
9000 // use occurs; no diagnostic is required.
9001 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9002 bool Okay = false;
9003 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9004 // Is there any previous explicit specialization declaration?
9006 Okay = true;
9007 break;
9008 }
9009 }
9010
9011 if (!Okay) {
9012 SourceRange Range(TemplateNameLoc, RAngleLoc);
9013 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9014 << Context.getCanonicalTagType(Specialization) << Range;
9015
9016 Diag(PrevDecl->getPointOfInstantiation(),
9017 diag::note_instantiation_required_here)
9018 << (PrevDecl->getTemplateSpecializationKind()
9020 return true;
9021 }
9022 }
9023
9024 // If this is not a friend, note that this is an explicit specialization.
9025 if (TUK != TagUseKind::Friend)
9026 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9027
9028 // Check that this isn't a redefinition of this specialization.
9029 if (TUK == TagUseKind::Definition) {
9030 RecordDecl *Def = Specialization->getDefinition();
9031 NamedDecl *Hidden = nullptr;
9032 bool HiddenDefVisible = false;
9033 if (Def && SkipBody &&
9034 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9035 SkipBody->ShouldSkip = true;
9036 SkipBody->Previous = Def;
9037 if (!HiddenDefVisible && Hidden)
9039 } else if (Def) {
9040 SourceRange Range(TemplateNameLoc, RAngleLoc);
9041 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9042 Diag(Def->getLocation(), diag::note_previous_definition);
9043 Specialization->setInvalidDecl();
9044 return true;
9045 }
9046 }
9047
9050
9051 // Add alignment attributes if necessary; these attributes are checked when
9052 // the ASTContext lays out the structure.
9053 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9054 if (LangOpts.HLSL)
9055 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9058 }
9059
9060 if (ModulePrivateLoc.isValid())
9061 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9062 << (isPartialSpecialization? 1 : 0)
9063 << FixItHint::CreateRemoval(ModulePrivateLoc);
9064
9065 // C++ [temp.expl.spec]p9:
9066 // A template explicit specialization is in the scope of the
9067 // namespace in which the template was defined.
9068 //
9069 // We actually implement this paragraph where we set the semantic
9070 // context (in the creation of the ClassTemplateSpecializationDecl),
9071 // but we also maintain the lexical context where the actual
9072 // definition occurs.
9073 Specialization->setLexicalDeclContext(CurContext);
9074
9075 // We may be starting the definition of this specialization.
9076 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9077 Specialization->startDefinition();
9078
9079 if (TUK == TagUseKind::Friend) {
9080 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9081 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9082 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9084 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9085 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9086
9087 // Build the fully-sugared type for this class template
9088 // specialization as the user wrote in the specialization
9089 // itself. This means that we'll pretty-print the type retrieved
9090 // from the specialization's declaration the way that the user
9091 // actually wrote the specialization, rather than formatting the
9092 // name based on the "canonical" representation used to store the
9093 // template arguments in the specialization.
9095 TemplateNameLoc,
9096 WrittenTy,
9097 /*FIXME:*/KWLoc);
9098 Friend->setAccess(AS_public);
9099 CurContext->addDecl(Friend);
9100 } else {
9101 // Add the specialization into its lexical context, so that it can
9102 // be seen when iterating through the list of declarations in that
9103 // context. However, specializations are not found by name lookup.
9104 CurContext->addDecl(Specialization);
9105 }
9106
9107 if (SkipBody && SkipBody->ShouldSkip)
9108 return SkipBody->Previous;
9109
9110 Specialization->setInvalidDecl(Invalid);
9112 return Specialization;
9113}
9114
9116 MultiTemplateParamsArg TemplateParameterLists,
9117 Declarator &D) {
9118 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9119 ActOnDocumentableDecl(NewDecl);
9120 return NewDecl;
9121}
9122
9124 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9125 const IdentifierInfo *Name, SourceLocation NameLoc) {
9126 DeclContext *DC = CurContext;
9127
9128 if (!DC->getRedeclContext()->isFileContext()) {
9129 Diag(NameLoc,
9130 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9131 return nullptr;
9132 }
9133
9134 if (TemplateParameterLists.size() > 1) {
9135 Diag(NameLoc, diag::err_concept_extra_headers);
9136 return nullptr;
9137 }
9138
9139 TemplateParameterList *Params = TemplateParameterLists.front();
9140
9141 if (Params->size() == 0) {
9142 Diag(NameLoc, diag::err_concept_no_parameters);
9143 return nullptr;
9144 }
9145
9146 // Ensure that the parameter pack, if present, is the last parameter in the
9147 // template.
9148 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9149 ParamEnd = Params->end();
9150 ParamIt != ParamEnd; ++ParamIt) {
9151 Decl const *Param = *ParamIt;
9152 if (Param->isParameterPack()) {
9153 if (++ParamIt == ParamEnd)
9154 break;
9155 Diag(Param->getLocation(),
9156 diag::err_template_param_pack_must_be_last_template_parameter);
9157 return nullptr;
9158 }
9159 }
9160
9161 ConceptDecl *NewDecl =
9162 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9163
9164 if (NewDecl->hasAssociatedConstraints()) {
9165 // C++2a [temp.concept]p4:
9166 // A concept shall not have associated constraints.
9167 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9168 NewDecl->setInvalidDecl();
9169 }
9170
9171 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9172 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9174 LookupName(Previous, S);
9175 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9176 /*AllowInlineNamespace*/ false);
9177
9178 // We cannot properly handle redeclarations until we parse the constraint
9179 // expression, so only inject the name if we are sure we are not redeclaring a
9180 // symbol
9181 if (Previous.empty())
9182 PushOnScopeChains(NewDecl, S, true);
9183
9184 return NewDecl;
9185}
9186
9188 bool Found = false;
9190 while (F.hasNext()) {
9191 NamedDecl *D = F.next();
9192 if (D == C) {
9193 F.erase();
9194 Found = true;
9195 break;
9196 }
9197 }
9198 F.done();
9199 return Found;
9200}
9201
9204 Expr *ConstraintExpr,
9205 const ParsedAttributesView &Attrs) {
9206 assert(!C->hasDefinition() && "Concept already defined");
9207 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9208 C->setInvalidDecl();
9209 return nullptr;
9210 }
9211 C->setDefinition(ConstraintExpr);
9212 ProcessDeclAttributeList(S, C, Attrs);
9213
9214 // Check for conflicting previous declaration.
9215 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9216 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9218 LookupName(Previous, S);
9219 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9220 /*AllowInlineNamespace*/ false);
9221 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9222 bool AddToScope = true;
9223 CheckConceptRedefinition(C, Previous, AddToScope);
9224
9226 if (!WasAlreadyAdded && AddToScope)
9227 PushOnScopeChains(C, S);
9228
9229 return C;
9230}
9231
9233 LookupResult &Previous, bool &AddToScope) {
9234 AddToScope = true;
9235
9236 if (Previous.empty())
9237 return;
9238
9239 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9240 if (!OldConcept) {
9241 auto *Old = Previous.getRepresentativeDecl();
9242 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9243 << NewDecl->getDeclName();
9244 notePreviousDefinition(Old, NewDecl->getLocation());
9245 AddToScope = false;
9246 return;
9247 }
9248 // Check if we can merge with a concept declaration.
9249 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9250 if (!IsSame) {
9251 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9252 << NewDecl->getDeclName();
9253 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9254 AddToScope = false;
9255 return;
9256 }
9257 if (hasReachableDefinition(OldConcept) &&
9258 IsRedefinitionInModule(NewDecl, OldConcept)) {
9259 Diag(NewDecl->getLocation(), diag::err_redefinition)
9260 << NewDecl->getDeclName();
9261 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9262 AddToScope = false;
9263 return;
9264 }
9265 if (!Previous.isSingleResult()) {
9266 // FIXME: we should produce an error in case of ambig and failed lookups.
9267 // Other decls (e.g. namespaces) also have this shortcoming.
9268 return;
9269 }
9270 // We unwrap canonical decl late to check for module visibility.
9271 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9272}
9273
9275 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9276 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9277 Diag(Loc, diag::err_recursive_concept) << CE;
9278 Diag(CE->getLocation(), diag::note_declared_at);
9279 return true;
9280 }
9281 // Concept template parameters don't have a definition and can't
9282 // be defined recursively.
9283 return false;
9284}
9285
9286/// \brief Strips various properties off an implicit instantiation
9287/// that has just been explicitly specialized.
9288static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9289 if (MinGW || (isa<FunctionDecl>(D) &&
9290 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9291 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9292
9293 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9294 FD->setInlineSpecified(false);
9295}
9296
9297/// Compute the diagnostic location for an explicit instantiation
9298// declaration or definition.
9300 NamedDecl* D, SourceLocation PointOfInstantiation) {
9301 // Explicit instantiations following a specialization have no effect and
9302 // hence no PointOfInstantiation. In that case, walk decl backwards
9303 // until a valid name loc is found.
9304 SourceLocation PrevDiagLoc = PointOfInstantiation;
9305 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9306 Prev = Prev->getPreviousDecl()) {
9307 PrevDiagLoc = Prev->getLocation();
9308 }
9309 assert(PrevDiagLoc.isValid() &&
9310 "Explicit instantiation without point of instantiation?");
9311 return PrevDiagLoc;
9312}
9313
9314bool
9317 NamedDecl *PrevDecl,
9319 SourceLocation PrevPointOfInstantiation,
9320 bool &HasNoEffect) {
9321 HasNoEffect = false;
9322
9323 switch (NewTSK) {
9324 case TSK_Undeclared:
9326 assert(
9327 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9328 "previous declaration must be implicit!");
9329 return false;
9330
9332 switch (PrevTSK) {
9333 case TSK_Undeclared:
9335 // Okay, we're just specializing something that is either already
9336 // explicitly specialized or has merely been mentioned without any
9337 // instantiation.
9338 return false;
9339
9341 if (PrevPointOfInstantiation.isInvalid()) {
9342 // The declaration itself has not actually been instantiated, so it is
9343 // still okay to specialize it.
9345 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9346 return false;
9347 }
9348 // Fall through
9349 [[fallthrough]];
9350
9353 assert((PrevTSK == TSK_ImplicitInstantiation ||
9354 PrevPointOfInstantiation.isValid()) &&
9355 "Explicit instantiation without point of instantiation?");
9356
9357 // C++ [temp.expl.spec]p6:
9358 // If a template, a member template or the member of a class template
9359 // is explicitly specialized then that specialization shall be declared
9360 // before the first use of that specialization that would cause an
9361 // implicit instantiation to take place, in every translation unit in
9362 // which such a use occurs; no diagnostic is required.
9363 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9364 // Is there any previous explicit specialization declaration?
9366 return false;
9367 }
9368
9369 Diag(NewLoc, diag::err_specialization_after_instantiation)
9370 << PrevDecl;
9371 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9372 << (PrevTSK != TSK_ImplicitInstantiation);
9373
9374 return true;
9375 }
9376 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9377
9379 switch (PrevTSK) {
9381 // This explicit instantiation declaration is redundant (that's okay).
9382 HasNoEffect = true;
9383 return false;
9384
9385 case TSK_Undeclared:
9387 // We're explicitly instantiating something that may have already been
9388 // implicitly instantiated; that's fine.
9389 return false;
9390
9392 // C++0x [temp.explicit]p4:
9393 // For a given set of template parameters, if an explicit instantiation
9394 // of a template appears after a declaration of an explicit
9395 // specialization for that template, the explicit instantiation has no
9396 // effect.
9397 HasNoEffect = true;
9398 return false;
9399
9401 // C++0x [temp.explicit]p10:
9402 // If an entity is the subject of both an explicit instantiation
9403 // declaration and an explicit instantiation definition in the same
9404 // translation unit, the definition shall follow the declaration.
9405 Diag(NewLoc,
9406 diag::err_explicit_instantiation_declaration_after_definition);
9407
9408 // Explicit instantiations following a specialization have no effect and
9409 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9410 // until a valid name loc is found.
9411 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9412 diag::note_explicit_instantiation_definition_here);
9413 HasNoEffect = true;
9414 return false;
9415 }
9416 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9417
9419 switch (PrevTSK) {
9420 case TSK_Undeclared:
9422 // We're explicitly instantiating something that may have already been
9423 // implicitly instantiated; that's fine.
9424 return false;
9425
9427 // C++ DR 259, C++0x [temp.explicit]p4:
9428 // For a given set of template parameters, if an explicit
9429 // instantiation of a template appears after a declaration of
9430 // an explicit specialization for that template, the explicit
9431 // instantiation has no effect.
9432 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9433 << PrevDecl;
9434 Diag(PrevDecl->getLocation(),
9435 diag::note_previous_template_specialization);
9436 HasNoEffect = true;
9437 return false;
9438
9440 // We're explicitly instantiating a definition for something for which we
9441 // were previously asked to suppress instantiations. That's fine.
9442
9443 // C++0x [temp.explicit]p4:
9444 // For a given set of template parameters, if an explicit instantiation
9445 // of a template appears after a declaration of an explicit
9446 // specialization for that template, the explicit instantiation has no
9447 // effect.
9448 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9449 // Is there any previous explicit specialization declaration?
9451 HasNoEffect = true;
9452 break;
9453 }
9454 }
9455
9456 return false;
9457
9459 // C++0x [temp.spec]p5:
9460 // For a given template and a given set of template-arguments,
9461 // - an explicit instantiation definition shall appear at most once
9462 // in a program,
9463
9464 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9465 Diag(NewLoc, (getLangOpts().MSVCCompat)
9466 ? diag::ext_explicit_instantiation_duplicate
9467 : diag::err_explicit_instantiation_duplicate)
9468 << PrevDecl;
9469 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9470 diag::note_previous_explicit_instantiation);
9471 HasNoEffect = true;
9472 return false;
9473 }
9474 }
9475
9476 llvm_unreachable("Missing specialization/instantiation case?");
9477}
9478
9480 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9482 // Remove anything from Previous that isn't a function template in
9483 // the correct context.
9484 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9485 LookupResult::Filter F = Previous.makeFilter();
9486 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9487 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9488 while (F.hasNext()) {
9489 NamedDecl *D = F.next()->getUnderlyingDecl();
9490 if (!isa<FunctionTemplateDecl>(D)) {
9491 F.erase();
9492 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9493 continue;
9494 }
9495
9496 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9498 F.erase();
9499 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9500 continue;
9501 }
9502 }
9503 F.done();
9504
9505 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9506 if (Previous.empty()) {
9507 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9508 << IsFriend;
9509 for (auto &P : DiscardedCandidates)
9510 Diag(P.second->getLocation(),
9511 diag::note_dependent_function_template_spec_discard_reason)
9512 << P.first << IsFriend;
9513 return true;
9514 }
9515
9517 ExplicitTemplateArgs);
9518 return false;
9519}
9520
9522 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9523 LookupResult &Previous, bool QualifiedFriend) {
9524 // The set of function template specializations that could match this
9525 // explicit function template specialization.
9526 UnresolvedSet<8> Candidates;
9527 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9528 /*ForTakingAddress=*/false);
9529
9530 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9531 ConvertedTemplateArgs;
9532
9533 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9534 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9535 I != E; ++I) {
9536 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9537 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9538 // Only consider templates found within the same semantic lookup scope as
9539 // FD.
9540 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9542 continue;
9543
9544 QualType FT = FD->getType();
9545 // C++11 [dcl.constexpr]p8:
9546 // A constexpr specifier for a non-static member function that is not
9547 // a constructor declares that member function to be const.
9548 //
9549 // When matching a constexpr member function template specialization
9550 // against the primary template, we don't yet know whether the
9551 // specialization has an implicit 'const' (because we don't know whether
9552 // it will be a static member function until we know which template it
9553 // specializes). This rule was removed in C++14.
9554 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9555 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9557 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9558 if (OldMD && OldMD->isConst()) {
9559 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9561 EPI.TypeQuals.addConst();
9562 FT = Context.getFunctionType(FPT->getReturnType(),
9563 FPT->getParamTypes(), EPI);
9564 }
9565 }
9566
9568 if (ExplicitTemplateArgs)
9569 Args = *ExplicitTemplateArgs;
9570
9571 // C++ [temp.expl.spec]p11:
9572 // A trailing template-argument can be left unspecified in the
9573 // template-id naming an explicit function template specialization
9574 // provided it can be deduced from the function argument type.
9575 // Perform template argument deduction to determine whether we may be
9576 // specializing this template.
9577 // FIXME: It is somewhat wasteful to build
9578 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9579 FunctionDecl *Specialization = nullptr;
9581 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9582 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9584 // Template argument deduction failed; record why it failed, so
9585 // that we can provide nifty diagnostics.
9586 FailedCandidates.addCandidate().set(
9587 I.getPair(), FunTmpl->getTemplatedDecl(),
9588 MakeDeductionFailureInfo(Context, TDK, Info));
9589 (void)TDK;
9590 continue;
9591 }
9592
9593 // Target attributes are part of the cuda function signature, so
9594 // the deduced template's cuda target must match that of the
9595 // specialization. Given that C++ template deduction does not
9596 // take target attributes into account, we reject candidates
9597 // here that have a different target.
9598 if (LangOpts.CUDA &&
9599 CUDA().IdentifyTarget(Specialization,
9600 /* IgnoreImplicitHDAttr = */ true) !=
9601 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9602 FailedCandidates.addCandidate().set(
9603 I.getPair(), FunTmpl->getTemplatedDecl(),
9606 continue;
9607 }
9608
9609 // Record this candidate.
9610 if (ExplicitTemplateArgs)
9611 ConvertedTemplateArgs[Specialization] = std::move(Args);
9612 Candidates.addDecl(Specialization, I.getAccess());
9613 }
9614 }
9615
9616 // For a qualified friend declaration (with no explicit marker to indicate
9617 // that a template specialization was intended), note all (template and
9618 // non-template) candidates.
9619 if (QualifiedFriend && Candidates.empty()) {
9620 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9621 << FD->getDeclName() << FDLookupContext;
9622 // FIXME: We should form a single candidate list and diagnose all
9623 // candidates at once, to get proper sorting and limiting.
9624 for (auto *OldND : Previous) {
9625 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9626 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9627 }
9628 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9629 return true;
9630 }
9631
9632 // Find the most specialized function template.
9634 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9635 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9636 PDiag(diag::err_function_template_spec_ambiguous)
9637 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9638 PDiag(diag::note_function_template_spec_matched));
9639
9640 if (Result == Candidates.end())
9641 return true;
9642
9643 // Ignore access information; it doesn't figure into redeclaration checking.
9645
9646 if (const auto *PT = Specialization->getPrimaryTemplate();
9647 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9648 auto Message = DSA->getMessage();
9649 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9650 << PT << !Message.empty() << Message;
9651 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9652 }
9653
9654 // C++23 [except.spec]p13:
9655 // An exception specification is considered to be needed when:
9656 // - [...]
9657 // - the exception specification is compared to that of another declaration
9658 // (e.g., an explicit specialization or an overriding virtual function);
9659 // - [...]
9660 //
9661 // The exception specification of a defaulted function is evaluated as
9662 // described above only when needed; similarly, the noexcept-specifier of a
9663 // specialization of a function template or member function of a class
9664 // template is instantiated only when needed.
9665 //
9666 // The standard doesn't specify what the "comparison with another declaration"
9667 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9668 // not state which properties of an explicit specialization must match the
9669 // primary template.
9670 //
9671 // We assume that an explicit specialization must correspond with (per
9672 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9673 // the declaration produced by substitution into the function template.
9674 //
9675 // Since the determination whether two function declarations correspond does
9676 // not consider exception specification, we only need to instantiate it once
9677 // we determine the primary template when comparing types per
9678 // [basic.link]p11.1.
9679 auto *SpecializationFPT =
9680 Specialization->getType()->castAs<FunctionProtoType>();
9681 // If the function has a dependent exception specification, resolve it after
9682 // we have selected the primary template so we can check whether it matches.
9683 if (getLangOpts().CPlusPlus17 &&
9684 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9685 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9686 return true;
9687
9689 = Specialization->getTemplateSpecializationInfo();
9690 assert(SpecInfo && "Function template specialization info missing?");
9691
9692 // Note: do not overwrite location info if previous template
9693 // specialization kind was explicit.
9695 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9696 Specialization->setLocation(FD->getLocation());
9697 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9698 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9699 // function can differ from the template declaration with respect to
9700 // the constexpr specifier.
9701 // FIXME: We need an update record for this AST mutation.
9702 // FIXME: What if there are multiple such prior declarations (for instance,
9703 // from different modules)?
9704 Specialization->setConstexprKind(FD->getConstexprKind());
9705 }
9706
9707 // FIXME: Check if the prior specialization has a point of instantiation.
9708 // If so, we have run afoul of .
9709
9710 // If this is a friend declaration, then we're not really declaring
9711 // an explicit specialization.
9712 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9713
9714 // Check the scope of this explicit specialization.
9715 if (!isFriend &&
9717 Specialization->getPrimaryTemplate(),
9719 false))
9720 return true;
9721
9722 // C++ [temp.expl.spec]p6:
9723 // If a template, a member template or the member of a class template is
9724 // explicitly specialized then that specialization shall be declared
9725 // before the first use of that specialization that would cause an implicit
9726 // instantiation to take place, in every translation unit in which such a
9727 // use occurs; no diagnostic is required.
9728 bool HasNoEffect = false;
9729 if (!isFriend &&
9734 SpecInfo->getPointOfInstantiation(),
9735 HasNoEffect))
9736 return true;
9737
9738 // Mark the prior declaration as an explicit specialization, so that later
9739 // clients know that this is an explicit specialization.
9740 // A dependent friend specialization which has a definition should be treated
9741 // as explicit specialization, despite being invalid.
9742 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9743 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9744 // Since explicit specializations do not inherit '=delete' from their
9745 // primary function template - check if the 'specialization' that was
9746 // implicitly generated (during template argument deduction for partial
9747 // ordering) from the most specialized of all the function templates that
9748 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9749 // first check that it was implicitly generated during template argument
9750 // deduction by making sure it wasn't referenced, and then reset the deleted
9751 // flag to not-deleted, so that we can inherit that information from 'FD'.
9752 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9753 !Specialization->getCanonicalDecl()->isReferenced()) {
9754 // FIXME: This assert will not hold in the presence of modules.
9755 assert(
9756 Specialization->getCanonicalDecl() == Specialization &&
9757 "This must be the only existing declaration of this specialization");
9758 // FIXME: We need an update record for this AST mutation.
9759 Specialization->setDeletedAsWritten(false);
9760 }
9761 // FIXME: We need an update record for this AST mutation.
9764 }
9765
9766 // Turn the given function declaration into a function template
9767 // specialization, with the template arguments from the previous
9768 // specialization.
9769 // Take copies of (semantic and syntactic) template argument lists.
9771 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9772 FD->setFunctionTemplateSpecialization(
9773 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9775 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9776
9777 // A function template specialization inherits the target attributes
9778 // of its template. (We require the attributes explicitly in the
9779 // code to match, but a template may have implicit attributes by
9780 // virtue e.g. of being constexpr, and it passes these implicit
9781 // attributes on to its specializations.)
9782 if (LangOpts.CUDA)
9783 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9784
9785 // The "previous declaration" for this function template specialization is
9786 // the prior function template specialization.
9787 Previous.clear();
9788 Previous.addDecl(Specialization);
9789 return false;
9790}
9791
9792bool
9794 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9795 "Only for non-template members");
9796
9797 // Try to find the member we are instantiating.
9798 NamedDecl *FoundInstantiation = nullptr;
9799 NamedDecl *Instantiation = nullptr;
9800 NamedDecl *InstantiatedFrom = nullptr;
9801 MemberSpecializationInfo *MSInfo = nullptr;
9802
9803 if (Previous.empty()) {
9804 // Nowhere to look anyway.
9805 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9806 UnresolvedSet<8> Candidates;
9807 for (NamedDecl *Candidate : Previous) {
9808 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9809 // Ignore any candidates that aren't member functions.
9810 if (!Method)
9811 continue;
9812
9813 QualType Adjusted = Function->getType();
9814 if (!hasExplicitCallingConv(Adjusted))
9815 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9816 // Ignore any candidates with the wrong type.
9817 // This doesn't handle deduced return types, but both function
9818 // declarations should be undeduced at this point.
9819 // FIXME: The exception specification should probably be ignored when
9820 // comparing the types.
9821 if (!Context.hasSameType(Adjusted, Method->getType()))
9822 continue;
9823
9824 // Ignore any candidates with unsatisfied constraints.
9825 if (ConstraintSatisfaction Satisfaction;
9826 Method->getTrailingRequiresClause() &&
9827 (CheckFunctionConstraints(Method, Satisfaction,
9828 /*UsageLoc=*/Member->getLocation(),
9829 /*ForOverloadResolution=*/true) ||
9830 !Satisfaction.IsSatisfied))
9831 continue;
9832
9833 Candidates.addDecl(Candidate);
9834 }
9835
9836 // If we have no viable candidates left after filtering, we are done.
9837 if (Candidates.empty())
9838 return false;
9839
9840 // Find the function that is more constrained than every other function it
9841 // has been compared to.
9842 UnresolvedSetIterator Best = Candidates.begin();
9843 CXXMethodDecl *BestMethod = nullptr;
9844 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9845 I != E; ++I) {
9846 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9847 if (I == Best ||
9848 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9849 Best = I;
9850 BestMethod = Method;
9851 }
9852 }
9853
9854 FoundInstantiation = *Best;
9855 Instantiation = BestMethod;
9856 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9857 MSInfo = BestMethod->getMemberSpecializationInfo();
9858
9859 // Make sure the best candidate is more constrained than all of the others.
9860 bool Ambiguous = false;
9861 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9862 I != E; ++I) {
9863 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9864 if (I != Best &&
9865 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9866 Ambiguous = true;
9867 break;
9868 }
9869 }
9870
9871 if (Ambiguous) {
9872 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9873 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9874 for (NamedDecl *Candidate : Candidates) {
9875 Candidate = Candidate->getUnderlyingDecl();
9876 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9877 << Candidate;
9878 }
9879 return true;
9880 }
9881 } else if (isa<VarDecl>(Member)) {
9882 VarDecl *PrevVar;
9883 if (Previous.isSingleResult() &&
9884 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9885 if (PrevVar->isStaticDataMember()) {
9886 FoundInstantiation = Previous.getRepresentativeDecl();
9887 Instantiation = PrevVar;
9888 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9889 MSInfo = PrevVar->getMemberSpecializationInfo();
9890 }
9891 } else if (isa<RecordDecl>(Member)) {
9892 CXXRecordDecl *PrevRecord;
9893 if (Previous.isSingleResult() &&
9894 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9895 FoundInstantiation = Previous.getRepresentativeDecl();
9896 Instantiation = PrevRecord;
9897 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9898 MSInfo = PrevRecord->getMemberSpecializationInfo();
9899 }
9900 } else if (isa<EnumDecl>(Member)) {
9901 EnumDecl *PrevEnum;
9902 if (Previous.isSingleResult() &&
9903 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9904 FoundInstantiation = Previous.getRepresentativeDecl();
9905 Instantiation = PrevEnum;
9906 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9907 MSInfo = PrevEnum->getMemberSpecializationInfo();
9908 }
9909 }
9910
9911 if (!Instantiation) {
9912 // There is no previous declaration that matches. Since member
9913 // specializations are always out-of-line, the caller will complain about
9914 // this mismatch later.
9915 return false;
9916 }
9917
9918 // A member specialization in a friend declaration isn't really declaring
9919 // an explicit specialization, just identifying a specific (possibly implicit)
9920 // specialization. Don't change the template specialization kind.
9921 //
9922 // FIXME: Is this really valid? Other compilers reject.
9923 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9924 // Preserve instantiation information.
9925 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9926 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9927 cast<CXXMethodDecl>(InstantiatedFrom),
9929 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9930 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9931 cast<CXXRecordDecl>(InstantiatedFrom),
9933 }
9934
9935 Previous.clear();
9936 Previous.addDecl(FoundInstantiation);
9937 return false;
9938 }
9939
9940 // Make sure that this is a specialization of a member.
9941 if (!InstantiatedFrom) {
9942 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9943 << Member;
9944 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9945 return true;
9946 }
9947
9948 // C++ [temp.expl.spec]p6:
9949 // If a template, a member template or the member of a class template is
9950 // explicitly specialized then that specialization shall be declared
9951 // before the first use of that specialization that would cause an implicit
9952 // instantiation to take place, in every translation unit in which such a
9953 // use occurs; no diagnostic is required.
9954 assert(MSInfo && "Member specialization info missing?");
9955
9956 bool HasNoEffect = false;
9959 Instantiation,
9961 MSInfo->getPointOfInstantiation(),
9962 HasNoEffect))
9963 return true;
9964
9965 // Check the scope of this explicit specialization.
9967 InstantiatedFrom,
9968 Instantiation, Member->getLocation(),
9969 false))
9970 return true;
9971
9972 // Note that this member specialization is an "instantiation of" the
9973 // corresponding member of the original template.
9974 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9975 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9976 if (InstantiationFunction->getTemplateSpecializationKind() ==
9978 // Explicit specializations of member functions of class templates do not
9979 // inherit '=delete' from the member function they are specializing.
9980 if (InstantiationFunction->isDeleted()) {
9981 // FIXME: This assert will not hold in the presence of modules.
9982 assert(InstantiationFunction->getCanonicalDecl() ==
9983 InstantiationFunction);
9984 // FIXME: We need an update record for this AST mutation.
9985 InstantiationFunction->setDeletedAsWritten(false);
9986 }
9987 }
9988
9989 MemberFunction->setInstantiationOfMemberFunction(
9991 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9992 MemberVar->setInstantiationOfStaticDataMember(
9993 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9994 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9995 MemberClass->setInstantiationOfMemberClass(
9997 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9998 MemberEnum->setInstantiationOfMemberEnum(
9999 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10000 } else {
10001 llvm_unreachable("unknown member specialization kind");
10002 }
10003
10004 // Save the caller the trouble of having to figure out which declaration
10005 // this specialization matches.
10006 Previous.clear();
10007 Previous.addDecl(FoundInstantiation);
10008 return false;
10009}
10010
10011/// Complete the explicit specialization of a member of a class template by
10012/// updating the instantiated member to be marked as an explicit specialization.
10013///
10014/// \param OrigD The member declaration instantiated from the template.
10015/// \param Loc The location of the explicit specialization of the member.
10016template<typename DeclT>
10017static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10018 SourceLocation Loc) {
10019 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10020 return;
10021
10022 // FIXME: Inform AST mutation listeners of this AST mutation.
10023 // FIXME: If there are multiple in-class declarations of the member (from
10024 // multiple modules, or a declaration and later definition of a member type),
10025 // should we update all of them?
10026 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10027 OrigD->setLocation(Loc);
10028}
10029
10032 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10033 if (Instantiation == Member)
10034 return;
10035
10036 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10037 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10038 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10039 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10040 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10041 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10042 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10043 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10044 else
10045 llvm_unreachable("unknown member specialization kind");
10046}
10047
10048/// Check the scope of an explicit instantiation.
10049///
10050/// \returns true if a serious error occurs, false otherwise.
10052 SourceLocation InstLoc,
10053 bool WasQualifiedName) {
10055 DeclContext *CurContext = S.CurContext->getRedeclContext();
10056
10057 if (CurContext->isRecord()) {
10058 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10059 << D;
10060 return true;
10061 }
10062
10063 // C++11 [temp.explicit]p3:
10064 // An explicit instantiation shall appear in an enclosing namespace of its
10065 // template. If the name declared in the explicit instantiation is an
10066 // unqualified name, the explicit instantiation shall appear in the
10067 // namespace where its template is declared or, if that namespace is inline
10068 // (7.3.1), any namespace from its enclosing namespace set.
10069 //
10070 // This is DR275, which we do not retroactively apply to C++98/03.
10071 if (WasQualifiedName) {
10072 if (CurContext->Encloses(OrigContext))
10073 return false;
10074 } else {
10075 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10076 return false;
10077 }
10078
10079 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10080 if (WasQualifiedName)
10081 S.Diag(InstLoc,
10082 S.getLangOpts().CPlusPlus11?
10083 diag::err_explicit_instantiation_out_of_scope :
10084 diag::warn_explicit_instantiation_out_of_scope_0x)
10085 << D << NS;
10086 else
10087 S.Diag(InstLoc,
10088 S.getLangOpts().CPlusPlus11?
10089 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10090 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10091 << D << NS;
10092 } else
10093 S.Diag(InstLoc,
10094 S.getLangOpts().CPlusPlus11?
10095 diag::err_explicit_instantiation_must_be_global :
10096 diag::warn_explicit_instantiation_must_be_global_0x)
10097 << D;
10098 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10099 return false;
10100}
10101
10102/// Common checks for whether an explicit instantiation of \p D is valid.
10104 SourceLocation InstLoc,
10105 bool WasQualifiedName,
10107 // C++ [temp.explicit]p13:
10108 // An explicit instantiation declaration shall not name a specialization of
10109 // a template with internal linkage.
10112 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10113 return true;
10114 }
10115
10116 // C++11 [temp.explicit]p3: [DR 275]
10117 // An explicit instantiation shall appear in an enclosing namespace of its
10118 // template.
10119 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10120 return true;
10121
10122 return false;
10123}
10124
10125/// Determine whether the given scope specifier has a template-id in it.
10127 // C++11 [temp.explicit]p3:
10128 // If the explicit instantiation is for a member function, a member class
10129 // or a static data member of a class template specialization, the name of
10130 // the class template specialization in the qualified-id for the member
10131 // name shall be a simple-template-id.
10132 //
10133 // C++98 has the same restriction, just worded differently.
10134 for (NestedNameSpecifier NNS = SS.getScopeRep();
10136 /**/) {
10137 const Type *T = NNS.getAsType();
10139 return true;
10140 NNS = T->getPrefix();
10141 }
10142 return false;
10143}
10144
10145/// Make a dllexport or dllimport attr on a class template specialization take
10146/// effect.
10149 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10150 assert(A && "dllExportImportClassTemplateSpecialization called "
10151 "on Def without dllexport or dllimport");
10152
10153 // We reject explicit instantiations in class scope, so there should
10154 // never be any delayed exported classes to worry about.
10155 assert(S.DelayedDllExportClasses.empty() &&
10156 "delayed exports present at explicit instantiation");
10158
10159 // Propagate attribute to base class templates.
10160 for (auto &B : Def->bases()) {
10161 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10162 B.getType()->getAsCXXRecordDecl()))
10164 }
10165
10167}
10168
10170 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10171 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10172 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10173 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10174 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10175 // Find the class template we're specializing
10176 TemplateName Name = TemplateD.get();
10177 TemplateDecl *TD = Name.getAsTemplateDecl();
10178 // Check that the specialization uses the same tag kind as the
10179 // original template.
10181 assert(Kind != TagTypeKind::Enum &&
10182 "Invalid enum tag in class template explicit instantiation!");
10183
10184 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10185
10186 if (!ClassTemplate) {
10187 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10188 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10189 Diag(TD->getLocation(), diag::note_previous_use);
10190 return true;
10191 }
10192
10193 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10194 Kind, /*isDefinition*/false, KWLoc,
10195 ClassTemplate->getIdentifier())) {
10196 Diag(KWLoc, diag::err_use_with_wrong_tag)
10197 << ClassTemplate
10199 ClassTemplate->getTemplatedDecl()->getKindName());
10200 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10201 diag::note_previous_use);
10202 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10203 }
10204
10205 // C++0x [temp.explicit]p2:
10206 // There are two forms of explicit instantiation: an explicit instantiation
10207 // definition and an explicit instantiation declaration. An explicit
10208 // instantiation declaration begins with the extern keyword. [...]
10209 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10212
10214 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10215 // Check for dllexport class template instantiation declarations,
10216 // except for MinGW mode.
10217 for (const ParsedAttr &AL : Attr) {
10218 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10219 Diag(ExternLoc,
10220 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10221 Diag(AL.getLoc(), diag::note_attribute);
10222 break;
10223 }
10224 }
10225
10226 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10227 Diag(ExternLoc,
10228 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10229 Diag(A->getLocation(), diag::note_attribute);
10230 }
10231 }
10232
10233 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10234 // instantiation declarations for most purposes.
10235 bool DLLImportExplicitInstantiationDef = false;
10237 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10238 // Check for dllimport class template instantiation definitions.
10239 bool DLLImport =
10240 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10241 for (const ParsedAttr &AL : Attr) {
10242 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10243 DLLImport = true;
10244 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10245 // dllexport trumps dllimport here.
10246 DLLImport = false;
10247 break;
10248 }
10249 }
10250 if (DLLImport) {
10252 DLLImportExplicitInstantiationDef = true;
10253 }
10254 }
10255
10256 // Translate the parser's template argument list in our AST format.
10257 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10258 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10259
10260 // Check that the template argument list is well-formed for this
10261 // template.
10263 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10264 /*DefaultArgs=*/{}, false, CTAI,
10265 /*UpdateArgsWithConversions=*/true,
10266 /*ConstraintsNotSatisfied=*/nullptr))
10267 return true;
10268
10269 // Find the class template specialization declaration that
10270 // corresponds to these arguments.
10271 void *InsertPos = nullptr;
10273 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10274
10275 TemplateSpecializationKind PrevDecl_TSK
10276 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10277
10278 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10279 Context.getTargetInfo().getTriple().isOSCygMing()) {
10280 // Check for dllexport class template instantiation definitions in MinGW
10281 // mode, if a previous declaration of the instantiation was seen.
10282 for (const ParsedAttr &AL : Attr) {
10283 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10284 Diag(AL.getLoc(),
10285 diag::warn_attribute_dllexport_explicit_instantiation_def);
10286 break;
10287 }
10288 }
10289 }
10290
10291 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10292 SS.isSet(), TSK))
10293 return true;
10294
10296
10297 bool HasNoEffect = false;
10298 if (PrevDecl) {
10299 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10300 PrevDecl, PrevDecl_TSK,
10301 PrevDecl->getPointOfInstantiation(),
10302 HasNoEffect))
10303 return PrevDecl;
10304
10305 // Even though HasNoEffect == true means that this explicit instantiation
10306 // has no effect on semantics, we go on to put its syntax in the AST.
10307
10308 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10309 PrevDecl_TSK == TSK_Undeclared) {
10310 // Since the only prior class template specialization with these
10311 // arguments was referenced but not declared, reuse that
10312 // declaration node as our own, updating the source location
10313 // for the template name to reflect our new declaration.
10314 // (Other source locations will be updated later.)
10315 Specialization = PrevDecl;
10316 Specialization->setLocation(TemplateNameLoc);
10317 PrevDecl = nullptr;
10318 }
10319
10320 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10321 DLLImportExplicitInstantiationDef) {
10322 // The new specialization might add a dllimport attribute.
10323 HasNoEffect = false;
10324 }
10325 }
10326
10327 if (!Specialization) {
10328 // Create a new class template specialization declaration node for
10329 // this explicit specialization.
10331 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10332 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10334
10335 // A MSInheritanceAttr attached to the previous declaration must be
10336 // propagated to the new node prior to instantiation.
10337 if (PrevDecl) {
10338 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10339 auto *Clone = A->clone(getASTContext());
10340 Clone->setInherited(true);
10341 Specialization->addAttr(Clone);
10342 Consumer.AssignInheritanceModel(Specialization);
10343 }
10344 }
10345
10346 if (!HasNoEffect && !PrevDecl) {
10347 // Insert the new specialization.
10348 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10349 }
10350 }
10351
10352 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10353
10354 // Set source locations for keywords.
10355 Specialization->setExternKeywordLoc(ExternLoc);
10356 Specialization->setTemplateKeywordLoc(TemplateLoc);
10357 Specialization->setBraceRange(SourceRange());
10358
10359 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10362
10363 // Add the explicit instantiation into its lexical context. However,
10364 // since explicit instantiations are never found by name lookup, we
10365 // just put it into the declaration context directly.
10366 Specialization->setLexicalDeclContext(CurContext);
10367 CurContext->addDecl(Specialization);
10368
10369 // Syntax is now OK, so return if it has no other effect on semantics.
10370 if (HasNoEffect) {
10371 // Set the template specialization kind.
10372 Specialization->setTemplateSpecializationKind(TSK);
10373 return Specialization;
10374 }
10375
10376 // C++ [temp.explicit]p3:
10377 // A definition of a class template or class member template
10378 // shall be in scope at the point of the explicit instantiation of
10379 // the class template or class member template.
10380 //
10381 // This check comes when we actually try to perform the
10382 // instantiation.
10384 = cast_or_null<ClassTemplateSpecializationDecl>(
10385 Specialization->getDefinition());
10386 if (!Def)
10388 /*Complain=*/true,
10389 CTAI.StrictPackMatch);
10390 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10391 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10392 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10393 }
10394
10395 // Instantiate the members of this class template specialization.
10396 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10397 Specialization->getDefinition());
10398 if (Def) {
10400 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10401 // TSK_ExplicitInstantiationDefinition
10402 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10404 DLLImportExplicitInstantiationDef)) {
10405 // FIXME: Need to notify the ASTMutationListener that we did this.
10407
10408 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10409 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10410 // An explicit instantiation definition can add a dll attribute to a
10411 // template with a previous instantiation declaration. MinGW doesn't
10412 // allow this.
10413 auto *A = cast<InheritableAttr>(
10415 A->setInherited(true);
10416 Def->addAttr(A);
10418 }
10419 }
10420
10421 // Fix a TSK_ImplicitInstantiation followed by a
10422 // TSK_ExplicitInstantiationDefinition
10423 bool NewlyDLLExported =
10424 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10425 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10426 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10427 // An explicit instantiation definition can add a dll attribute to a
10428 // template with a previous implicit instantiation. MinGW doesn't allow
10429 // this. We limit clang to only adding dllexport, to avoid potentially
10430 // strange codegen behavior. For example, if we extend this conditional
10431 // to dllimport, and we have a source file calling a method on an
10432 // implicitly instantiated template class instance and then declaring a
10433 // dllimport explicit instantiation definition for the same template
10434 // class, the codegen for the method call will not respect the dllimport,
10435 // while it will with cl. The Def will already have the DLL attribute,
10436 // since the Def and Specialization will be the same in the case of
10437 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10438 // attribute to the Specialization; we just need to make it take effect.
10439 assert(Def == Specialization &&
10440 "Def and Specialization should match for implicit instantiation");
10442 }
10443
10444 // In MinGW mode, export the template instantiation if the declaration
10445 // was marked dllexport.
10446 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10447 Context.getTargetInfo().getTriple().isOSCygMing() &&
10448 PrevDecl->hasAttr<DLLExportAttr>()) {
10450 }
10451
10452 // Set the template specialization kind. Make sure it is set before
10453 // instantiating the members which will trigger ASTConsumer callbacks.
10454 Specialization->setTemplateSpecializationKind(TSK);
10455 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10456 } else {
10457
10458 // Set the template specialization kind.
10459 Specialization->setTemplateSpecializationKind(TSK);
10460 }
10461
10462 return Specialization;
10463}
10464
10467 SourceLocation TemplateLoc, unsigned TagSpec,
10468 SourceLocation KWLoc, CXXScopeSpec &SS,
10469 IdentifierInfo *Name, SourceLocation NameLoc,
10470 const ParsedAttributesView &Attr) {
10471
10472 bool Owned = false;
10473 bool IsDependent = false;
10474 Decl *TagD =
10475 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10476 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10477 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10478 false, TypeResult(), /*IsTypeSpecifier*/ false,
10479 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10480 .get();
10481 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10482
10483 if (!TagD)
10484 return true;
10485
10486 TagDecl *Tag = cast<TagDecl>(TagD);
10487 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10488
10489 if (Tag->isInvalidDecl())
10490 return true;
10491
10493 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10494 if (!Pattern) {
10495 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10496 << Context.getCanonicalTagType(Record);
10497 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10498 return true;
10499 }
10500
10501 // C++0x [temp.explicit]p2:
10502 // If the explicit instantiation is for a class or member class, the
10503 // elaborated-type-specifier in the declaration shall include a
10504 // simple-template-id.
10505 //
10506 // C++98 has the same restriction, just worded differently.
10508 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10509 << Record << SS.getRange();
10510
10511 // C++0x [temp.explicit]p2:
10512 // There are two forms of explicit instantiation: an explicit instantiation
10513 // definition and an explicit instantiation declaration. An explicit
10514 // instantiation declaration begins with the extern keyword. [...]
10518
10519 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10520
10521 // Verify that it is okay to explicitly instantiate here.
10522 CXXRecordDecl *PrevDecl
10523 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10524 if (!PrevDecl && Record->getDefinition())
10525 PrevDecl = Record;
10526 if (PrevDecl) {
10528 bool HasNoEffect = false;
10529 assert(MSInfo && "No member specialization information?");
10530 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10531 PrevDecl,
10533 MSInfo->getPointOfInstantiation(),
10534 HasNoEffect))
10535 return true;
10536 if (HasNoEffect)
10537 return TagD;
10538 }
10539
10540 CXXRecordDecl *RecordDef
10541 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10542 if (!RecordDef) {
10543 // C++ [temp.explicit]p3:
10544 // A definition of a member class of a class template shall be in scope
10545 // at the point of an explicit instantiation of the member class.
10546 CXXRecordDecl *Def
10547 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10548 if (!Def) {
10549 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10550 << 0 << Record->getDeclName() << Record->getDeclContext();
10551 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10552 << Pattern;
10553 return true;
10554 } else {
10555 if (InstantiateClass(NameLoc, Record, Def,
10557 TSK))
10558 return true;
10559
10560 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10561 if (!RecordDef)
10562 return true;
10563 }
10564 }
10565
10566 // Instantiate all of the members of the class.
10567 InstantiateClassMembers(NameLoc, RecordDef,
10569
10571 MarkVTableUsed(NameLoc, RecordDef, true);
10572
10573 // FIXME: We don't have any representation for explicit instantiations of
10574 // member classes. Such a representation is not needed for compilation, but it
10575 // should be available for clients that want to see all of the declarations in
10576 // the source code.
10577 return TagD;
10578}
10579
10581 SourceLocation ExternLoc,
10582 SourceLocation TemplateLoc,
10583 Declarator &D) {
10584 // Explicit instantiations always require a name.
10585 // TODO: check if/when DNInfo should replace Name.
10587 DeclarationName Name = NameInfo.getName();
10588 if (!Name) {
10589 if (!D.isInvalidType())
10591 diag::err_explicit_instantiation_requires_name)
10593
10594 return true;
10595 }
10596
10597 // Get the innermost enclosing declaration scope.
10598 S = S->getDeclParent();
10599
10600 // Determine the type of the declaration.
10602 QualType R = T->getType();
10603 if (R.isNull())
10604 return true;
10605
10606 // C++ [dcl.stc]p1:
10607 // A storage-class-specifier shall not be specified in [...] an explicit
10608 // instantiation (14.7.2) directive.
10610 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10611 << Name;
10612 return true;
10613 } else if (D.getDeclSpec().getStorageClassSpec()
10615 // Complain about then remove the storage class specifier.
10616 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10618
10620 }
10621
10622 // C++0x [temp.explicit]p1:
10623 // [...] An explicit instantiation of a function template shall not use the
10624 // inline or constexpr specifiers.
10625 // Presumably, this also applies to member functions of class templates as
10626 // well.
10630 diag::err_explicit_instantiation_inline :
10631 diag::warn_explicit_instantiation_inline_0x)
10634 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10635 // not already specified.
10637 diag::err_explicit_instantiation_constexpr);
10638
10639 // A deduction guide is not on the list of entities that can be explicitly
10640 // instantiated.
10642 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10643 << /*explicit instantiation*/ 0;
10644 return true;
10645 }
10646
10647 // C++0x [temp.explicit]p2:
10648 // There are two forms of explicit instantiation: an explicit instantiation
10649 // definition and an explicit instantiation declaration. An explicit
10650 // instantiation declaration begins with the extern keyword. [...]
10654
10655 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10657 /*ObjectType=*/QualType());
10658
10659 if (!R->isFunctionType()) {
10660 // C++ [temp.explicit]p1:
10661 // A [...] static data member of a class template can be explicitly
10662 // instantiated from the member definition associated with its class
10663 // template.
10664 // C++1y [temp.explicit]p1:
10665 // A [...] variable [...] template specialization can be explicitly
10666 // instantiated from its template.
10667 if (Previous.isAmbiguous())
10668 return true;
10669
10670 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10671 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10672
10673 if (!PrevTemplate) {
10674 if (!Prev || !Prev->isStaticDataMember()) {
10675 // We expect to see a static data member here.
10676 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10677 << Name;
10678 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10679 P != PEnd; ++P)
10680 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10681 return true;
10682 }
10683
10685 // FIXME: Check for explicit specialization?
10687 diag::err_explicit_instantiation_data_member_not_instantiated)
10688 << Prev;
10689 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10690 // FIXME: Can we provide a note showing where this was declared?
10691 return true;
10692 }
10693 } else {
10694 // Explicitly instantiate a variable template.
10695
10696 // C++1y [dcl.spec.auto]p6:
10697 // ... A program that uses auto or decltype(auto) in a context not
10698 // explicitly allowed in this section is ill-formed.
10699 //
10700 // This includes auto-typed variable template instantiations.
10701 if (R->isUndeducedType()) {
10702 Diag(T->getTypeLoc().getBeginLoc(),
10703 diag::err_auto_not_allowed_var_inst);
10704 return true;
10705 }
10706
10708 // C++1y [temp.explicit]p3:
10709 // If the explicit instantiation is for a variable, the unqualified-id
10710 // in the declaration shall be a template-id.
10712 diag::err_explicit_instantiation_without_template_id)
10713 << PrevTemplate;
10714 Diag(PrevTemplate->getLocation(),
10715 diag::note_explicit_instantiation_here);
10716 return true;
10717 }
10718
10719 // Translate the parser's template argument list into our AST format.
10720 TemplateArgumentListInfo TemplateArgs =
10722
10723 DeclResult Res =
10724 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10725 TemplateArgs, /*SetWrittenArgs=*/true);
10726 if (Res.isInvalid())
10727 return true;
10728
10729 if (!Res.isUsable()) {
10730 // We somehow specified dependent template arguments in an explicit
10731 // instantiation. This should probably only happen during error
10732 // recovery.
10733 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10734 return true;
10735 }
10736
10737 // Ignore access control bits, we don't need them for redeclaration
10738 // checking.
10739 Prev = cast<VarDecl>(Res.get());
10740 }
10741
10742 // C++0x [temp.explicit]p2:
10743 // If the explicit instantiation is for a member function, a member class
10744 // or a static data member of a class template specialization, the name of
10745 // the class template specialization in the qualified-id for the member
10746 // name shall be a simple-template-id.
10747 //
10748 // C++98 has the same restriction, just worded differently.
10749 //
10750 // This does not apply to variable template specializations, where the
10751 // template-id is in the unqualified-id instead.
10752 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10754 diag::ext_explicit_instantiation_without_qualified_id)
10755 << Prev << D.getCXXScopeSpec().getRange();
10756
10757 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10758
10759 // Verify that it is okay to explicitly instantiate here.
10762 bool HasNoEffect = false;
10764 PrevTSK, POI, HasNoEffect))
10765 return true;
10766
10767 if (!HasNoEffect) {
10768 // Instantiate static data member or variable template.
10770 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10771 VTSD->setExternKeywordLoc(ExternLoc);
10772 VTSD->setTemplateKeywordLoc(TemplateLoc);
10773 }
10774
10775 // Merge attributes.
10777 if (PrevTemplate)
10778 ProcessAPINotes(Prev);
10779
10782 }
10783
10784 // Check the new variable specialization against the parsed input.
10785 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10786 Diag(T->getTypeLoc().getBeginLoc(),
10787 diag::err_invalid_var_template_spec_type)
10788 << 0 << PrevTemplate << R << Prev->getType();
10789 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10790 << 2 << PrevTemplate->getDeclName();
10791 return true;
10792 }
10793
10794 // FIXME: Create an ExplicitInstantiation node?
10795 return (Decl*) nullptr;
10796 }
10797
10798 // If the declarator is a template-id, translate the parser's template
10799 // argument list into our AST format.
10800 bool HasExplicitTemplateArgs = false;
10801 TemplateArgumentListInfo TemplateArgs;
10803 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10804 HasExplicitTemplateArgs = true;
10805 }
10806
10807 // C++ [temp.explicit]p1:
10808 // A [...] function [...] can be explicitly instantiated from its template.
10809 // A member function [...] of a class template can be explicitly
10810 // instantiated from the member definition associated with its class
10811 // template.
10812 UnresolvedSet<8> TemplateMatches;
10813 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10815 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10816 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10817 P != PEnd; ++P) {
10818 NamedDecl *Prev = *P;
10819 if (!HasExplicitTemplateArgs) {
10820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10821 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10822 /*AdjustExceptionSpec*/true);
10823 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10824 if (Method->getPrimaryTemplate()) {
10825 TemplateMatches.addDecl(Method, P.getAccess());
10826 } else {
10827 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10828 C.FoundDecl = P.getPair();
10829 C.Function = Method;
10830 C.Viable = true;
10832 if (Method->getTrailingRequiresClause() &&
10834 /*ForOverloadResolution=*/true) ||
10835 !S.IsSatisfied)) {
10836 C.Viable = false;
10838 }
10839 }
10840 }
10841 }
10842 }
10843
10844 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10845 if (!FunTmpl)
10846 continue;
10847
10848 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10849 FunctionDecl *Specialization = nullptr;
10851 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10852 Specialization, Info);
10854 // Keep track of almost-matches.
10855 FailedTemplateCandidates.addCandidate().set(
10856 P.getPair(), FunTmpl->getTemplatedDecl(),
10857 MakeDeductionFailureInfo(Context, TDK, Info));
10858 (void)TDK;
10859 continue;
10860 }
10861
10862 // Target attributes are part of the cuda function signature, so
10863 // the cuda target of the instantiated function must match that of its
10864 // template. Given that C++ template deduction does not take
10865 // target attributes into account, we reject candidates here that
10866 // have a different target.
10867 if (LangOpts.CUDA &&
10868 CUDA().IdentifyTarget(Specialization,
10869 /* IgnoreImplicitHDAttr = */ true) !=
10870 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10871 FailedTemplateCandidates.addCandidate().set(
10872 P.getPair(), FunTmpl->getTemplatedDecl(),
10875 continue;
10876 }
10877
10878 TemplateMatches.addDecl(Specialization, P.getAccess());
10879 }
10880
10881 FunctionDecl *Specialization = nullptr;
10882 if (!NonTemplateMatches.empty()) {
10883 unsigned Msg = 0;
10884 OverloadCandidateDisplayKind DisplayKind;
10886 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10887 Best)) {
10888 case OR_Success:
10889 case OR_Deleted:
10890 Specialization = cast<FunctionDecl>(Best->Function);
10891 break;
10892 case OR_Ambiguous:
10893 Msg = diag::err_explicit_instantiation_ambiguous;
10894 DisplayKind = OCD_AmbiguousCandidates;
10895 break;
10897 Msg = diag::err_explicit_instantiation_no_candidate;
10898 DisplayKind = OCD_AllCandidates;
10899 break;
10900 }
10901 if (Msg) {
10902 PartialDiagnostic Diag = PDiag(Msg) << Name;
10903 NonTemplateMatches.NoteCandidates(
10904 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10905 {});
10906 return true;
10907 }
10908 }
10909
10910 if (!Specialization) {
10911 // Find the most specialized function template specialization.
10913 TemplateMatches.begin(), TemplateMatches.end(),
10914 FailedTemplateCandidates, D.getIdentifierLoc(),
10915 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10916 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10917 PDiag(diag::note_explicit_instantiation_candidate));
10918
10919 if (Result == TemplateMatches.end())
10920 return true;
10921
10922 // Ignore access control bits, we don't need them for redeclaration checking.
10924 }
10925
10926 // C++11 [except.spec]p4
10927 // In an explicit instantiation an exception-specification may be specified,
10928 // but is not required.
10929 // If an exception-specification is specified in an explicit instantiation
10930 // directive, it shall be compatible with the exception-specifications of
10931 // other declarations of that function.
10932 if (auto *FPT = R->getAs<FunctionProtoType>())
10933 if (FPT->hasExceptionSpec()) {
10934 unsigned DiagID =
10935 diag::err_mismatched_exception_spec_explicit_instantiation;
10936 if (getLangOpts().MicrosoftExt)
10937 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10939 PDiag(DiagID) << Specialization->getType(),
10940 PDiag(diag::note_explicit_instantiation_here),
10941 Specialization->getType()->getAs<FunctionProtoType>(),
10942 Specialization->getLocation(), FPT, D.getBeginLoc());
10943 // In Microsoft mode, mismatching exception specifications just cause a
10944 // warning.
10945 if (!getLangOpts().MicrosoftExt && Result)
10946 return true;
10947 }
10948
10949 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10951 diag::err_explicit_instantiation_member_function_not_instantiated)
10953 << (Specialization->getTemplateSpecializationKind() ==
10955 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10956 return true;
10957 }
10958
10959 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10960 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10961 PrevDecl = Specialization;
10962
10963 if (PrevDecl) {
10964 bool HasNoEffect = false;
10966 PrevDecl,
10968 PrevDecl->getPointOfInstantiation(),
10969 HasNoEffect))
10970 return true;
10971
10972 // FIXME: We may still want to build some representation of this
10973 // explicit specialization.
10974 if (HasNoEffect)
10975 return (Decl*) nullptr;
10976 }
10977
10978 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10979 // functions
10980 // valarray<size_t>::valarray(size_t) and
10981 // valarray<size_t>::~valarray()
10982 // that it declared to have internal linkage with the internal_linkage
10983 // attribute. Ignore the explicit instantiation declaration in this case.
10984 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10986 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10987 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10988 RD->isInStdNamespace())
10989 return (Decl*) nullptr;
10990 }
10991
10994
10995 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10996 // instantiation declarations.
10998 Specialization->hasAttr<DLLImportAttr>() &&
10999 Context.getTargetInfo().getCXXABI().isMicrosoft())
11001
11002 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11003
11004 if (Specialization->isDefined()) {
11005 // Let the ASTConsumer know that this function has been explicitly
11006 // instantiated now, and its linkage might have changed.
11007 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11008 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11010
11011 // C++0x [temp.explicit]p2:
11012 // If the explicit instantiation is for a member function, a member class
11013 // or a static data member of a class template specialization, the name of
11014 // the class template specialization in the qualified-id for the member
11015 // name shall be a simple-template-id.
11016 //
11017 // C++98 has the same restriction, just worded differently.
11018 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11019 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11020 D.getCXXScopeSpec().isSet() &&
11023 diag::ext_explicit_instantiation_without_qualified_id)
11025
11027 *this,
11028 FunTmpl ? (NamedDecl *)FunTmpl
11029 : Specialization->getInstantiatedFromMemberFunction(),
11030 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11031
11032 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11033 return (Decl*) nullptr;
11034}
11035
11037 const CXXScopeSpec &SS,
11038 const IdentifierInfo *Name,
11039 SourceLocation TagLoc,
11040 SourceLocation NameLoc) {
11041 // This has to hold, because SS is expected to be defined.
11042 assert(Name && "Expected a name in a dependent tag");
11043
11045 if (!NNS)
11046 return true;
11047
11049
11050 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11051 Diag(NameLoc, diag::err_dependent_tag_decl)
11052 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11053 return true;
11054 }
11055
11056 // Create the resulting type.
11058 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11059
11060 // Create type-source location information for this type.
11061 TypeLocBuilder TLB;
11063 TL.setElaboratedKeywordLoc(TagLoc);
11065 TL.setNameLoc(NameLoc);
11067}
11068
11070 const CXXScopeSpec &SS,
11071 const IdentifierInfo &II,
11072 SourceLocation IdLoc,
11073 ImplicitTypenameContext IsImplicitTypename) {
11074 if (SS.isInvalid())
11075 return true;
11076
11077 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11078 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11079 << FixItHint::CreateRemoval(TypenameLoc);
11080
11082 TypeSourceInfo *TSI = nullptr;
11083 QualType T =
11086 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11087 /*DeducedTSTContext=*/true);
11088 if (T.isNull())
11089 return true;
11090 return CreateParsedType(T, TSI);
11091}
11092
11095 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11096 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11097 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11098 ASTTemplateArgsPtr TemplateArgsIn,
11099 SourceLocation RAngleLoc) {
11100 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11101 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11102 ? diag::compat_cxx11_typename_outside_of_template
11103 : diag::compat_pre_cxx11_typename_outside_of_template)
11104 << FixItHint::CreateRemoval(TypenameLoc);
11105
11106 // Strangely, non-type results are not ignored by this lookup, so the
11107 // program is ill-formed if it finds an injected-class-name.
11108 if (TypenameLoc.isValid()) {
11109 auto *LookupRD =
11110 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11111 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11112 Diag(TemplateIILoc,
11113 diag::ext_out_of_line_qualified_id_type_names_constructor)
11114 << TemplateII << 0 /*injected-class-name used as template name*/
11115 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11116 }
11117 }
11118
11119 // Translate the parser's template argument list in our AST format.
11120 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11121 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11122
11126 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11127 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11128 if (T.isNull())
11129 return true;
11130
11131 // Provide source-location information for the template specialization type.
11132 TypeLocBuilder Builder;
11134 = Builder.push<TemplateSpecializationTypeLoc>(T);
11135 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11136 TemplateIILoc, TemplateArgs);
11137 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11138 return CreateParsedType(T, TSI);
11139}
11140
11141/// Determine whether this failed name lookup should be treated as being
11142/// disabled by a usage of std::enable_if.
11144 SourceRange &CondRange, Expr *&Cond) {
11145 // We must be looking for a ::type...
11146 if (!II.isStr("type"))
11147 return false;
11148
11149 // ... within an explicitly-written template specialization...
11151 return false;
11152
11153 // FIXME: Look through sugar.
11154 auto EnableIfTSTLoc =
11156 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11157 return false;
11158 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11159
11160 // ... which names a complete class template declaration...
11161 const TemplateDecl *EnableIfDecl =
11162 EnableIfTST->getTemplateName().getAsTemplateDecl();
11163 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11164 return false;
11165
11166 // ... called "enable_if".
11167 const IdentifierInfo *EnableIfII =
11168 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11169 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11170 return false;
11171
11172 // Assume the first template argument is the condition.
11173 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11174
11175 // Dig out the condition.
11176 Cond = nullptr;
11177 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11179 return true;
11180
11181 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11182
11183 // Ignore Boolean literals; they add no value.
11184 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11185 Cond = nullptr;
11186
11187 return true;
11188}
11189
11192 SourceLocation KeywordLoc,
11193 NestedNameSpecifierLoc QualifierLoc,
11194 const IdentifierInfo &II,
11195 SourceLocation IILoc,
11196 TypeSourceInfo **TSI,
11197 bool DeducedTSTContext) {
11198 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11199 DeducedTSTContext);
11200 if (T.isNull())
11201 return QualType();
11202
11203 TypeLocBuilder TLB;
11205 auto TL = TLB.push<DependentNameTypeLoc>(T);
11206 TL.setElaboratedKeywordLoc(KeywordLoc);
11207 TL.setQualifierLoc(QualifierLoc);
11208 TL.setNameLoc(IILoc);
11211 TL.setElaboratedKeywordLoc(KeywordLoc);
11212 TL.setQualifierLoc(QualifierLoc);
11213 TL.setNameLoc(IILoc);
11214 } else if (isa<TemplateTypeParmType>(T)) {
11215 // FIXME: There might be a 'typename' keyword here, but we just drop it
11216 // as it can't be represented.
11217 assert(!QualifierLoc);
11218 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11219 } else if (isa<TagType>(T)) {
11220 auto TL = TLB.push<TagTypeLoc>(T);
11221 TL.setElaboratedKeywordLoc(KeywordLoc);
11222 TL.setQualifierLoc(QualifierLoc);
11223 TL.setNameLoc(IILoc);
11224 } else if (isa<TypedefType>(T)) {
11225 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11226 } else {
11227 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11228 }
11229 *TSI = TLB.getTypeSourceInfo(Context, T);
11230 return T;
11231}
11232
11233/// Build the type that describes a C++ typename specifier,
11234/// e.g., "typename T::type".
11237 SourceLocation KeywordLoc,
11238 NestedNameSpecifierLoc QualifierLoc,
11239 const IdentifierInfo &II,
11240 SourceLocation IILoc, bool DeducedTSTContext) {
11241 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11242
11243 CXXScopeSpec SS;
11244 SS.Adopt(QualifierLoc);
11245
11246 DeclContext *Ctx = nullptr;
11247 if (QualifierLoc) {
11248 Ctx = computeDeclContext(SS);
11249 if (!Ctx) {
11250 // If the nested-name-specifier is dependent and couldn't be
11251 // resolved to a type, build a typename type.
11252 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11253 return Context.getDependentNameType(Keyword,
11254 QualifierLoc.getNestedNameSpecifier(),
11255 &II);
11256 }
11257
11258 // If the nested-name-specifier refers to the current instantiation,
11259 // the "typename" keyword itself is superfluous. In C++03, the
11260 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11261 // allows such extraneous "typename" keywords, and we retroactively
11262 // apply this DR to C++03 code with only a warning. In any case we continue.
11263
11264 if (RequireCompleteDeclContext(SS, Ctx))
11265 return QualType();
11266 }
11267
11268 DeclarationName Name(&II);
11269 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11270 if (Ctx)
11271 LookupQualifiedName(Result, Ctx, SS);
11272 else
11273 LookupName(Result, CurScope);
11274 unsigned DiagID = 0;
11275 Decl *Referenced = nullptr;
11276 switch (Result.getResultKind()) {
11278 // If we're looking up 'type' within a template named 'enable_if', produce
11279 // a more specific diagnostic.
11280 SourceRange CondRange;
11281 Expr *Cond = nullptr;
11282 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11283 // If we have a condition, narrow it down to the specific failed
11284 // condition.
11285 if (Cond) {
11286 Expr *FailedCond;
11287 std::string FailedDescription;
11288 std::tie(FailedCond, FailedDescription) =
11290
11291 Diag(FailedCond->getExprLoc(),
11292 diag::err_typename_nested_not_found_requirement)
11293 << FailedDescription
11294 << FailedCond->getSourceRange();
11295 return QualType();
11296 }
11297
11298 Diag(CondRange.getBegin(),
11299 diag::err_typename_nested_not_found_enable_if)
11300 << Ctx << CondRange;
11301 return QualType();
11302 }
11303
11304 DiagID = Ctx ? diag::err_typename_nested_not_found
11305 : diag::err_unknown_typename;
11306 break;
11307 }
11308
11310 // We found a using declaration that is a value. Most likely, the using
11311 // declaration itself is meant to have the 'typename' keyword.
11312 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11313 IILoc);
11314 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11315 << Name << Ctx << FullRange;
11316 if (UnresolvedUsingValueDecl *Using
11317 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11318 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11319 Diag(Loc, diag::note_using_value_decl_missing_typename)
11320 << FixItHint::CreateInsertion(Loc, "typename ");
11321 }
11322 }
11323 // Fall through to create a dependent typename type, from which we can
11324 // recover better.
11325 [[fallthrough]];
11326
11328 // Okay, it's a member of an unknown instantiation.
11329 return Context.getDependentNameType(Keyword,
11330 QualifierLoc.getNestedNameSpecifier(),
11331 &II);
11332
11334 // FXIME: Missing support for UsingShadowDecl on this path?
11335 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11336 // C++ [class.qual]p2:
11337 // In a lookup in which function names are not ignored and the
11338 // nested-name-specifier nominates a class C, if the name specified
11339 // after the nested-name-specifier, when looked up in C, is the
11340 // injected-class-name of C [...] then the name is instead considered
11341 // to name the constructor of class C.
11342 //
11343 // Unlike in an elaborated-type-specifier, function names are not ignored
11344 // in typename-specifier lookup. However, they are ignored in all the
11345 // contexts where we form a typename type with no keyword (that is, in
11346 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11347 //
11348 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11349 // ignore functions, but that appears to be an oversight.
11354 Type, IILoc);
11355 // FIXME: This appears to be the only case where a template type parameter
11356 // can have an elaborated keyword. We should preserve it somehow.
11359 assert(!QualifierLoc);
11361 }
11362 return Context.getTypeDeclType(
11363 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11364 }
11365
11366 // C++ [dcl.type.simple]p2:
11367 // A type-specifier of the form
11368 // typename[opt] nested-name-specifier[opt] template-name
11369 // is a placeholder for a deduced class type [...].
11370 if (getLangOpts().CPlusPlus17) {
11371 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11372 if (!DeducedTSTContext) {
11373 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11374 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11375 Diag(IILoc, diag::err_dependent_deduced_tst)
11377 << QualType(Qualifier.getAsType(), 0);
11378 else
11379 Diag(IILoc, diag::err_deduced_tst)
11382 return QualType();
11383 }
11384 TemplateName Name = Context.getQualifiedTemplateName(
11385 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11386 TemplateName(TD));
11387 return Context.getDeducedTemplateSpecializationType(
11388 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11389 }
11390 }
11391
11392 DiagID = Ctx ? diag::err_typename_nested_not_type
11393 : diag::err_typename_not_type;
11394 Referenced = Result.getFoundDecl();
11395 break;
11396
11398 DiagID = Ctx ? diag::err_typename_nested_not_type
11399 : diag::err_typename_not_type;
11400 Referenced = *Result.begin();
11401 break;
11402
11404 return QualType();
11405 }
11406
11407 // If we get here, it's because name lookup did not find a
11408 // type. Emit an appropriate diagnostic and return an error.
11409 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11410 IILoc);
11411 if (Ctx)
11412 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11413 else
11414 Diag(IILoc, DiagID) << FullRange << Name;
11415 if (Referenced)
11416 Diag(Referenced->getLocation(),
11417 Ctx ? diag::note_typename_member_refers_here
11418 : diag::note_typename_refers_here)
11419 << Name;
11420 return QualType();
11421}
11422
11423namespace {
11424 // See Sema::RebuildTypeInCurrentInstantiation
11425 class CurrentInstantiationRebuilder
11426 : public TreeTransform<CurrentInstantiationRebuilder> {
11427 SourceLocation Loc;
11428 DeclarationName Entity;
11429
11430 public:
11432
11433 CurrentInstantiationRebuilder(Sema &SemaRef,
11434 SourceLocation Loc,
11435 DeclarationName Entity)
11436 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11437 Loc(Loc), Entity(Entity) { }
11438
11439 /// Determine whether the given type \p T has already been
11440 /// transformed.
11441 ///
11442 /// For the purposes of type reconstruction, a type has already been
11443 /// transformed if it is NULL or if it is not dependent.
11444 bool AlreadyTransformed(QualType T) {
11445 return T.isNull() || !T->isInstantiationDependentType();
11446 }
11447
11448 /// Returns the location of the entity whose type is being
11449 /// rebuilt.
11450 SourceLocation getBaseLocation() { return Loc; }
11451
11452 /// Returns the name of the entity whose type is being rebuilt.
11453 DeclarationName getBaseEntity() { return Entity; }
11454
11455 /// Sets the "base" location and entity when that
11456 /// information is known based on another transformation.
11457 void setBase(SourceLocation Loc, DeclarationName Entity) {
11458 this->Loc = Loc;
11459 this->Entity = Entity;
11460 }
11461
11462 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11463 // Lambdas never need to be transformed.
11464 return E;
11465 }
11466 };
11467} // end anonymous namespace
11468
11470 SourceLocation Loc,
11471 DeclarationName Name) {
11472 if (!T || !T->getType()->isInstantiationDependentType())
11473 return T;
11474
11475 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11476 return Rebuilder.TransformType(T);
11477}
11478
11480 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11481 DeclarationName());
11482 return Rebuilder.TransformExpr(E);
11483}
11484
11486 if (SS.isInvalid())
11487 return true;
11488
11490 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11491 DeclarationName());
11493 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11494 if (!Rebuilt)
11495 return true;
11496
11497 SS.Adopt(Rebuilt);
11498 return false;
11499}
11500
11502 TemplateParameterList *Params) {
11503 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11504 Decl *Param = Params->getParam(I);
11505
11506 // There is nothing to rebuild in a type parameter.
11507 if (isa<TemplateTypeParmDecl>(Param))
11508 continue;
11509
11510 // Rebuild the template parameter list of a template template parameter.
11512 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11514 TTP->getTemplateParameters()))
11515 return true;
11516
11517 continue;
11518 }
11519
11520 // Rebuild the type of a non-type template parameter.
11522 TypeSourceInfo *NewTSI
11524 NTTP->getLocation(),
11525 NTTP->getDeclName());
11526 if (!NewTSI)
11527 return true;
11528
11529 if (NewTSI->getType()->isUndeducedType()) {
11530 // C++17 [temp.dep.expr]p3:
11531 // An id-expression is type-dependent if it contains
11532 // - an identifier associated by name lookup with a non-type
11533 // template-parameter declared with a type that contains a
11534 // placeholder type (7.1.7.4),
11535 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11536 }
11537
11538 if (NewTSI != NTTP->getTypeSourceInfo()) {
11539 NTTP->setTypeSourceInfo(NewTSI);
11540 NTTP->setType(NewTSI->getType());
11541 }
11542 }
11543
11544 return false;
11545}
11546
11547std::string
11549 const TemplateArgumentList &Args) {
11550 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11551}
11552
11553std::string
11555 const TemplateArgument *Args,
11556 unsigned NumArgs) {
11557 SmallString<128> Str;
11558 llvm::raw_svector_ostream Out(Str);
11559
11560 if (!Params || Params->size() == 0 || NumArgs == 0)
11561 return std::string();
11562
11563 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11564 if (I >= NumArgs)
11565 break;
11566
11567 if (I == 0)
11568 Out << "[with ";
11569 else
11570 Out << ", ";
11571
11572 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11573 Out << Id->getName();
11574 } else {
11575 Out << '$' << I;
11576 }
11577
11578 Out << " = ";
11579 Args[I].print(getPrintingPolicy(), Out,
11581 getPrintingPolicy(), Params, I));
11582 }
11583
11584 Out << ']';
11585 return std::string(Out.str());
11586}
11587
11589 CachedTokens &Toks) {
11590 if (!FD)
11591 return;
11592
11593 auto LPT = std::make_unique<LateParsedTemplate>();
11594
11595 // Take tokens to avoid allocations
11596 LPT->Toks.swap(Toks);
11597 LPT->D = FnD;
11598 LPT->FPO = getCurFPFeatures();
11599 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11600
11601 FD->setLateTemplateParsed(true);
11602}
11603
11605 if (!FD)
11606 return;
11607 FD->setLateTemplateParsed(false);
11608}
11609
11611 DeclContext *DC = CurContext;
11612
11613 while (DC) {
11614 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11615 const FunctionDecl *FD = RD->isLocalClass();
11616 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11617 } else if (DC->isTranslationUnit() || DC->isNamespace())
11618 return false;
11619
11620 DC = DC->getParent();
11621 }
11622 return false;
11623}
11624
11625namespace {
11626/// Walk the path from which a declaration was instantiated, and check
11627/// that every explicit specialization along that path is visible. This enforces
11628/// C++ [temp.expl.spec]/6:
11629///
11630/// If a template, a member template or a member of a class template is
11631/// explicitly specialized then that specialization shall be declared before
11632/// the first use of that specialization that would cause an implicit
11633/// instantiation to take place, in every translation unit in which such a
11634/// use occurs; no diagnostic is required.
11635///
11636/// and also C++ [temp.class.spec]/1:
11637///
11638/// A partial specialization shall be declared before the first use of a
11639/// class template specialization that would make use of the partial
11640/// specialization as the result of an implicit or explicit instantiation
11641/// in every translation unit in which such a use occurs; no diagnostic is
11642/// required.
11643class ExplicitSpecializationVisibilityChecker {
11644 Sema &S;
11645 SourceLocation Loc;
11648
11649public:
11650 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11652 : S(S), Loc(Loc), Kind(Kind) {}
11653
11654 void check(NamedDecl *ND) {
11655 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11656 return checkImpl(FD);
11657 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11658 return checkImpl(RD);
11659 if (auto *VD = dyn_cast<VarDecl>(ND))
11660 return checkImpl(VD);
11661 if (auto *ED = dyn_cast<EnumDecl>(ND))
11662 return checkImpl(ED);
11663 }
11664
11665private:
11666 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11667 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11668 : Sema::MissingImportKind::ExplicitSpecialization;
11669 const bool Recover = true;
11670
11671 // If we got a custom set of modules (because only a subset of the
11672 // declarations are interesting), use them, otherwise let
11673 // diagnoseMissingImport intelligently pick some.
11674 if (Modules.empty())
11675 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11676 else
11677 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11678 }
11679
11680 bool CheckMemberSpecialization(const NamedDecl *D) {
11681 return Kind == Sema::AcceptableKind::Visible
11684 }
11685
11686 bool CheckExplicitSpecialization(const NamedDecl *D) {
11687 return Kind == Sema::AcceptableKind::Visible
11690 }
11691
11692 bool CheckDeclaration(const NamedDecl *D) {
11693 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11695 }
11696
11697 // Check a specific declaration. There are three problematic cases:
11698 //
11699 // 1) The declaration is an explicit specialization of a template
11700 // specialization.
11701 // 2) The declaration is an explicit specialization of a member of an
11702 // templated class.
11703 // 3) The declaration is an instantiation of a template, and that template
11704 // is an explicit specialization of a member of a templated class.
11705 //
11706 // We don't need to go any deeper than that, as the instantiation of the
11707 // surrounding class / etc is not triggered by whatever triggered this
11708 // instantiation, and thus should be checked elsewhere.
11709 template<typename SpecDecl>
11710 void checkImpl(SpecDecl *Spec) {
11711 bool IsHiddenExplicitSpecialization = false;
11712 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11713 // Some invalid friend declarations are written as specializations but are
11714 // instantiated implicitly.
11715 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11716 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11717 if (SpecKind == TSK_ExplicitSpecialization) {
11718 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11719 ? !CheckMemberSpecialization(Spec)
11720 : !CheckExplicitSpecialization(Spec);
11721 } else {
11722 checkInstantiated(Spec);
11723 }
11724
11725 if (IsHiddenExplicitSpecialization)
11726 diagnose(Spec->getMostRecentDecl(), false);
11727 }
11728
11729 void checkInstantiated(FunctionDecl *FD) {
11730 if (auto *TD = FD->getPrimaryTemplate())
11731 checkTemplate(TD);
11732 }
11733
11734 void checkInstantiated(CXXRecordDecl *RD) {
11735 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11736 if (!SD)
11737 return;
11738
11739 auto From = SD->getSpecializedTemplateOrPartial();
11740 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11741 checkTemplate(TD);
11742 else if (auto *TD =
11743 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11744 if (!CheckDeclaration(TD))
11745 diagnose(TD, true);
11746 checkTemplate(TD);
11747 }
11748 }
11749
11750 void checkInstantiated(VarDecl *RD) {
11751 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11752 if (!SD)
11753 return;
11754
11755 auto From = SD->getSpecializedTemplateOrPartial();
11756 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11757 checkTemplate(TD);
11758 else if (auto *TD =
11759 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11760 if (!CheckDeclaration(TD))
11761 diagnose(TD, true);
11762 checkTemplate(TD);
11763 }
11764 }
11765
11766 void checkInstantiated(EnumDecl *FD) {}
11767
11768 template<typename TemplDecl>
11769 void checkTemplate(TemplDecl *TD) {
11770 if (TD->isMemberSpecialization()) {
11771 if (!CheckMemberSpecialization(TD))
11772 diagnose(TD->getMostRecentDecl(), false);
11773 }
11774 }
11775};
11776} // end anonymous namespace
11777
11779 if (!getLangOpts().Modules)
11780 return;
11781
11782 ExplicitSpecializationVisibilityChecker(*this, Loc,
11784 .check(Spec);
11785}
11786
11788 NamedDecl *Spec) {
11789 if (!getLangOpts().CPlusPlusModules)
11790 return checkSpecializationVisibility(Loc, Spec);
11791
11792 ExplicitSpecializationVisibilityChecker(*this, Loc,
11794 .check(Spec);
11795}
11796
11799 return N->getLocation();
11800 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11802 return FD->getLocation();
11805 return N->getLocation();
11806 }
11807 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11808 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11809 continue;
11810 return CSC.PointOfInstantiation;
11811 }
11812 return N->getLocation();
11813}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
APSInt & getComplexIntImag()
Definition APValue.h:527
ValueKind getKind() const
Definition APValue.h:461
APFixedPoint & getFixedPoint()
Definition APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isMemberPointer() const
Definition APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isNullPointer() const
Definition APValue.cpp:1019
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition Attr.h:44
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2373
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2391
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2441
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2434
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2409
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2415
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2421
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8146
Pointer to a block type.
Definition TypeBase.h:3542
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2099
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:735
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3872
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2020
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2061
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2198
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1371
ValueDecl * getDecl()
Definition Expr.h:1338
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2700
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
bool hasEllipsis() const
Definition DeclSpec.h:2699
bool isInvalidType() const
Definition DeclSpec.h:2688
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4061
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3512
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4011
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4432
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4270
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5080
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:827
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:2000
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4193
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4502
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4301
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4160
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3735
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4132
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition Decl.cpp:4366
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2362
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4405
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4153
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4844
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
QualType getReturnType() const
Definition TypeBase.h:4802
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
Describes an C or C++ initializer list.
Definition Expr.h:5233
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
Represents a linkage specification.
Definition DeclCXX.h:3015
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4398
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
QualType getPointeeType() const
Definition TypeBase.h:3671
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition Template.h:269
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:264
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7856
Represents a pointer to an Objective C object.
Definition TypeBase.h:7912
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1416
bool isVarDeclReference() const
Definition ExprCXX.h:3304
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3320
bool isConceptReference() const
Definition ExprCXX.h:3293
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3339
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4365
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8112
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8383
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8294
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8479
QualType getCanonicalType() const
Definition TypeBase.h:8346
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8388
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3549
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
Represents a struct/union/class.
Definition Decl.h:4312
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4496
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5312
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13552
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
Whether and why a template name is required in this lookup.
Definition Sema.h:11349
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11357
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12392
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12425
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7676
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13486
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12984
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9287
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9291
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9299
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9294
ExprResult ActOnConstantExpression(ExprResult Res)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9601
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void NoteAllFoundTemplates(TemplateName Name)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition Sema.h:1445
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4134
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2049
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11320
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:11918
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11921
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11925
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1283
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:925
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition Sema.h:11310
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12098
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12116
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12106
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12126
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
AssumedTemplateKind
Definition Sema.h:11370
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11377
@ None
This is not assumed to be a template name.
Definition Sema.h:11372
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11374
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition Sema.h:11303
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:920
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14329
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14317
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14326
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14320
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14344
const LangOptions & getLangOpts() const
Definition Sema.h:918
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1282
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1281
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1418
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15325
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ASTConsumer & Consumer
Definition Sema.h:1284
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4630
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6696
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
bool inParameterMappingSubstitution() const
Definition Sema.h:13857
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11347
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:509
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11530
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11540
@ TPC_FriendFunctionTemplate
Definition Sema.h:11538
@ TPC_ClassTemplateMember
Definition Sema.h:11536
@ TPC_FunctionTemplate
Definition Sema.h:11535
@ TPC_FriendClassTemplate
Definition Sema.h:11537
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11539
friend class InitializationSequence
Definition Sema.h:1560
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6246
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6383
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3469
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11312
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:143
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9610
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12827
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8609
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4666
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
StringRef getKindName() const
Definition Decl.h:3907
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4894
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:4968
TagKind getTagKind() const
Definition Decl.h:3911
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:678
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3688
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3513
const Type * getTypeForDecl() const
Definition Decl.h:3538
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3547
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:913
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6177
A container of type source information.
Definition TypeBase.h:8265
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8276
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBooleanType() const
Definition TypeBase.h:9017
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isRValueReferenceType() const
Definition TypeBase.h:8563
bool isVoidPointerType() const
Definition Type.cpp:712
bool isArrayType() const
Definition TypeBase.h:8630
bool isPointerType() const
Definition TypeBase.h:8531
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9174
bool isReferenceType() const
Definition TypeBase.h:8555
bool isEnumeralType() const
Definition TypeBase.h:8662
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9005
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8708
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8559
bool isBitIntType() const
Definition TypeBase.h:8796
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8654
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isMemberPointerType() const
Definition TypeBase.h:8612
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9023
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition Type.cpp:4904
bool isPointerOrReferenceType() const
Definition TypeBase.h:8535
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8527
bool isVectorType() const
Definition TypeBase.h:8670
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9107
bool isNullPtrType() const
Definition TypeBase.h:8924
bool isRecordType() const
Definition TypeBase.h:8658
QualType getUnderlyingType() const
Definition Decl.h:3617
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
QualType desugar() const
Definition Type.cpp:4041
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1210
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:787
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5982
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3940
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2907
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2800
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Represents a GCC generic vector type.
Definition TypeBase.h:4175
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Extern
Definition Specifiers.h:251
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:449
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5890
@ Enum
The "enum" keyword.
Definition TypeBase.h:5904
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5865
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5883
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2247
CharacterLiteralKind
Definition Expr.h:1603
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5351
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3276
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11956
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11952
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11945
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11942
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11942
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13001
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13108
A stack object to be created when performing template instantiation.
Definition Sema.h:13197
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13357
NamedDecl * Previous
Definition Sema.h:354
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009